Issue 243661
Summary [flang] Wrong code with `-mllvm -inline-all`: a pointer to a TARGET dummy is assumed not to alias the caller's actual argument
Labels miscompilation, flang:fir-hlfir
Assignees
Reporter vzakhari
    After FIR inlining, flang assumes that an access through a pointer cannot reach a variable of the caller that does not have the TARGET attribute. That is not true while the inlined procedure runs: the procedure can point the pointer at its TARGET dummy argument, which is associated with the caller's variable. The TBAA tags built from this assumption make LLVM forward a stale value, and `fir::AliasAnalysis::alias()` returns `NoAlias` for the same situation.

The results below are from flang built from llvm-project `main` at b4dc88dfc6921e567b455fefc903c20dbef7fab3. The debug traces are from a debug build whose `AliasAnalysis.{h,cpp}`, `AddAliasTags.cpp` and `Inliner.cpp` are identical to that revision.

## Wrong result

`repro.f90`:

```fortran
module m
  integer, target :: other = 0
contains
  subroutine callee(x, q, c)
    integer, target :: x
 integer, pointer :: q
    logical :: c
    if (c) then
      q => x
 else
      q => other
    end if
    q = 0
  end subroutine
end module

subroutine caller(j, p, c, r)
  use m
  integer :: j
  integer, pointer :: p
  logical :: c
  integer :: r
  j = 1
  call callee(j, p, c)
  r = j
end subroutine
```

`main.f90`, compiled separately so that `caller` is not inlined into the main program:

```fortran
program main
 interface
    subroutine caller(j, p, c, r)
      integer :: j
 integer, pointer :: p
      logical :: c
      integer :: r
    end subroutine
  end interface
  integer :: j, r
  integer, pointer :: p => null()
  call caller(j, p, .true., r)
  print *, r
end program
```

```console
$ flang -c main.f90
$ flang -O2 -mllvm -inline-all -c repro.f90
$ flang main.o repro.o && ./a.out
 1
```

The expected output is `0`. The program prints `0` when `repro.f90` is compiled with `-O0`, `-O2`, `-O3` or `-O0 -mllvm -inline-all`, and `1` with `-O2 -mllvm -inline-all` or `-O3 -mllvm -inline-all`. Adding `-mllvm -enable-tbaa=false` to `-O2 -mllvm -inline-all` gives `0` again. Declaring `j` ALLOCATABLE in `caller` and in the interface, and allocating it in the main program, also prints `1`.

### Why the result must be 0

`callee` may point `q` at `x` because `x` has the TARGET attribute. The actual argument `j` does not have it, so the pointer association becomes undefined when `callee` returns (Fortran 2023 15.5.2.5, paragraph 11, and 19.5.2.5, item (10)). While `callee` runs, though, `q` is associated with `x`, and so with `j`; the informative text in Fortran 2023 C.11.4, paragraph 5, says so explicitly. `q` is argument associated with the caller's `p`. So `q = 0` defines `j`, and `r = j` must store 0. The program never references `p` after the call.

### What goes wrong

The LLVM IR of `caller` (`flang -O2 -mllvm -inline-all -S -emit-llvm repro.f90`) stores the constant 1 into `r`:

```llvm
define void @caller_(ptr noalias captures(none) initializes((0, 4)) %0, ptr nofree writeonly captures(none) initializes((0, 24)) %1, ptr noalias nofree readonly captures(none) %2, ptr noalias nofree writeonly captures(none) initializes((0, 4)) %3) local_unnamed_addr #0 {
 store i32 1, ptr %0, align 4, !tbaa !14
  %5 = load i32, ptr %2, align 4, !tbaa !20
  %.not = icmp eq i32 %5, 0
  %spec.select = select i1 %.not, ptr @_QMmEother, ptr %0
  store ptr %spec.select, ptr %1, align 1, !tbaa !26
 ...
  store i32 0, ptr %spec.select, align 4, !tbaa !28
  store i32 1, ptr %3, align 4, !tbaa !30
  ret void
}
...
!14 = !{!15, !15, i64 0}
!15 = !{!"dummy arg data/_QFcallerEj", !16, i64 0}
!16 = !{!"dummy arg data", !17, i64 0}
!17 = !{!"any data access", !18, i64 0}
!18 = !{!"any access", !19, i64 0}
!19 = !{!"Flang function root _QPcaller"}
...
!28 = !{!29, !29, i64 0}
!29 = !{!"target data", !17, i64 0}
```

