llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[InstCombine] Dead disjunct not removed when implied false by a later conjunct

Open mariiakrasniuk opened this issue 1 month ago • 1 comments

InstCombine does not remove a disjunct that a later conjunct in the same logical-and chain proves false.

define i1 @src(i32 %a, i32 %b, i32 %c) {
  %c0 = icmp ne i32 %c, 0
  %c1 = icmp slt i32 %b, 1
  %or = select i1 %c0, i1 true, i1 %c1
  %m  = and i32 %a, 8
  %z  = icmp eq i32 %m, 0
  %a1 = select i1 %or, i1 %z, i1 false
  %c2 = icmp sgt i32 %b, 1
  %r  = select i1 %a1, i1 %c2, i1 false
  ret i1 %r
}

The value is (%c0 || %b < 1) && %z && %b > 1. For the result to be true, %b > 1 must hold, which makes %b < 1 false, so the %c1 disjunct cannot affect the final result and %or can be replaced with %c0 in this context:

define i1 @tgt(i32 %a, i32 %b, i32 %c) {
  %c0 = icmp ne i32 %c, 0
  %m  = and i32 %a, 8
  %z  = icmp eq i32 %m, 0
  %a1 = select i1 %c0, i1 %z, i1 false
  %c2 = icmp sgt i32 %b, 1
  %r  = select i1 %a1, i1 %c2, i1 false
  ret i1 %r
}

The fold does fire when the implying condition is adjacent to the disjunction. Removing the unrelated %z conjunct is enough:

define i1 @adjacent(i32 %b, i32 %c) {
  %c0 = icmp ne i32 %c, 0
  %c1 = icmp slt i32 %b, 1
  %or = select i1 %c0, i1 true, i1 %c1
  %c2 = icmp sgt i32 %b, 1
  %r  = select i1 %or, i1 %c2, i1 false
  ret i1 %r
}

InstCombine simplifies this one as expected, so the implied-condition reasoning appears not to look past an intervening conjunct in the logical-and chain.

Proof: https://alive2.llvm.org/ce/z/yuhN5q

mariiakrasniuk avatar Oct 22 '26 17:10 mariiakrasniuk

Hi, I think this optimization can be generalized to:

((X ? true : b <s n) ? Y : false) ? b >s n : false ⇒ (X ? Y : false) ? b >s n : false

https://alive2.llvm.org/ce/z/pwJYJj

hiandgodblessyou avatar Oct 31 '26 04:10 hiandgodblessyou