Issue 244760
Summary [flang][OpenMP] DIST_SCHEDULE on composite DISTRIBUTE PARALLEL DO [SIMD] is evaluated inside the PARALLEL region
Labels flang:openmp
Assignees chichunchen
Reporter chichunchen
    Flang lowers composite DISTRIBUTE PARALLEL DO [SIMD] as `omp.parallel { omp.distribute { omp.wsloop { [omp.simd] ... } } }`. In `genCompositeDistributeParallelDo` and `genCompositeDistributeParallelDoSimd` (`flang/lib/Lower/OpenMP/OpenMP.cpp`), it generates the DISTRIBUTE clauses after it creates `omp.parallel`. As a result, the DIST_SCHEDULE chunk-size _expression_ is emitted inside the parallel region.

DIST_SCHEDULE is split to the DISTRIBUTE leaf. A clause _expression_ on a compound construct "is evaluated immediately before the construct to which the clause has been split" (OpenMP 5.2 §17.2, 6.0 §19.2). In the source, DISTRIBUTE encloses PARALLEL, so the _expression_ is outside PARALLEL. Emitting it inside `omp.parallel` has two effects:

1. **Wrong variant.** A DECLARE VARIANT call or METADIRECTIVE in the _expression_ sees PARALLEL in its construct context and can select the wrong variant.
2. **Redundant evaluation.** Every thread of the parallel region evaluates the _expression_, instead of once per team. The spec does not require a single evaluation, but the extra evaluations are wasted work.

### Reproducer

```fortran
module b
contains
  pure integer function teams_chunk(n)
    integer, intent(in) :: n
    teams_chunk = n
  end function
  pure integer function parallel_chunk(n)
    integer, intent(in) :: n
    parallel_chunk = n
  end function
  pure integer function chunk(n)
    integer, intent(in) :: n
    !$omp declare variant(teams_chunk) match(construct={teams})
    !$omp declare variant(parallel_chunk) match(construct={parallel})
    chunk = n
  end function

  ! DIST_SCHEDULE is split to DISTRIBUTE: it sees TEAMS, not PARALLEL.
  subroutine composite(n, a)
    integer :: n, a(n), i
    !$omp teams distribute parallel do dist_schedule(static, chunk(n))
    do i = 1, n
      a(i) = i
    end do
  end subroutine

  subroutine composite_simd(n, a)
    integer :: n, a(n), i
    !$omp teams distribute parallel do simd dist_schedule(static, chunk(n))
    do i = 1, n
      a(i) = i
    end do
  end subroutine
end module
```

```console
$ flang -fc1 -fopenmp -fopenmp-version=52 -emit-hlfir repro.f90 -o -
```

| Procedure | Expected | Actual |
|---|---|---|
| `composite` | `teams_chunk`, evaluated in `omp.teams` before `omp.parallel` | `parallel_chunk`, evaluated inside `omp.parallel` |
| `composite_simd` | `teams_chunk`, evaluated in `omp.teams` before `omp.parallel` | `parallel_chunk`, evaluated inside `omp.parallel` |

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

Reply via email to