llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[flang] Image selector in a subscript is silently ignored when lowering coindexed objects

Open JDPailleux opened this issue 2 weeks ago • 0 comments

Summary

When a coindexed object appears inside a subscript of another designator, e.g. a(n[k]), Flang lowering drops the image selector [k] and reads n from the local image. No diagnostic is emitted, so the program silently computes a wrong result.

This was found while reviewing the EVENT_QUERY lowering PR, where a check based on ExtractCoarrayRef only inspects the base of the argument's designator and therefore does not see a coindexed object nested in a subscript. The problem is not specific to EVENT_QUERY (see in #237317).

Reproducers and examples

subroutine q(k)
  integer :: k
  integer, save :: n[*]
  integer :: a(10), m
  m = a(n[k])
end subroutine
flang -fcoarray -S -emit-llvm repro.f90 -o -

  call void @llvm.memcpy.p0.p0.i32(ptr align 8 %3, ptr align 8 @_QFqEn, i32 24, i1 false)
  %7 = getelementptr { ptr, i64, i32, i8, i8, i8, i8 }, ptr %3, i32 0, i32 0
  %8 = load ptr, ptr %7, align 8
  %9 = load i32, ptr %8, align 4
  ...
  %15 = getelementptr nusw nuw i32, ptr %4, i64 %14
  ...
  call void @_QMprifPprif_event_query(ptr %6, ptr %5, ptr null)
  %20 = load i64, ptr %5, align 8
  %21 = trunc i64 %20 to i32
  store i32 %21, ptr %15, align 4

Other example :

call system_clock(count=a(n[k]))

Example with EVENT_QUERY

The generated code never reads k. It loads the subscript from the local n and uses it to index a. With EVENT_QUERY, the following compiles the same way, with the count stored into the element of a selected by the local n:

use iso_fortran_env, only: event_type
type(event_type), save :: ev[*]
integer, save :: n[*]
integer :: a(10)
call event_query(ev, a(n[k]))

An array element ev(n[k]) as EVENT and s(n[k]) as STAT are handled the same way.

Analysis

Any lowering path that looks for a coindexed object only through the base of a designator (for instance with ExtractCoarrayRef) will miss coindexed objects that appear in subscripts. The image selector is then lost, and the subscript expression is evaluated locally.

Related

  • #212777 (coarray access lowering)
  • Review comment by @MattPD in #237317

JDPailleux avatar Nov 16 '26 15:11 JDPailleux