Skip to content

Commit 26ce3e4

Browse files
authored
[InstCombine] Preserve NSW flags for lshr (mul nuw X, C1), C2 -> mul nuw nsw X, (C1 >> C2) (#72625)
Alive2: https://alive2.llvm.org/ce/z/TU_V9M This missed optimization is discovered with the help of AliveToolkit/alive2#962.
1 parent f049395 commit 26ce3e4

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

llvm/lib/Transforms/InstCombine/InstCombineShifts.cpp

+4-3
Original file line numberDiff line numberDiff line change
@@ -1435,12 +1435,13 @@ Instruction *InstCombinerImpl::visitLShr(BinaryOperator &I) {
14351435
if (Op0->hasOneUse()) {
14361436
APInt NewMulC = MulC->lshr(ShAmtC);
14371437
// if c is divisible by (1 << ShAmtC):
1438-
// lshr (mul nuw x, MulC), ShAmtC -> mul nuw x, (MulC >> ShAmtC)
1438+
// lshr (mul nuw x, MulC), ShAmtC -> mul nuw nsw x, (MulC >> ShAmtC)
14391439
if (MulC->eq(NewMulC.shl(ShAmtC))) {
14401440
auto *NewMul =
14411441
BinaryOperator::CreateNUWMul(X, ConstantInt::get(Ty, NewMulC));
1442-
BinaryOperator *OrigMul = cast<BinaryOperator>(Op0);
1443-
NewMul->setHasNoSignedWrap(OrigMul->hasNoSignedWrap());
1442+
assert(ShAmtC != 0 &&
1443+
"lshr X, 0 should be handled by simplifyLShrInst.");
1444+
NewMul->setHasNoSignedWrap(true);
14441445
return NewMul;
14451446
}
14461447
}

llvm/test/Transforms/InstCombine/shift-logic.ll

+2-2
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ define i32 @PR44028(i32 %x) {
259259

260260
define i64 @lshr_mul(i64 %0) {
261261
; CHECK-LABEL: @lshr_mul(
262-
; CHECK-NEXT: [[TMP2:%.*]] = mul nuw i64 [[TMP0:%.*]], 13
262+
; CHECK-NEXT: [[TMP2:%.*]] = mul nuw nsw i64 [[TMP0:%.*]], 13
263263
; CHECK-NEXT: ret i64 [[TMP2]]
264264
;
265265
%2 = mul nuw i64 %0, 52
@@ -279,7 +279,7 @@ define i64 @lshr_mul_nuw_nsw(i64 %0) {
279279

280280
define <4 x i32> @lshr_mul_vector(<4 x i32> %0) {
281281
; CHECK-LABEL: @lshr_mul_vector(
282-
; CHECK-NEXT: [[TMP2:%.*]] = mul nuw <4 x i32> [[TMP0:%.*]], <i32 13, i32 13, i32 13, i32 13>
282+
; CHECK-NEXT: [[TMP2:%.*]] = mul nuw nsw <4 x i32> [[TMP0:%.*]], <i32 13, i32 13, i32 13, i32 13>
283283
; CHECK-NEXT: ret <4 x i32> [[TMP2]]
284284
;
285285
%2 = mul nuw <4 x i32> %0, <i32 52, i32 52, i32 52, i32 52>

0 commit comments

Comments
 (0)