<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/107263>107263</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            clang OpenMP hello world segfault
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          jakub-homola
      </td>
    </tr>
</table>

<pre>
    Hello,

consider the following code -- it is a simple OpenMP hello world with an infinite loop:
```
#include <cstdio>
#include <omp.h>

int main()
{
    printf("Max threads: %d\n", omp_get_max_threads());
 #pragma omp parallel
    {
        printf("Hello world from thread %d out of %d\n", omp_get_thread_num(), omp_get_num_threads());
 while(true) ;
    }
    printf("End of program\n");

 return 0;
}
```

Compile with
```
clang++ -O2 -fopenmp source.cpp -o program.x
```
and run.

Expected output (8 threads):
```
Max threads: 8
Hello world from thread 0 out of 8
Hello world from thread 1 out of 8
Hello world from thread 2 out of 8
Hello world from thread 3 out of 8
Hello world from thread 4 out of 8
Hello world from thread 5 out of 8
Hello world from thread 6 out of 8
Hello world from thread 7 out of 8
```
(or in some other random order). Then it should hang due to the infinite loops.

Actual output:
```
Max threads: 8
Hello world from thread 0 out of 8
Hello world from thread 5 out of 8
Hello world from thread 5 out of 8
Hello world from thread 3 out of 8
Hello world from thread 3 out of 8
Hello world from thread 4 out of 8
Hello world from thread 4 out of 8
Hello world from thread 1 out of 8
Hello world from thread 1 out of 8
Hello world from thread 2 out of 8
Segmentation fault (core dumped)
```
This is obviously wrong. One thing is the segfault. Other thing is that more lines are printed than expected -- some threads print twice, some don't print at all; I never saw a thread print 3 times.

Using -O1, -O2 or -O3 creates this error. Using -O0, the program runs fine just as expected.

The issue occurs on multiple machines, I tried clang versions 16.0 through 18.1, all have the issue.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy8VkuP4zYT_DX0pSFBpvw86DBP7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