| Issue |
242250
|
| Summary |
[PowerPC] post-RA machine scheduler moves the epilogue's CR2-CR4 restore above a read of CR2
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
hazohelet
|
Live Reproducer: [https://godbolt.org/z/heGe3PxxE](<https://godbolt.org/z/heGe3PxxE>)
Compiling the following C code for `powerpc64le` with `clang -O2` and running it prints the wrong result.
```c
#include <stdio.h>
__attribute__((noinline)) int f(__int128 a, int n) {
int w = 0;
while (n--)
w = (w >= a) + (w >= a + 1) + (w >= a + 2) + (w >= a + 3);
return (w >= a) + (w >= a + 1) + (w >= a + 2) + (w >= a + 3);
}
static volatile int A = 0;
int main(void) { printf("%d\n", f(A, 1)); }
```
clang command:
```sh
clang --target=powerpc64le-linux-gnu -O2 repro.c && qemu-ppc64le ./a.out
```
Output (wrong):
```text
0
```
Expected (what -O0 prints, and what x86-64 prints):
```text
2
```
With `a = 0` the loop sets `w` to 1, so `f` returns (1 >= 0) + (1 >= 1) + (1 >= 2) + (1 >= 3) = 2.
`f` uses CR2, CR3 and CR4 (these are callee-saved IIRC), so it saves the caller's values in its prologue (`mfcr 12; stw 12, 8(1)`) and restores them in its epilogue. At the end of `f`, it looks like that restore (`mtcrf 56, 12`) is scheduled before instructions that still read `f`'s own CR2 and CR3 (bit 10 is CR2's EQ bit, bit 12 CR3's LT bit):
```asm
lwz 12, 8(1)
cmpld 3, 4
li 3, 1
mtcrf 56, 12 # CR2-CR4 restored here
crandc 22, 10, 1 # reads bit 10: the restored CR2, not f's
crnor 21, 22, 21
crand 22, 10, 0 # bit 10 again
cmpld 8, 4
isel 5, 0, 3, 21
crandc 21, 12, 10 # bits 12 and 10
```
With `-mllvm -enable-post-misched=false`, `lwz 12, 8(1)` and `mtcrf 56, 12` are the last instructions before `blr`.
Notes:
* `-O2`, `-O3`, `-Os` and `-Oz` are wrong (`-Os` and `-Oz` print 1); `-O0`, `-O1`, `-mcpu=pwr9` and `-mcpu=pwr10` are correct, and so is `powerpc64` (big-endian)
* `-mllvm -enable-post-misched=false` makes it correct
* Clang 22.1.8 and 23.1.2 are correct
clang version:
```text
clang version 24.0.0git (https://github.com/llvm/llvm-project 4e8f741d81620d640c4d25b9e78f327772e60ed7)
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs