[llvm] [SeparateConstOffsetFromGEP] Stop distributing sext/zext over lossy trunc (PR #221381)

Fabian Ritter via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 8 02:47:55 PDT 2026


ritter-x2a wrote:

Please correct me if I'm wrong, but effectively this fix relies on the assumption that `sext(trunc(a + b)) = sext(trunc(a)) + sext(trunc(b))` if `sext(trunc(a + b))` is a no-op, right?
But that's not the case if, for example (assuming we truncate to i8), `a` is `224` and `b` is `-100`. On the left-hand side, the trunc is a no-op since `a+b` is 124, but the right-hand side computes -132, I think.

That means the fix still transforms (with `-mtriple=x86_64-unknown-linux-gnu`)
```
define ptr @src(ptr %p, i1 %c) {
  %a = select i1 %c, i32 224, i32 227
  %sum = add nsw i32 %a, -100
  %t = trunc i32 %sum to i8
  %idx = sext i8 %t to i64
  %q = getelementptr i32, ptr %p, i64 %idx
  ret ptr %q
}
```

into

```
define ptr @tgt(ptr %p, i1 %c) {
  %a = select i1 %c, i32 224, i32 227
  %1 = trunc i32 %a to i8
  %2 = sext i8 %1 to i64
  %3 = getelementptr i32, ptr %p, i64 %2
  %q2 = getelementptr i8, ptr %3, i64 -400
  ret ptr %q2
}
```

...which is wrong, according to alive2: https://alive2.llvm.org/ce/z/p3wFAD
(Disclaimer: Claude helped me find the counter example.)

https://github.com/llvm/llvm-project/pull/221381


More information about the llvm-commits mailing list