Issue 234360
Summary [flang] TRIM of a character variable allocates a heap temporary
Labels flang
Assignees cenewcombe
Reporter cenewcombe
    `TRIM(x)` is lowered to the runtime call `_FortranATrim`, which heap-allocates the result; the caller then frees it. This happens for every `trim` that is not inside a character comparison (those are handled by `ExpressionSimplification`, #154593). For example:

```fortran
subroutine s(a, b, n)
  character(len=*), intent(in) :: a, b
  integer, intent(in) :: n
  character(len=64) :: name
  name = trim(a) // '/' // trim(b)
  call sub(trim(name), n)
end subroutine
```

`flang -O2 -emit-llvm -S` gives three `_FortranATrim` calls and three `free`s.

When the operand is a character variable, `TRIM(x)` is equivalent to the substring `x(1:LEN_TRIM(x))`, which does not need a copy. Lowering
`hlfir.char_trim` of a variable to a substring with an inline `LEN_TRIM` would avoid the runtime call and the heap allocation; a consumer that needs its own copy (actual argument) would get a stack temporary from bufferization instead, which LLVM can often remove.

In SPEC CPU2017 527.cam4_r this pattern (`physics_update`, a diagnostic label built on every call) accounts for about 1% of runtime on x86-64: `_FortranATrim` plus the associated `malloc`/`free` and descriptor setup.

Assisted-by: Copilot
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to