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

    <tr>
        <th>Summary</th>
        <td>
            Invalid optimisation: `atomicrmw xchg` turned into `atomic store`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

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

    <tr>
      <th>Reporter</th>
      <td>
          RalfJung
      </td>
    </tr>
</table>

<pre>
    This is a sibling issue to https://github.com/llvm/llvm-project/issues/56450: LLVM will sometimes replace `atomicrmw xchg` by `atomic store`, specifically when the ordering is relaxed or release, and the result of the `xchg` is unused.

However, replacing an RMW by a non-RMW operation like is not sound under the C++ memory model (and LLVM does not seem to implement a fundamentally different model in that regard). Here's a counterexample using pseudocode notation:
```
Y:=1 rlx
fence(rel)
SWAP(X,0,rlx)
fence(acq)
a := Z rlx
||
Z:=1 rlx
fence(rel)
SWAP(X,0,rlx)
fence(acq)
b := Y rlx
```
One of the two SWAP has to read-from the other. This is because two RMWs cannot both read-from the same store (the implicit initial store of 0). Without loss of generality, let's assume the SWAP in the 2nd thread reads-from the first. Therefore we now have a synchronization edge from the fence(rel) in the first thread to the fence(acq) in the 2nd thread. Therefore `b` must be 1. (In the symmetric case, `a` must be 1.)

After the optimization, it is possible for both `a` and `b` to be 0. This means the optimization introduced new program behavior, and is therefore wrong.

(Thanks to Ori Lahav and Jeehoon Kang.)
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy0Vd-P2zYM_muUF-ICW0mc5MEP9wOHtrtDh1uxW_smS7StVRYzSU4u--sHynGvt_ZpwIDAsSWR30d-FKlitJ1HrMXmRmzuFmpMPYX6Sbn2w-i7RUPmXH_qbQQbQUG0jbO-AxvjiJAI-pQOUayuhbwX8r6zqR-bpaZByHvnjvPf1SHQn6iTkPfZMgp5v6nWm0KsruHh4fdHOFnnINKAyQ4YIeDBKY0g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