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

[InstCombine] Missed fold: a non-power-of-two `sdiv exact` compare

Open zhengyang92 opened this issue 8 months ago • 6 comments

Reproducer

define i1 @src(i64 %x) {
entry:
  %q = sdiv exact i64 %x, 24
  %r = icmp ugt i64 %q, 4611686018427387903
  ret i1 %r
}

Expected

This is equivalent to:

define i1 @tgt(i64 %x) {
entry:
  %r = icmp slt i64 %x, 0
  ret i1 %r
}

Reason:

  • %q = sdiv exact %x, 24 implies %x is divisible by 24
  • %q >u 4611686018427387903 means %q is negative
  • for positive divisor 24, %q < 0 iff %x < 0

Alive2 verifies src => tgt. https://alive2.llvm.org/ce/z/TQeyKJ

What LLVM does

With LLVM trunk:

opt -S -passes='instcombine'

the function is left unchanged (https://godbolt.org/z/9EWjrnhYz)

LLVM already handles power-of-two divisors like https://godbolt.org/z/qchnqf3f4:

sdiv exact i64 %x, 8

Missed case

The missed case is:

icmp ugt (sdiv exact x, C), K

where:

  • C is positive and not a power of two
  • K is large enough that the comparison is true iff the quotient is negative

So the missing canonicalization is:

icmp ugt (sdiv exact %x, C_nonpow2), K_high
  -> icmp slt %x, 0

zhengyang92 avatar Mar 19 '26 03:03 zhengyang92

@zhengyang92: Could you please elaborate?

EugeneZelenko avatar Mar 19 '26 03:03 EugeneZelenko

@EugeneZelenko thanks! Hope this new version is easy to read.

zhengyang92 avatar Mar 19 '26 04:03 zhengyang92

Should be handled by https://github.com/llvm/llvm-project/pull/76439.

dtcxzyw avatar Mar 19 '26 12:03 dtcxzyw

Should be handled by #76439.

@dtcxzyw Hi Yingwei, the code in PR missed some generalized cases, do we have any plans to improve this?

zhengyang92 avatar Mar 20 '26 08:03 zhengyang92

Should be handled by #76439.

@dtcxzyw Hi Yingwei, the code in PR missed some generalized cases, do we have any plans to improve this?

Sure. IIRC it was blocked by some regressions...

dtcxzyw avatar Mar 22 '26 17:03 dtcxzyw

Hi @zhengyang92 @dtcxzyw, I think this optimization can be generalized like this. Thanks.

For integer type iN Let: INT_MAX_N = 2^(N-1) - 1 INT_MIN_N = -2^(N-1) MaxQ(C) = sdiv(INT_MAX_N, C) MinQ(C) = sdiv(INT_MIN_N, C)

0 <s C ∧ MaxQ(C) <=u K <u MinQ(C) |= icmp_ugt(sdiv_exact(x, C), K) ⇒ icmp_slt(x, 0)

hiandgodblessyou avatar Jun 08 '26 23:06 hiandgodblessyou