| Issue |
239932
|
| Summary |
[X86] Wrong code: rotate of rotate fold overflows the i8 shift amount on non power of 2 integers such as i100 and i193
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
robinbishtt
|
## Summary
Two rotates written as `shl`/`lshr`/`or` on a non power of 2 integer for example i193 can give the wrong result in the X86 backend. A single rotate is always correct. `llc` is wrong at -O0, -O1 and -O2. Clang is wrong at -O0. Clang -O1 and above look correct, probably because InstCombine turns the pattern into `llvm.fshl` before it reaches the backend.
I found the cause an overflow in the rotate of rotate fold in `DAGCombiner::visitRotate` and have a fix with a regression test. I will open a PR that references this issue.
## Reproducer 1: C clang -O0 -std=c23
```c
#include <stdio.h>
volatile unsigned _BitInt(193) g = 1;
int main(void) {
unsigned _BitInt(193) a = g;
unsigned _BitInt(193) r = ((((a << 1u) | (a >> 192u)) << 184u) | (((a << 1u) | (a >> 192u)) >> 9u));
for (int i = 3; i >= 0; i--) printf("%016llx", (unsigned long long)(r >> (64 * i)));
printf("\n");
return 0;
}
```
Expected (2^185): `0000000000000000020000000000000000000000000000000000000000000000`
Actual at -O0 (clang 18 and clang 20): `0000000000000000000000000000000004000000000000000000000000000000` (bit 122 is set)
At -O2 clang 20 prints the expected value.
The program has no undefined behavior. The type is unsigned and every shift amount is below 193. I checked the expected values with Python big integers.
## Reproducer 2: LLVM IR wrong at llc -O0 and -O2
`f.ll`:
```llvm
target triple = "x86_64-pc-linux-gnu"
define void @f(ptr %in, ptr %out) {
%l = load i256, ptr %in, align 8
%a = trunc i256 %l to i193
%s1 = shl i193 %a, 1
%r1 = lshr i193 %a, 192
%rot1 = or i193 %s1, %r1
%s2 = shl i193 %rot1, 184
%r2 = lshr i193 %rot1, 9
%res = or i193 %s2, %r2
%z = zext i193 %res to i256
store i256 %z, ptr %out, align 8
ret void
}
```
`drv.c`:
```c
#include <stdio.h>
void f(unsigned long long *in, unsigned long long *out);
int main(void) {
unsigned long long in[4] = {1, 0, 0, 0}, out[4];
f(in, out);
printf("%016llx%016llx%016llx%016llx\n", out[3], out[2], out[1], out[0]);
return 0;
}
```
```
llc -O2 -filetype=obj f.ll -o f.o && gcc drv.c f.o -o drv && ./drv
```
Expected: `0000000000000000020000000000000000000000000000000000000000000000`
Actual (llc 20, both -O0 and -O2): `0000000000000000000000000000000004000000000000000000000000000000`
(I use `-filetype=obj` because a recent llc writes a `.prefalign` directive that older GNU assemblers reject.)
## Which widths and amounts fail
Each case is rot(rot(a, k1), k2) on iN, compared with Python on random inputs. Result with Ubuntu llc 18:
| Width | Amounts | Result |
|---|---|---|
| i193 | (1,184), (100,1) | wrong |
| i193 | (5,7) | correct |
| i200 | (1,191) | wrong |
| i255 | (5,7) | wrong |
| i150 | (1,141) | wrong |
| i150 | (5,7) | correct |
| i100 | (90,90) | wrong |
| i100 | (50,50) | correct |
| i96 | (90,90) | wrong |
| i129 | (100,100) | wrong |
| i128, i256, i85, i64 | large amounts | correct |
<details>
<summary>Script that produces this table (python3 repro.py /path/to/llc)</summary>
```python
import os, random, shutil, subprocess, sys
LLC = sys.argv[1]
CC = shutil.which("gcc") or shutil.which("clang")
random.seed(7)
os.makedirs("/tmp/rotrepro", exist_ok=True)
os.chdir("/tmp/rotrepro")
def run_case(W, k1, k2):
n = (W + 63) // 64 # 64-bit words used to pass the value
C = 64 * n
M = (1 << W) - 1
rotl = lambda v, k: ((v << k) & M) | (v >> (W - k))
load = (f" %a = trunc i{C} %l to i{W}\n" if C != W
else f" %a = bitcast i{W} %l to i{W}\n")
store = (f" %z = zext i{W} %res to i{C}\n" if C != W
else f" %z = bitcast i{W} %res to i{W}\n")
ir = f'''target triple = "x86_64-pc-linux-gnu"
define void @f(ptr %in, ptr %out) {{
%l = load i{C}, ptr %in, align 8
{load} %s1 = shl i{W} %a, {k1}
%r1 = lshr i{W} %a, {W - k1}
%rot1 = or i{W} %s1, %r1
%s2 = shl i{W} %rot1, {k2}
%r2 = lshr i{W} %rot1, {W - k2}
%res = or i{W} %s2, %r2
{store} store i{C} %z, ptr %out, align 8
ret void
}}
'''
open("t.ll", "w").write(ir)
open("d.c", "w").write(f'''#include <stdio.h>
#include <stdlib.h>
void f(unsigned long long *in, unsigned long long *out);
int main(int c, char **v) {{
unsigned long long in[{n}] = {{0}}, out[{n}];
for (int i = 0; i < {n}; i++) in[i] = strtoull(v[1 + i], 0, 16);
f(in, out);
for (int i = {n - 1}; i >= 0; i--) printf("%016llx", out[i]);
printf("\\n");
return 0;
}}''')
subprocess.run([LLC, "-O2", "-filetype=obj", "t.ll", "-o", "t.o"], check=True)
subprocess.run([CC, "d.c", "t.o", "-o", "t"], check=True)
for _ in range(3):
a = random.getrandbits(W)
args = [format((a >> (64 * i)) & (2**64 - 1), "x") for i in range(n)]
out = int(subprocess.run(["./t"] + args, capture_output=True, text=True).stdout.strip(), 16)
if out != rotl(rotl(a, k1), k2):
return False
return True
cases = [(193, 1, 184), (193, 100, 1), (193, 5, 7), (200, 1, 191), (255, 5, 7),
(150, 1, 141), (150, 5, 7), (100, 90, 90), (100, 50, 50), (96, 90, 90),
(129, 100, 100), (128, 100, 100), (256, 200, 100), (85, 80, 80), (64, 50, 50)]
bad = 0
for W, k1, k2 in cases:
ok = run_case(W, k1, k2)
bad += not ok
print(f"i{W} rot({k1},{k2}): {'OK' if ok else 'WRONG'}")
print(f"SUMMARY: {len(cases) - bad} OK, {bad} WRONG")
```
</details>
## Compiler versions
Ubuntu 24.04 x86-64, packages from apt.llvm.org. Same rotate pattern on random inputs, at widths 150, 193, 200, 255:
| Version | clang -O0 | clang -O1, -O2 | llc -O0 and -O2, IR test |
|---|---|---|---|
| 18.1.8 | wrong | correct | wrong |
| 20.1.8 | wrong | correct | wrong |
| 22.1.8 | wrong | correct | wrong |
| 23.1.6 (snapshot 2026-11-03) | wrong | correct | wrong |
## Root cause
`DAGCombiner::visitRotate` in `llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp` has a fold labelled `fold (rot* (rot* x, c2), c1)`. It merges two rotates into one with the amount `((c1 % BW) +/- (c2 % BW) + BW) % BW`. This math is done in the shift amount type (`ShiftVT`), which is 8 bits wide here, judging by the results. For BW = 193 the intermediate value can reach 3*193-2 = 577, so it wraps around. The wrap-around only matters when BW is not a power of 2, because 256 is a multiple of 128 and 256.
Example: a=1 with rot(1,184). 1 + 184 + 193 = 378, and 378 mod 256 = 122. So the code rotates by 122 instead of 185. Both reproducers print bit 122.
The rule "wrong when (c1 % BW) + (c2 % BW) + BW is 256 or more" matched all 15 cases in the table. It also predicted two extra cases I tried afterwards: i100 rot(90,90) is wrong, and i85 rot(80,80) is correct.
## Fix
This skips the fold when the amount math can overflow the shift amount type:
```diff
EVT ShiftVT = N1.getValueType();
+ // The amount arithmetic below is done in ShiftVT and can reach
+ // 3 * Bitsize - 2. If that does not fit in ShiftVT the result wraps
+ // around. This is harmless only when Bitsize is a power of 2 (the
+ // wrap-around is then a multiple of Bitsize), so skip the fold otherwise.
+ unsigned AmtBits = ShiftVT.getScalarSizeInBits();
+ APInt MaxAmt = APInt::getMaxValue(AmtBits);
+ bool MayOverflow = !isPowerOf2_32(Bitsize) && MaxAmt.ult(3 * Bitsize - 2);
+ if (MayOverflow || MaxAmt.ult(Bitsize))
+ return SDValue();
bool SameSide = (N->getOpcode() == NextOp);
```
Doing the arithmetic in a wider type and keeping the fold would also work. I picked the smaller change.
I built `llc` from `main` (LLVM 24.0.0git, Release, X86 only, cloned 2026-11-05) with this change and ran the 15 cases with `repro.py`.
<details>
<summary>Output: Ubuntu llc 18 versus llc built from main with the fix</summary>
```
== OLD (system llc 18)
i193 rot(1,184): WRONG
i193 rot(100,1): WRONG
i193 rot(5,7): OK
i200 rot(1,191): WRONG
i255 rot(5,7): WRONG
i150 rot(1,141): WRONG
i150 rot(5,7): OK
i100 rot(90,90): WRONG
i100 rot(50,50): OK
i96 rot(90,90): WRONG
i129 rot(100,100): WRONG
i128 rot(100,100): OK
i256 rot(200,100): OK
i85 rot(80,80): OK
i64 rot(50,50): OK
SUMMARY: 7 OK, 8 WRONG
== FIXED (llc 24.0.0git built from main + this change)
i193 rot(1,184): OK
i193 rot(100,1): OK
i193 rot(5,7): OK
i200 rot(1,191): OK
i255 rot(5,7): OK
i150 rot(1,141): OK
i150 rot(5,7): OK
i100 rot(90,90): OK
i100 rot(50,50): OK
i96 rot(90,90): OK
i129 rot(100,100): OK
i128 rot(100,100): OK
i256 rot(200,100): OK
i85 rot(80,80): OK
i64 rot(50,50): OK
SUMMARY: 15 OK, 0 WRONG
```
</details>
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs