[InstCombine] fold exact sdiv to ashr (2nd try)

The 1st attempt failed to updated the test checks as expected.

Original commit message:

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.
This commit is contained in:
Sanjay Patel 2022-10-08 10:09:44 -04:00
parent ebda06686f
commit eccb9a77c6
2 changed files with 12 additions and 2 deletions

View File

@ -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));

View File

@ -70,10 +70,11 @@ define <2 x i8> @n6_vec_negative(<2 x i8> %x) {
ret <2 x i8> %div
}
; sdiv exact X, (1<<ShAmt) --> ashr exact X, ShAmt (if shl is non-negative)
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: [[DIV:%.*]] = ashr exact i8 [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT: ret i8 [[DIV]]
;
%shl = shl nsw i8 1, %y
@ -81,6 +82,8 @@ define i8 @shl1_nsw(i8 %x, i8 %y) {
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:%.*]]
@ -92,6 +95,8 @@ define i8 @shl1_nuw(i8 %x, i8 %y) {
ret i8 %div
}
; negative test - must have exact
define i8 @shl1_nsw_not_exact(i8 %x, i8 %y) {
; CHECK-LABEL: @shl1_nsw_not_exact(
; CHECK-NEXT: [[SHL:%.*]] = shl nuw nsw i8 1, [[Y:%.*]]