llvm / llvm/llvm-project

[LoongArch] 128bit cmpxchg using sc.q instruction may return a corrupted value on CAS failure

Open
#210,431 5 comments 0 reactions 0 assignees View on GitHub
backend:loongarch miscompilation
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Currently, 128bit cmpxchg using sc.q instruction (implemented in https://github.com/llvm/llvm-project/pull/116771) generates the following pattern:

```
ll.d
dbar
ld.d

# jump to .Lfail if not equal to expected value

# sc.q and jump depend on it

.Lfail:
dbar
```

https://github.com/llvm/llvm-project/blob/d982e0499b7f780279c435403b8249d7c3812cae/llvm/test/CodeGen/LoongArch/ir-instruction/atomic-cmpxchg-128.ll#L25-L42

IIUC, this allows returning a corrupted value when the comparison fails because the value can be modified between ll.d and ld.d.
(dbar that located between them guarantees that ld.d doesn't read before ll.d, but cannot guarantee that no writes from other cores will occur between them.)

To implement this correctly, you need to use `sc.q` to write back the loaded value when the comparison fails, and if that fails, you need to retry the loop. (AArch64's LL/SC-based 128-bit CAS is also implemented using this way.)

```diff
; LA64-SCQ-NEXT: .LBB0_3:
- ; LA64-SCQ-NEXT: dbar 20
+ ; LA64-SCQ-NEXT: move $a7, $a5
+ ; LA64-SCQ-NEXT: sc.q $a7, $a6, $a0
+ ; LA64-SCQ-NEXT: beq $a7, $zero, .LBB0_1
; LA64-SCQ-NEXT: .LBB0_4:
```

cc @tangaac (author of https://github.com/llvm/llvm-project/pull/116771)
cc @heiher @SixWeining (reviewers of https://github.com/llvm/llvm-project/pull/116771)

Contributor guide

Open the contributing guide

Research direction

Start with llvm/test/CodeGen/LoongArch/ir-instruction/atomic-cmpxchg-128.ll around lines 25-42 and inspect the generated 128-bit cmpxchg sequence. Reproduce or review the test output, then ensure the CAS-failure path preserves the loaded value and retries when the sc.q write-back fails; update the test expectations accordingly.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.