<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/62057>62057</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
clang introduces undefined behavior into well-formed C++ program with infinite loop
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
gonzalobg
</td>
</tr>
</table>
<pre>
This program is well-formed and the C++ standard guarantees that a thread that reaches `block` will not execute any subsequent instructions, since the thread performs an [execution step] on every loop iteration (the atomic operation)](http://eel.is/c++draft/intro.progress#3.3).
Therefore, when `example(nullptr)` is called, the C++ standard guarantees that a null pointer will never be dereferenced.
However, clang ([godbolt](https://clang.godbolt.org/z/Tn46qv9ce)) removes the loop, causing the program to dereference a `nullptr`, therefore introducing _undefined behavior_ into a well-formed program. My assessment is that clang is incorrectly not inserting an `llvm.sideeffect` intrinsic inside the loop.
```cpp
#include <atomic>
void block() {
std::atomic<int> x = 0;
while (true) {
if (x.load(std::memory_order_relaxed) == 1)
break;
}
}
void example(int* data) {
block();
*data = 42;
}
int main() {
example(nullptr);
return 0;
}
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJyMVE1zozgQ_TXypSsUCEPMgUMcj2sve8s9JVADvSMkRhJ2PL9-SwJ_bfYwlMs2Uqtfv6fXLZyjXiPWrNiz4rARsx-MrXujfwtlmn7TGHmpPwZyMFnTWzECOTijUi-dsSNKEFqCHxDeGd8zvgfnhZbCSuhnYYX2iA78IDwI8INFIZc3i6Id0AEr00aZ9icrUziTUqCNB_zCdvYIQl_AzY3DXzNqD6Sdt3PryWjH-Ds40i1G8DXzhDZU5UBoYMV-SUNGg_M4seIARgOe0F5AGTMBebQi7jO-C2mENyO1YKZ1nfGKFQfGd4P3E8vfGD8yfkRUCTnGj-1CWVrRecaPpL01SZQJnWM8z5Oc8Sph6YGlb8v3x4AWO2Mx1H8eUAc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