`j = 1` is tagged `dummy arg data/_QFcallerEj`, and `q = 0` is tagged `target data`. Both tags are in the caller's tree, under `any data access`, so TBAA says that the two stores do not alias, and LLVM forwards the 1 to `r = j`.

`AddAliasTags` takes `q = 0` for an access through the caller's dummy argument `p`. Its `-debug-_only_=fir-add-alias-tags` trace for that store is:

```
Analysing fir.store %c0_i32 to %17 : !fir.ptr<i32>
Got source <block argument> of type '!fir.ref<!fir.box<!fir.ptr<i32>>>' at index: 1 SourceKind: Argument Type: !fir.ref<!fir.box<!fir.ptr<i32>>>  following data AccessPath: [PointerDeref] {Pointer}
```

So the store gets the caller's `target data` tag, which [the dummy argument rules](https://github.com/llvm/llvm-project/blob/b4dc88dfc6921e567b455fefc903c20dbef7fab3/flang/lib/Optimizer/Transforms/AddAliasTags.cpp#L698-L717) keep apart from the caller's non-TARGET dummy `j`. That separation is right for the caller's own accesses, but not for an access made by the inlined `callee`.

## Wrong `alias()` answers

`fir::AliasAnalysis::alias()` has the same problem. The FIR below is what `flang -O2 -mllvm -inline-all` produces for the following source (the input of `flang-licm`), with `test.ptr` labels added. Here `j` is ALLOCATABLE, which is needed for the second wrong answer.

```fortran
subroutine caller(j, p)
  integer, allocatable :: j
  integer, pointer :: p
  call callee(j, p)
contains
 subroutine callee(x, q)
    integer, target :: x
    integer, pointer :: q
    q => x
    q = 0
  end subroutine
end subroutine
```

```mlir
// RUN: fir-opt %s -pass-pipeline='builtin.module(func.func(test-fir-alias-analysis))' \
// RUN:   --mlir-disable-threading -o /dev/null 2>&1

func.func @_QPcaller(%arg0: !fir.ref<!fir.box<!fir.heap<i32>>> {fir.bindc_name = "j"}, %arg1: !fir.ref<!fir.box<!fir.ptr<i32>>> {fir.bindc_name = "p"}) {
  %c0_i32 = arith.constant 0 : i32
  %0 = fir.dummy_scope : !fir.dscope
 %1 = fir.declare %arg0 dummy_scope %0 arg 1 uniq_name("_QFcallerEj") fortran_attrs<allocatable> : (!fir.ref<!fir.box<!fir.heap<i32>>>, !fir.dscope) -> !fir.ref<!fir.box<!fir.heap<i32>>>
  %2 = fir.declare %arg1 dummy_scope %0 arg 2 uniq_name("_QFcallerEp") fortran_attrs<pointer> : (!fir.ref<!fir.box<!fir.ptr<i32>>>, !fir.dscope) -> !fir.ref<!fir.box<!fir.ptr<i32>>>
  %3 = fir.load %1 : !fir.ref<!fir.box<!fir.heap<i32>>>
  %4 = fir.box_addr %3 {test.ptr = "j.data"} : (!fir.box<!fir.heap<i32>>) -> !fir.heap<i32>
  %5 = fir.convert %4 : (!fir.heap<i32>) -> !fir.ref<i32>
  %6 = fir.dummy_scope : !fir.dscope
  %7 = fir.declare %2 dummy_scope %6 arg 2 uniq_name("_QFcallerFcalleeEq") fortran_attrs<pointer> : (!fir.ref<!fir.box<!fir.ptr<i32>>>, !fir.dscope) -> !fir.ref<!fir.box<!fir.ptr<i32>>>
  %8 = fir.declare %5 dummy_scope %6 arg 1 uniq_name("_QFcallerFcalleeEx") fortran_attrs<target> {test.ptr = "callee.x"} : (!fir.ref<i32>, !fir.dscope) -> !fir.ref<i32>
  %9 = fir.embox %8 : (!fir.ref<i32>) -> !fir.box<!fir.ptr<i32>>
  fir.store %9 to %7 : !fir.ref<!fir.box<!fir.ptr<i32>>>
  %10 = fir.load %7 : !fir.ref<!fir.box<!fir.ptr<i32>>>
  %11 = fir.box_addr %10 {test.ptr = "q.tgt"} : (!fir.box<!fir.ptr<i32>>) -> !fir.ptr<i32>
  fir.store %c0_i32 to %11 : !fir.ptr<i32>
  return
}
```

