https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128859
Bug ID: 128859
Summary: [OpenMP] wrong code: statement before doacross(sink:
omp_cur_iteration - 1) runs only in first inner
iteration
Product: gcc
Version: 17.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: middle-end
Assignee: unassigned at gcc dot gnu.org
Reporter: yqtian668 at gmail dot com
Target Milestone: ---
Created attachment 66218
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=66218&action=edit
patch and test
With `#pragma omp for ordered(N)` where N is larger than the collapse count,
the statement immediately before `#pragma omp ordered doacross(sink:
omp_cur_iteration - 1)` is executed only in the first iteration of the inner
(non-collapsed) loops.
```c
int a[64][64], b;
void
f (int n)
{
int i, j;
#pragma omp for ordered(2)
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
{
b++;
#pragma omp ordered doacross(sink: omp_cur_iteration - 1)
a[i][j] = b;
#pragma omp ordered doacross(source: omp_cur_iteration)
}
}
int
main ()
{
f (5);
if (b != 25)
__builtin_abort ();
return 0;
}
```
```sh
gcc -O2 -fopenmp t.c && OMP_NUM_THREADS=1 ./a.out
```
`b` is 5 instead of 25 (also at -O0). Tested with trunk
e32f3d31e252d378450484b3a9250631d8efb36b and GCC 13.3.
If the statement before the construct is a debug statement, it is the debug
marker that gets misplaced instead, so -g and -g0 differ. Writing `b++; ;`
gives b=25 with -g, b=5 with -g0, and `-fcompare-debug` fails.
In `expand_omp_ordered_sink`, for `fd->ordered > fd->collapse`, `gsi3` is the
last statement before the construct, and the block is split before it:
```c
else
{
gsi_prev (&gsi3);
e4 = split_block (gsi_bb (gsi3), gsi_stmt (gsi3));
}
```
so that statement moves into the block guarded by `if (.first != 0)`.
Splitting after `gsi3` (dropping the `gsi_prev`) guards only the
inserted statements. I have a patch with a libgomp runtime test.