[llvm] fe15290 - [InstCombine] fold exact sdiv to ashr
Sanjay Patel via llvm-commits
llvm-commits at lists.llvm.org
Sat Oct 8 06:54:45 PDT 2022
Author: Sanjay Patel
Date: 2022-10-08T09:23:46-04:00
New Revision: fe15290e0cf5d2bcdefca2e81ef6ff8155a2f7a8
URL: https://github.com/llvm/llvm-project/commit/fe15290e0cf5d2bcdefca2e81ef6ff8155a2f7a8
DIFF: https://github.com/llvm/llvm-project/commit/fe15290e0cf5d2bcdefca2e81ef6ff8155a2f7a8.diff
LOG: [InstCombine] fold exact sdiv to ashr
sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
https://alive2.llvm.org/ce/z/kB6VF7
It would probably be better to use ValueTracking to replace this
and the existing transform above it, but the analysis does not
account for the no-wrap properly, and it's not immediately clear
to me how to fix it.
Added:
Modified:
llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
llvm/test/Transforms/InstCombine/sdiv-exact-by-power-of-two.ll
Removed:
################################################################################
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
index 69625c082c5c7..d9fcd436b00e0 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
@@ -1199,6 +1199,11 @@ Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
return BinaryOperator::CreateExactAShr(Op0, C);
}
+ // sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
+ Value *ShAmt;
+ if (match(Op1, m_NSWShl(m_One(), m_Value(ShAmt))))
+ return BinaryOperator::CreateExactAShr(Op0, ShAmt);
+
// sdiv exact X, -1<<C --> -(ashr exact X, C)
if (match(Op1, m_NegatedPower2())) {
Constant *NegPow2C = ConstantExpr::getNeg(cast<Constant>(Op1));
diff --git a/llvm/test/Transforms/InstCombine/sdiv-exact-by-power-of-two.ll b/llvm/test/Transforms/InstCombine/sdiv-exact-by-power-of-two.ll
index 8bc29d04118be..ff650de2c5c80 100644
--- a/llvm/test/Transforms/InstCombine/sdiv-exact-by-power-of-two.ll
+++ b/llvm/test/Transforms/InstCombine/sdiv-exact-by-power-of-two.ll
@@ -71,16 +71,13 @@ define <2 x i8> @n6_vec_negative(<2 x i8> %x) {
}
define i8 @shl1_nsw(i8 %x, i8 %y) {
-; CHECK-LABEL: @shl1_nsw(
-; CHECK-NEXT: [[SHL:%.*]] = shl nuw nsw i8 1, [[Y:%.*]]
-; CHECK-NEXT: [[DIV:%.*]] = sdiv exact i8 [[X:%.*]], [[SHL]]
-; CHECK-NEXT: ret i8 [[DIV]]
-;
%shl = shl nsw i8 1, %y
%div = sdiv exact i8 %x, %shl
ret i8 %div
}
+; negative test - must have nsw
+
define i8 @shl1_nuw(i8 %x, i8 %y) {
; CHECK-LABEL: @shl1_nuw(
; CHECK-NEXT: [[SHL:%.*]] = shl nuw i8 1, [[Y:%.*]]
@@ -91,3 +88,11 @@ define i8 @shl1_nuw(i8 %x, i8 %y) {
%div = sdiv exact i8 %x, %shl
ret i8 %div
}
+
+; negative test - must have exact
+
+define i8 @shl1_nsw_not_exact(i8 %x, i8 %y) {
+ %shl = shl nsw i8 1, %y
+ %div = sdiv i8 %x, %shl
+ ret i8 %div
+}
More information about the llvm-commits
mailing list