Output:

```
Testing : "_QPcaller"
j.data#0 <-> callee.x#0: MustAlias
j.data#0 <-> q.tgt#0: NoAlias
callee.x#0 <-> q.tgt#0: NoAlias
```

Both `NoAlias` answers should be `MayAlias`: `q.tgt` is the address that `q = 0` stores to, which is `j`'s data. The two answers have different causes. In the trace excerpts below (`-debug-_only_=fir-alias-analysis`), `...` marks text I removed.

**`j.data` vs `q.tgt`: the pointer rule, applied with the caller's attributes.**

```
AliasAnalysis::alias
  lhs: %4 = fir.box_addr %3 {test.ptr = "j.data"} : (!fir.box<!fir.heap<i32>>) -> !fir.heap<i32>
 lhsSrc: <block argument> of type '!fir.ref<!fir.box<!fir.heap<i32>>>' at index: 0 SourceKind: Argument ... AccessPath: [AllocDeref] {}
  rhs: %11 = fir.box_addr %10 {test.ptr = "q.tgt"} : (!fir.box<!fir.ptr<i32>>) -> !fir.ptr<i32>
  rhsSrc: <block argument> of type '!fir.ref<!fir.box<!fir.ptr<i32>>>' at index: 1 SourceKind: Argument ... AccessPath: [PointerDeref] {Pointer}
j.data#0 <-> q.tgt#0: NoAlias
```

`q.tgt` has the same source as the store in the TBAA case: a dereference of the caller's `p`. `j.data` is defined before the inlined code, so the walk from it never meets the TARGET declaration of `x`, and its source has no attributes. The [pointer rule](https://github.com/llvm/llvm-project/blob/b4dc88dfc6921e567b455fefc903c20dbef7fab3/flang/lib/Optimizer/Analysis/AliasAnalysis.cpp#L891-L905) (a pointer reaches only TARGET or POINTER objects) therefore does not apply, and the query ends in `NoAlias`. With a non-allocatable `j` this answer is `NoAlias` too.

**`callee.x` vs `q.tgt`: the scope-aware refinement lets the caller's pair decide.** The base query answers `MayAlias`, because the walk from `callee.x` picks up the TARGET attribute of `x`. Then the [refinement in `alias(mlir::Value, mlir::Value)`](https://github.com/llvm/llvm-project/blob/b4dc88dfc6921e567b455fefc903c20dbef7fab3/flang/lib/Optimizer/Analysis/AliasAnalysis.cpp#L750-L787), added in https://github.com/llvm/llvm-project/pull/201216, compares the declarations that both walks crossed in the same scope:

