Skip to content

Commit 4dd392f

Browse files
committed
[ConstantRange] Make shl() for negative LHS more precise
This differs from the positive case in that shifting by a larger amount makes the result smaller, not larger.
1 parent 498b59e commit 4dd392f

File tree

3 files changed

+16
-4
lines changed

3 files changed

+16
-4
lines changed

llvm/lib/IR/ConstantRange.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,6 +1477,13 @@ ConstantRange::shl(const ConstantRange &Other) const {
14771477
}
14781478

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

14811488
// There's overflow!
14821489
if (OtherMax.ugt(Max.countl_zero()))

llvm/test/Transforms/SCCP/and-add-shl.ll

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,7 @@ define i8 @and_not_shl(i8 %x) {
3030
; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]])
3131
; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]]
3232
; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1
33-
; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 32
34-
; CHECK-NEXT: ret i8 [[R]]
33+
; CHECK-NEXT: ret i8 0
3534
;
3635
%op1_p2 = icmp ule i8 %x, 5
3736
call void @llvm.assume(i1 %op1_p2)
@@ -48,8 +47,7 @@ define i8 @and_not_shl_1(i8 %x) {
4847
; CHECK-NEXT: call void @llvm.assume(i1 [[OP1_P2]])
4948
; CHECK-NEXT: [[SHIFT:%.*]] = shl nsw i8 -1, [[X]]
5049
; CHECK-NEXT: [[NOT:%.*]] = xor i8 [[SHIFT]], -1
51-
; CHECK-NEXT: [[R:%.*]] = and i8 [[NOT]], 48
52-
; CHECK-NEXT: ret i8 [[R]]
50+
; CHECK-NEXT: ret i8 0
5351
;
5452
%op1_p2 = icmp ule i8 %x, 4
5553
call void @llvm.assume(i1 %op1_p2)

llvm/unittests/IR/ConstantRangeTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1373,6 +1373,13 @@ TEST_F(ConstantRangeTest, Shl) {
13731373
ConstantRange(APInt(16, 0xfff << 0x1), APInt(16, 0x7fff << 0x1) + 1));
13741374
EXPECT_EQ(One.shl(WrapNullMax), Full);
13751375

1376+
ConstantRange NegOne(APInt(16, 0xffff));
1377+
EXPECT_EQ(NegOne.shl(ConstantRange(APInt(16, 0), APInt(16, 5))),
1378+
ConstantRange(APInt(16, 0xfff0), APInt(16, 0)));
1379+
EXPECT_EQ(ConstantRange(APInt(16, 0xfffe), APInt(16, 0))
1380+
.shl(ConstantRange(APInt(16, 0), APInt(16, 5))),
1381+
ConstantRange(APInt(16, 0xffe0), APInt(16, 0)));
1382+
13761383
TestBinaryOpExhaustive(
13771384
[](const ConstantRange &CR1, const ConstantRange &CR2) {
13781385
return CR1.shl(CR2);

0 commit comments

Comments
 (0)