Skip to content

Commit c42c320

Browse files
authored
[InstCombine] Add reverse of ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z) (#91386)
This is the same fold as ((X << nuw Z) sub nuw Y) >>u exact Z --> X sub nuw (Y >>u exact Z), which we already have and approved in the codebase, but with the sub operands swapped. Proof it works in reverse, so we could have a wider generalization of this pattern: https://alive2.llvm.org/ce/z/2cRcdx
1 parent 558c519 commit c42c320

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1275,6 +1275,17 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
12751275
return NewSub;
12761276
}
12771277

1278+
// (sub nuw X, (Y << nuw Z)) >>u exact Z --> (X >>u exact Z) sub nuw Y
1279+
if (I.isExact() &&
1280+
match(Op0, m_OneUse(m_NUWSub(m_Value(X),
1281+
m_NUWShl(m_Value(Y), m_Specific(Op1)))))) {
1282+
Value *NewLshr = Builder.CreateLShr(X, Op1, "", /*isExact=*/true);
1283+
auto *NewSub = BinaryOperator::CreateNUWSub(NewLshr, Y);
1284+
NewSub->setHasNoSignedWrap(
1285+
cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap());
1286+
return NewSub;
1287+
}
1288+
12781289
auto isSuitableBinOpcode = [](Instruction::BinaryOps BinOpcode) {
12791290
switch (BinOpcode) {
12801291
default:

llvm/test/Transforms/InstCombine/lshr.ll

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,33 @@ define i32 @shl_sub_lshr(i32 %x, i32 %c, i32 %y) {
466466
ret i32 %lshr
467467
}
468468

469+
define i32 @shl_sub_lshr_reverse(i32 %x, i32 %c, i32 %y) {
470+
; CHECK-LABEL: @shl_sub_lshr_reverse(
471+
; CHECK-NEXT: [[TMP1:%.*]] = lshr exact i32 [[Y:%.*]], [[C:%.*]]
472+
; CHECK-NEXT: [[LSHR:%.*]] = sub nuw nsw i32 [[TMP1]], [[X:%.*]]
473+
; CHECK-NEXT: ret i32 [[LSHR]]
474+
;
475+
%shl = shl nuw i32 %x, %c
476+
%sub = sub nuw nsw i32 %y, %shl
477+
%lshr = lshr exact i32 %sub, %c
478+
ret i32 %lshr
479+
}
480+
481+
; Negative test
482+
483+
define i32 @shl_sub_lshr_reverse_no_exact(i32 %x, i32 %c, i32 %y) {
484+
; CHECK-LABEL: @shl_sub_lshr_reverse_no_exact(
485+
; CHECK-NEXT: [[SHL:%.*]] = shl nuw i32 [[X:%.*]], [[C:%.*]]
486+
; CHECK-NEXT: [[SUB:%.*]] = sub nuw nsw i32 [[Y:%.*]], [[SHL]]
487+
; CHECK-NEXT: [[LSHR:%.*]] = lshr i32 [[SUB]], [[C]]
488+
; CHECK-NEXT: ret i32 [[LSHR]]
489+
;
490+
%shl = shl nuw i32 %x, %c
491+
%sub = sub nuw nsw i32 %y, %shl
492+
%lshr = lshr i32 %sub, %c
493+
ret i32 %lshr
494+
}
495+
469496
define i32 @shl_or_lshr(i32 %x, i32 %c, i32 %y) {
470497
; CHECK-LABEL: @shl_or_lshr(
471498
; CHECK-NEXT: [[TMP1:%.*]] = lshr i32 [[Y:%.*]], [[C:%.*]]

0 commit comments

Comments
 (0)