[InstCombine] Missed fold combining a range check with a masked equality
The range check below restricts %x to {-1, 0, 1}, while the masked equality requires its sign bit and low bit to be set. Only -1 satisfies both:
define i1 @src(i8 noundef %x) {
%offset = add i8 %x, 1
%in_range = icmp ult i8 %offset, 3
%masked = and i8 %x, -127
%bits = icmp eq i8 %masked, -127
%both = and i1 %in_range, %bits
ret i1 %both
}
Current trunk opt -O3 retains all six instructions (godbolt: https://godbolt.org/z/5EKWb5c6G). The expected result is (alive2: https://alive2.llvm.org/ce/z/KN9ASa):
define i1 @src(i8 noundef %x) {
%is_minus_one = icmp eq i8 %x, -1
ret i1 %is_minus_one
}
LLVM handles the two checks separately: one checks %x, the other checks %x & -127. It does not combine what they say about %x, so it misses that only -1 satisfies both. A possible fix is to combine the range check with the mask's requirement that %x be negative and odd.
The same failure to combine the checks occurs in RocksDB version_set.bc, in VersionStorageInfo::UpdateFilesByCompactionPri from llvm-opt-bench. Its final O3 IR contains this check on the precomputed selected heap size:
%230 = and i64 %spec.select, 1
%231 = icmp eq i64 %230, 0
%232 = add nsw i64 %spec.select, -2
%277 = icmp eq i64 %232, 0
%or.cond38.i.i.i = select i1 %231, i1 %277, i1 false
This checks whether the size is even and size - 2 == 0. But the latter already means size == 2, and 2 is even. LLVM could therefore replace both checks with size == 2.
Hi, I’d like to work on this. I’ll look into where the range check (icmp ult (add x, 1), 3) and the masked equality (and x, -127 == -127) can be combined in InstCombine, and put up a PR if I get a fix working.