[InstCombine] Missed fold: a non-power-of-two `sdiv exact` compare
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, 24implies%xis divisible by24%q >u 4611686018427387903means%qis negative- for positive divisor
24,%q < 0iff%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:
Cis positive and not a power of twoKis 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: Could you please elaborate?
@EugeneZelenko thanks! Hope this new version is easy to read.
Should be handled by https://github.com/llvm/llvm-project/pull/76439.
Should be handled by #76439.
@dtcxzyw Hi Yingwei, the code in PR missed some generalized cases, do we have any plans to improve this?
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...
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)