```
AliasAnalysis::alias
  lhs: %8 = fir.declare %5 dummy_scope %6 arg 1 uniq_name("_QFcallerFcalleeEx") fortran_attrs<target> ...
 lhsSrc: <block argument> of type '!fir.ref<!fir.box<!fir.heap<i32>>>' at index: 0 SourceKind: Argument ... AccessPath: [AllocDeref] {Target}
  rhs: %11 = fir.box_addr %10 {test.ptr = "q.tgt"} : (!fir.box<!fir.ptr<i32>>) -> !fir.ptr<i32>
  rhsSrc: <block argument> of type '!fir.ref<!fir.box<!fir.ptr<i32>>>' at index: 1 SourceKind: Argument ... AccessPath: [PointerDeref] {Pointer}
  aliasing because pointer dereference may reach target/pointer

AliasAnalysis::alias
  lhs: %8 = fir.declare %5 dummy_scope %6 arg 1 uniq_name("_QFcallerFcalleeEx") fortran_attrs<target> ...
  lhsSrc: %8 = fir.declare %5 dummy_scope %6 arg 1 uniq_name("_QFcallerFcalleeEx") fortran_attrs<target> ... AccessPath: [] {Target}
  rhs: %11 = fir.box_addr %10 {test.ptr = "q.tgt"} : (!fir.box<!fir.ptr<i32>>) -> !fir.ptr<i32>
  rhsSrc: %7 = fir.declare %2 dummy_scope %6 arg 2 uniq_name("_QFcallerFcalleeEq") fortran_attrs<pointer> ... AccessPath: [PointerDeref] {Pointer}
  aliasing because pointer dereference may reach target/pointer

AliasAnalysis::alias
  lhs: %8 = fir.declare %5 dummy_scope %6 arg 1 uniq_name("_QFcallerFcalleeEx") fortran_attrs<target> ...
  lhsSrc: %1 = fir.declare %arg0 dummy_scope %0 arg 1 uniq_name("_QFcallerEj") fortran_attrs<allocatable> ... AccessPath: [AllocDeref] {}
  rhs: %11 = fir.box_addr %10 {test.ptr = "q.tgt"} : (!fir.box<!fir.ptr<i32>>) -> !fir.ptr<i32>
  rhsSrc: %2 = fir.declare %arg1 dummy_scope %0 arg 2 uniq_name("_QFcallerEp") fortran_attrs<pointer> ... AccessPath: [PointerDeref] {Pointer}
  no alias via scoped-origin refinement
callee.x#0 <-> q.tgt#0: NoAlias
```

The first call is the base query. The second compares `callee`'s pair, TARGET `x` against POINTER `q`, and answers `MayAlias`. The third compares the caller's pair, ALLOCATABLE `j` without TARGET against POINTER `p`, and answers `NoAlias`. Because any pair that answers `NoAlias` decides the query, the result is `NoAlias`. As with the TBAA tags, the caller's pair holds for the caller's own accesses but not for accesses made by the inlined `callee`. With a non-allocatable `j`, this query answers `MayAlias`.

## Scope

FIR inlining happens only with `-mllvm -inline-all` ([`Inliner.cpp`](https://github.com/llvm/llvm-project/blob/b4dc88dfc6921e567b455fefc903c20dbef7fab3/flang/lib/Optimizer/Dialect/Inliner.cpp#L12-L25)), so that option is needed today. The wrong result above comes from the TBAA tags. The wrong `alias()` answers are visible to FIR passes that run after the inliner, such as `flang-licm`, which checks loop invariance with `getModRef`. I have not found a program in which the `alias()` answers alone change the result. The refinement was added in https://github.com/llvm/llvm-project/pull/201216. The first `alias()` answer and the TBAA tags do not go through it.

## Possible directions

Both problems miss the same fact: inside the inlined code, the caller's `j` is associated with a TARGET dummy, so pointers can reach it.

- When a function contains inlined procedures, a variable whose data address reaches a TARGET dummy declaration in a nested `fir.dummy_scope` (in the FIR above, `%8`, the `fir.declare` of `x`) could be treated as a TARGET wherever the pointer rule is applied: in `alias()` and in `AddAliasTags`. In `AddAliasTags`, accesses to `j` would then get a tag that conflicts with `target data`.
- The refinement should not let a pair from an outer scope answer `NoAlias` when a pair from a scope closer to the accesses allows aliasing, as `callee`'s TARGET `x` and POINTER `q` do here.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to