| Issue |
241605
|
| Summary |
[AArch64] Writes to global register variables in -ffixed-xN registers are hoisted and speculated (MachineLICM, early-ifcvt, ccmp)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
twcclegg
|
Writes to reserved physical registers are erroneously executed too early or
unconditionally. Having a global register variable with `-ffixed-xN` changes
program behavior. `-O0` is correct, and GCC has no such issue.
Compiler Explorer (clang trunk `-O2`, GCC trunk `-O2`, clang trunk `-O0`):
https://godbolt.org/z/8WMv3qGKj
```c
// clang -O2 --target=aarch64 -ffixed-x21 -ffixed-x22
register unsigned eax __asm__("w21");
register unsigned ecx __asm__("w22");
extern unsigned mem[16];
void ext(void);
// 1. post-RA MachineLICM: `mov w21, #7` is hoisted above the loop, so the first
// iteration stores 7 instead of the previous value of w21.
void licm(unsigned n) { for (unsigned i = 0; i < n; i++) { mem[i] = eax; eax = 7; } }
// 2. early-ifcvt: the branch becomes a csel and `mov w21, w1` runs on both paths.
unsigned ifcvt(unsigned a, unsigned b) { unsigned r = 3; if (a) { eax = b; r = b + 1; } return r; }
// 3. AArch64ConditionalCompares: `add w21, w1, #1` runs even when a != 5.
// Shown with -mllvm -aarch64-stress-ccmp; in larger functions the cost model
// allows the conversion without it.
void ccmp(unsigned a, unsigned b) { if (a == 5) { eax = b + 1; if (ecx == b) ext(); } }
```
Output from trunk (fe5542793):
```
licm: mov w21, #7 // before the loop
...
str w21, [x8], #4 // loop body stores 7 on every iteration
ifcvt: mov w21, w1 // unconditional
csinc w0, w8, w1, eq
ccmp: cmp w0, #5
add w21, w1, #1 // unconditional
ccmp w22, w1, #0, eq
```
Each goes away with the matching flag: `-mllvm -disable-postra-machine-licm`,
`-mllvm -disable-early-ifcvt`, `-mllvm -aarch64-enable-ccmp=false`.
Cause: each pass treats a physical-register def as movable if the register is not
live where the instruction lands. Reserved registers never appear in block live-in
lists, so their defs always look movable.
- `MachineLICMImpl::ProcessMI` / `HoistRegionPostRA`
- `SSAIfConv::InstrDependenciesAllowIfConv`
- `SSACCmpConv::canSpeculateInstrs`
The Clang manual says global register variables are supported only in
non-allocatable registers (see #116514). `-ffixed-xN` makes the register
non-allocatable, so this should be a supported case.
I have a small patch (three checks, one per pass, plus a test) and can open a PR.
Found while keeping guest registers in x21-x28 in a static recompiler. Also seen
with Apple clang 21.0.0.
Disclosure: I used Claude to discover this and help bisect the passes, reduce the
reproducer. I have reviewed and reproduced everything here.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs