Skip to content

Commit d9f4f30

Browse files
nikicakiramenai
authored andcommitted
[InstCombine] Compute result directly on APInts
If the bitwidth is 2 and we add two 1s, the result may overflow. This is fine in terms of correctness, but triggers the APInt ctor assertion. Fix this by performing the calculation directly on APInts. Fixes the issue reported in: llvm/llvm-project#114539 (comment)
1 parent 92403ed commit d9f4f30

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3038,12 +3038,12 @@ Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
30383038
unsigned BW = C.getBitWidth();
30393039
std::bitset<4> Table;
30403040
auto ComputeTable = [&](bool Op0Val, bool Op1Val) {
3041-
int Res = 0;
3041+
APInt Res(BW, 0);
30423042
if (Op0Val)
3043-
Res += isa<ZExtInst>(Ext0) ? 1 : -1;
3043+
Res += APInt(BW, isa<ZExtInst>(Ext0) ? 1 : -1, /*isSigned=*/true);
30443044
if (Op1Val)
3045-
Res += isa<ZExtInst>(Ext1) ? 1 : -1;
3046-
return ICmpInst::compare(APInt(BW, Res, true), C, Pred);
3045+
Res += APInt(BW, isa<ZExtInst>(Ext1) ? 1 : -1, /*isSigned=*/true);
3046+
return ICmpInst::compare(Res, C, Pred);
30473047
};
30483048

30493049
Table[0] = ComputeTable(false, false);

llvm/test/Transforms/InstCombine/icmp-add.ll

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,19 @@ bb:
7979
ret i1 %i4
8080
}
8181

82+
define i1 @cvt_icmp_0_zext_plus_zext_eq_i2(i1 %a, i1 %b) {
83+
; CHECK-LABEL: @cvt_icmp_0_zext_plus_zext_eq_i2(
84+
; CHECK-NEXT: [[TMP1:%.*]] = or i1 [[A:%.*]], [[B:%.*]]
85+
; CHECK-NEXT: [[CMP:%.*]] = xor i1 [[TMP1]], true
86+
; CHECK-NEXT: ret i1 [[CMP]]
87+
;
88+
%a.ext = zext i1 %a to i2
89+
%b.ext = zext i1 %b to i2
90+
%add = add i2 %a.ext, %b.ext
91+
%cmp = icmp eq i2 %add, 0
92+
ret i1 %cmp
93+
}
94+
8295
define i1 @cvt_icmp_1_zext_plus_zext_eq(i1 %arg, i1 %arg1) {
8396
; CHECK-LABEL: @cvt_icmp_1_zext_plus_zext_eq(
8497
; CHECK-NEXT: bb:

0 commit comments

Comments
 (0)