Skip to content

Commit c316730

Browse files
dtcxzywpaulhuggett
authored andcommitted
[InstCombine] Handle commuted pattern for ((X s/ C1) << C2) + X (llvm#121737)
Closes llvm#121700
1 parent 5374a3d commit c316730

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1326,6 +1326,18 @@ Instruction *InstCombinerImpl::foldAddLikeCommutative(Value *LHS, Value *RHS,
13261326
R->setHasNoUnsignedWrap(NUWOut);
13271327
return R;
13281328
}
1329+
1330+
// ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1331+
const APInt *C1, *C2;
1332+
if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1333+
APInt One(C2->getBitWidth(), 1);
1334+
APInt MinusC1 = -(*C1);
1335+
if (MinusC1 == (One << *C2)) {
1336+
Constant *NewRHS = ConstantInt::get(RHS->getType(), MinusC1);
1337+
return BinaryOperator::CreateSRem(RHS, NewRHS);
1338+
}
1339+
}
1340+
13291341
return nullptr;
13301342
}
13311343

@@ -1623,17 +1635,7 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
16231635
// X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1)
16241636
if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V);
16251637

1626-
// ((X s/ C1) << C2) + X => X s% -C1 where -C1 is 1 << C2
1627-
const APInt *C1, *C2;
1628-
if (match(LHS, m_Shl(m_SDiv(m_Specific(RHS), m_APInt(C1)), m_APInt(C2)))) {
1629-
APInt one(C2->getBitWidth(), 1);
1630-
APInt minusC1 = -(*C1);
1631-
if (minusC1 == (one << *C2)) {
1632-
Constant *NewRHS = ConstantInt::get(RHS->getType(), minusC1);
1633-
return BinaryOperator::CreateSRem(RHS, NewRHS);
1634-
}
1635-
}
1636-
1638+
const APInt *C1;
16371639
// (A & 2^C1) + A => A & (2^C1 - 1) iff bit C1 in A is a sign bit
16381640
if (match(&I, m_c_Add(m_And(m_Value(A), m_APInt(C1)), m_Deferred(A))) &&
16391641
C1->isPowerOf2() && (ComputeNumSignBits(A) > C1->countl_zero())) {

llvm/test/Transforms/InstCombine/add-shl-sdiv-to-srem.ll

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,17 @@ define i8 @add-shl-sdiv-scalar0(i8 %x) {
1212
ret i8 %rz
1313
}
1414

15+
define i8 @add-shl-sdiv-scalar0_commuted(i8 %x) {
16+
; CHECK-LABEL: @add-shl-sdiv-scalar0_commuted(
17+
; CHECK-NEXT: [[RZ:%.*]] = srem i8 [[X:%.*]], 4
18+
; CHECK-NEXT: ret i8 [[RZ]]
19+
;
20+
%sd = sdiv i8 %x, -4
21+
%sl = shl i8 %sd, 2
22+
%rz = add i8 %x, %sl
23+
ret i8 %rz
24+
}
25+
1526
define i8 @add-shl-sdiv-scalar1(i8 %x) {
1627
; CHECK-LABEL: @add-shl-sdiv-scalar1(
1728
; CHECK-NEXT: [[RZ:%.*]] = srem i8 [[X:%.*]], 64

0 commit comments

Comments
 (0)