Issue 243594
Summary [InstCombine] `-X / -Y --> X / Y` turns `sdiv poison, 1` into `sdiv poison, -1` (immediate UB)
Labels new issue
Assignees
Reporter arie2026
    `visitSDiv` folds `-X / -Y` to `X / Y` when known bits show `X != INT_MIN`. Known bits only describe non-poison values.
If X is poison and Y is -1, the source computes `sdiv poison, 1`, which is poison. The target computes `sdiv poison, -1`,
which is immediate UB.

Reproducer (`opt -passes=instcombine -S test.ll`):
```llvm
define i32 @f(i8 %a, i32 %y) {
  %x = zext i8 %a to i32
  %neg.x = sub i32 0, %x
 %neg.y = sub i32 0, %y
  %d = sdiv i32 %neg.x, %neg.y
  ret i32 %d
}
```

```llvm
define i32 @f(i8 %a, i32 %y) {
  %x = zext i8 %a to i32
  %d = sdiv i32 %x, %y
  ret i32 %d
}
```

Why this is wrong: for `%a = poison` and `%y = -1`, the source computes `%neg.y = 1` and returns `sdiv poison, 1` = poison.
The target executes `sdiv poison, -1`. LangRef (Poison Values) says that using poison as an operand "that has any values
that trigger undefined behavior" is immediate UB, and `INT_MIN / -1` is UB for `sdiv`.

```console
$ alive-tv test.ll tgt.ll
ERROR: Source is more defined than target
Example:
i8 %a = poison
i32 %y = #xffffffff (4294967295, -1)
Source:
i32 %neg.y = #x00000001 (1)
i32 %d = poison
Target:
i32 %d = UB triggered!
```

The in-tree test `sdiv_neg_neg_x_not_signmask` in `InstCombine/sdiv-canonicalize.ll` (X = `and i32 %a, 2147483647`,
`nsw` negations) CHECKs this fold, and alive2 rejects it the same way (`%a = poison`, `%y = -1`). Variants with `nsw`
negations or with X = `lshr i32 255, %a` also fail.

Expected: the known-bits condition is only used when X is known not to be poison, or the fold also requires Y != -1.

Notes: the fold is in `InstCombinerImpl::visitSDiv` (InstCombineMulDivRem.cpp, "-X / -Y --> X / Y, unless X == INT_MIN
and Y == -1"). The second disjunct (`nsw` negation of X and Y known != -1) looks fine. Possible fixes: add
`isGuaranteedNotToBePoison(NegOp0)` to the known-bits disjunct, or freeze X. This needs a poison dividend to show up.

Found with a mutation-based IR fuzzer. Triage, test-case minimization and parts of this write-up were assisted by
an LLM; verified the reproducer on b23814056.

Assisted-by: Claude (Anthropic)
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to