Skip to content

Commit

Permalink
[ConstantRange] Make shl() for negative LHS more precise
Browse files Browse the repository at this point in the history
This differs from the positive case in that shifting by a larger
amount makes the result smaller, not larger.
  • Loading branch information
nikic committed Aug 29, 2023
1 parent 498b59e commit 4dd392f
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
7 changes: 7 additions & 0 deletions llvm/lib/IR/ConstantRange.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1477,6 +1477,13 @@ ConstantRange::shl(const ConstantRange &Other) const {
}

APInt OtherMax = Other.getUnsignedMax();
if (isAllNegative() && OtherMax.ule(Min.countl_one())) {
// For negative numbers, if the shift does not overflow in a signed sense,
// a larger shift will make the number smaller.
Max <<= Other.getUnsignedMin();
Min <<= OtherMax;
return ConstantRange::getNonEmpty(std::move(Min), std::move(Max) + 1);
}

// There's overflow!
if (OtherMax.ugt(Max.countl_zero()))
Expand Down
6 changes: 2 additions & 4 deletions llvm/test/Transforms/SCCP/and-add-shl.ll
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ define i8 @and_not_shl(i8 %x) {
; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]])
; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]]
; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1
; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 32
; CHECK-NEXT: ret i8 [[R]]
; CHECK-NEXT: ret i8 0
;
%op1_p2 = icmp ule i8 %x, 5
call void @llvm.assume(i1 %op1_p2)
Expand All @@ -48,8 +47,7 @@ define i8 @and_not_shl_1(i8 %x) {
; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]])
; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]]
; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1
; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 48
; CHECK-NEXT: ret i8 [[R]]
; CHECK-NEXT: ret i8 0
;
%op1_p2 = icmp ule i8 %x, 4
call void @llvm.assume(i1 %op1_p2)
Expand Down
7 changes: 7 additions & 0 deletions llvm/unittests/IR/ConstantRangeTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,13 @@ TEST_F(ConstantRangeTest, Shl) {
ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
EXPECT_EQ(One.shl(WrapNullMax), Full);

ConstantRange NegOne(APInt(16, 0xffff));
EXPECT_EQ(NegOne.shl(ConstantRange(APInt(16, 0), APInt(16, 5))),
ConstantRange(APInt(16, 0xfff0), APInt(16, 0)));
EXPECT_EQ(ConstantRange(APInt(16, 0xfffe), APInt(16, 0))
.shl(ConstantRange(APInt(16, 0), APInt(16, 5))),
ConstantRange(APInt(16, 0xffe0), APInt(16, 0)));

TestBinaryOpExhaustive(
[](const ConstantRange &CR1, const ConstantRange &CR2) {
return CR1.shl(CR2);
Expand Down

0 comments on commit 4dd392f

Please sign in to comment.