[llvm] [SeparateConstOffsetFromGEP] Stop distributing sext/zext over lossy trunc (PR #221381)
Fujun Han via llvm-commits
llvm-commits at lists.llvm.org
Wed Sep 9 04:11:12 PDT 2026
Peter9606 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.)
You're right, thanks for the counter-example — proving the trunc of the sum
lossless says nothing about the operands once the constant is split out.
Reworked: with a pending sext/zext, find() now only traces through a trunc
when the truncated value is entirely constant, or when it is an add with an
immediate constant operand and known bits prove that both the sum and the
remaining operand survive the trunc+ext round trip (the constant is then
exactly their difference and fits by construction; zext additionally
requires it to be non-negative). Your example is added as
@sext_of_lossy_operand and no longer transforms.
Also dropped the triple (using the <lower-gep> variant like the other tests
in this directory) and the addrspace(1).
https://github.com/llvm/llvm-project/pull/221381
More information about the llvm-commits
mailing list