[llvm] [InstCombine] Fold sext of an nsw binop on trunc nsw into a wide nsw … (PR #228530)
via llvm-commits
llvm-commits at lists.llvm.org
Tue Oct 6 09:54:29 PDT 2026
https://github.com/junfengd-nv updated https://github.com/llvm/llvm-project/pull/228530
>From fdb07d616409ae5338282326f47661218a3d252a Mon Sep 17 00:00:00 2001
From: Junfeng Dong <junfengd at nvidia.com>
Date: Fri, 2 Oct 2026 10:14:38 -0700
Subject: [PATCH 1/4] [InstCombine] Fold sext of an nsw binop on trunc nsw into
a wide nsw binop
---
.../InstCombine/InstCombineCasts.cpp | 51 ++++++
.../InstCombine/sext-of-binop-of-trunc-nsw.ll | 148 ++++++++++++++++++
2 files changed, 199 insertions(+)
create mode 100644 llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index df52a84e0d3f34..eefb0db689b4ed 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1922,6 +1922,52 @@ bool TypeEvaluationHelper::canEvaluateSExtdPred(Value *V, Type *Ty) {
return false;
}
+/// Fold
+/// sext (binop nsw (trunc nsw X to iN), C) to iM
+/// to
+/// binop nsw X, sext(C)
+/// when X already has type iM. trunc nsw means X fits in iN, and nsw on the
+/// narrow binop means the result also fits in iN, so the sign-extended value
+/// is that same operation on X and the sign-extended other operand. The wide
+/// binop is nsw because its result fits in iN.
+///
+/// EvaluateInDifferentType rebuilds the binop without overflow flags. The
+/// sign-bit check then fails and visitSExt emits a shl/ashr pair, which SCEV
+/// cannot treat as a non-wrapping recurrence.
+static Instruction *foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext,
+ const DataLayout &DL) {
+ auto *BinOp = dyn_cast<OverflowingBinaryOperator>(Sext.getOperand(0));
+ if (!BinOp || !BinOp->hasNoSignedWrap())
+ return nullptr;
+
+ auto Opc = static_cast<Instruction::BinaryOps>(BinOp->getOpcode());
+ if (Opc != Instruction::Add && Opc != Instruction::Sub &&
+ Opc != Instruction::Mul)
+ return nullptr;
+
+ Type *DestTy = Sext.getType();
+ bool SawNSWTrunc = false;
+ auto widenOperand = [&](Value *V) -> Value * {
+ Value *X;
+ if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy) {
+ SawNSWTrunc = true;
+ return X;
+ }
+ if (auto *C = dyn_cast<Constant>(V))
+ return ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL);
+ return nullptr;
+ };
+
+ Value *LHS = widenOperand(BinOp->getOperand(0));
+ Value *RHS = widenOperand(BinOp->getOperand(1));
+ if (!LHS || !RHS || !SawNSWTrunc)
+ return nullptr;
+
+ auto *Wide = BinaryOperator::Create(Opc, LHS, RHS);
+ Wide->setHasNoSignedWrap(true);
+ return Wide;
+}
+
Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
// If this sign extend is only used by a truncate, let the truncate be
// eliminated before we try to optimize this sext.
@@ -1931,6 +1977,11 @@ Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
if (Instruction *I = commonCastTransforms(Sext))
return I;
+ // Do this before EvaluateInDifferentType, which drops nsw and may emit
+ // shl/ashr.
+ if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL))
+ return I;
+
Value *Src = Sext.getOperand(0);
Type *SrcTy = Src->getType(), *DestTy = Sext.getType();
unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
diff --git a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
new file mode 100644
index 00000000000000..c60ad8ad3e6209
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
@@ -0,0 +1,148 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+; sext(binop nsw (trunc nsw X), C) is the same operation on X when X already
+; has the destination type. Rebuilding that expression without nsw becomes a
+; shl/ashr pair, which SCEV cannot treat as a non-wrapping recurrence.
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+declare void @use32(i32)
+
+define i64 @sext_add_nsw_of_trunc_nsw(i64 %x) {
+; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_nsw(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], 1
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = add nsw i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_sub_nsw_of_trunc_nsw(i64 %x) {
+; CHECK-LABEL: define i64 @sext_sub_nsw_of_trunc_nsw(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], -1
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = sub nsw i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_sub_nsw_of_two_trunc_nsw(i64 %x, i64 %y) {
+; CHECK-LABEL: define i64 @sext_sub_nsw_of_two_trunc_nsw(
+; CHECK-SAME: i64 [[X:%.*]], i64 [[Y:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = sub nsw i64 [[X]], [[Y]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %tx = trunc nsw i64 %x to i32
+ %ty = trunc nsw i64 %y to i32
+ %s = sub nsw i32 %tx, %ty
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_mul_nsw_of_trunc_nsw(i64 %x) {
+; CHECK-LABEL: define i64 @sext_mul_nsw_of_trunc_nsw(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = mul nsw i64 [[X]], 3
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = mul nsw i32 %t, 3
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_add_nsw_constant_on_lhs(i64 %x) {
+; CHECK-LABEL: define i64 @sext_add_nsw_constant_on_lhs(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], -5
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = add nsw i32 -5, %t
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define <2 x i64> @sext_add_nsw_of_trunc_nsw_vec(<2 x i64> %x) {
+; CHECK-LABEL: define <2 x i64> @sext_add_nsw_of_trunc_nsw_vec(
+; CHECK-SAME: <2 x i64> [[X:%.*]]) {
+; CHECK-NEXT: [[E:%.*]] = add nsw <2 x i64> [[X]], splat (i64 1)
+; CHECK-NEXT: ret <2 x i64> [[E]]
+;
+ %t = trunc nsw <2 x i64> %x to <2 x i32>
+ %s = add nsw <2 x i32> %t, splat (i32 1)
+ %e = sext <2 x i32> %s to <2 x i64>
+ ret <2 x i64> %e
+}
+
+define i64 @sext_add_nsw_of_trunc_nsw_extra_use(i64 %x) {
+; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_nsw_extra_use(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[T:%.*]] = trunc nsw i64 [[X]] to i32
+; CHECK-NEXT: call void @use32(i32 [[T]])
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], 1
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ call void @use32(i32 %t)
+ %s = add nsw i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+; Negative: trunc without nsw does not prove that %x fits in i32.
+
+define i64 @sext_add_nsw_of_trunc_without_nsw(i64 %x) {
+; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_without_nsw(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[S:%.*]] = shl i64 [[X]], 32
+; CHECK-NEXT: [[SEXT:%.*]] = add i64 [[S]], 4294967296
+; CHECK-NEXT: [[E:%.*]] = ashr exact i64 [[SEXT]], 32
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc i64 %x to i32
+ %s = add nsw i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+; Negative: the narrow add may wrap, so the wide add is not equivalent.
+
+define i64 @sext_add_of_trunc_nsw_without_nsw(i64 %x) {
+; CHECK-LABEL: define i64 @sext_add_of_trunc_nsw_without_nsw(
+; CHECK-SAME: i64 [[X:%.*]]) {
+; CHECK-NEXT: [[S:%.*]] = shl i64 [[X]], 32
+; CHECK-NEXT: [[SEXT:%.*]] = add i64 [[S]], 4294967296
+; CHECK-NEXT: [[E:%.*]] = ashr exact i64 [[SEXT]], 32
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = add i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+; Negative: the truncated value is wider than the sext result.
+
+define i64 @sext_add_nsw_trunc_nsw_wider_source(i128 %x) {
+; CHECK-LABEL: define i64 @sext_add_nsw_trunc_nsw_wider_source(
+; CHECK-SAME: i128 [[X:%.*]]) {
+; CHECK-NEXT: [[T:%.*]] = trunc nsw i128 [[X]] to i64
+; CHECK-NEXT: [[S:%.*]] = shl i64 [[T]], 32
+; CHECK-NEXT: [[SEXT:%.*]] = add i64 [[S]], 4294967296
+; CHECK-NEXT: [[E:%.*]] = ashr exact i64 [[SEXT]], 32
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i128 %x to i32
+ %s = add nsw i32 %t, 1
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
>From f9a5e857a3cd41d780e7616312ae10c53298c82a Mon Sep 17 00:00:00 2001
From: Junfeng Dong <junfengd at nvidia.com>
Date: Mon, 5 Oct 2026 09:26:04 -0700
Subject: [PATCH 2/4] resolve feedbacks.
---
.../InstCombine/InstCombineCasts.cpp | 19 ++++++++-----------
.../InstCombine/sext-of-binop-of-trunc-nsw.ll | 18 ++++++++++++++++++
2 files changed, 26 insertions(+), 11 deletions(-)
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index eefb0db689b4ed..e9bbec3894c328 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1946,13 +1946,10 @@ static Instruction *foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext,
return nullptr;
Type *DestTy = Sext.getType();
- bool SawNSWTrunc = false;
auto widenOperand = [&](Value *V) -> Value * {
Value *X;
- if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy) {
- SawNSWTrunc = true;
+ if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy)
return X;
- }
if (auto *C = dyn_cast<Constant>(V))
return ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL);
return nullptr;
@@ -1960,12 +1957,10 @@ static Instruction *foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext,
Value *LHS = widenOperand(BinOp->getOperand(0));
Value *RHS = widenOperand(BinOp->getOperand(1));
- if (!LHS || !RHS || !SawNSWTrunc)
+ if (!LHS || !RHS)
return nullptr;
- auto *Wide = BinaryOperator::Create(Opc, LHS, RHS);
- Wide->setHasNoSignedWrap(true);
- return Wide;
+ return BinaryOperator::CreateNSW(Opc, LHS, RHS);
}
Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
@@ -1978,9 +1973,11 @@ Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
return I;
// Do this before EvaluateInDifferentType, which drops nsw and may emit
- // shl/ashr.
- if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL))
- return I;
+ // shl/ashr. Do not widen the arithmetic past a legal type.
+ if (isa<VectorType>(Sext.getType()) ||
+ shouldChangeType(Sext.getSrcTy(), Sext.getType()))
+ if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL))
+ return I;
Value *Src = Sext.getOperand(0);
Type *SrcTy = Src->getType(), *DestTy = Sext.getType();
diff --git a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
index c60ad8ad3e6209..5648120245ec0d 100644
--- a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
+++ b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
@@ -4,6 +4,7 @@
; sext(binop nsw (trunc nsw X), C) is the same operation on X when X already
; has the destination type. Rebuilding that expression without nsw becomes a
; shl/ashr pair, which SCEV cannot treat as a non-wrapping recurrence.
+; https://alive2.llvm.org/ce/z/CUWfpR
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"
@@ -146,3 +147,20 @@ define i64 @sext_add_nsw_trunc_nsw_wider_source(i128 %x) {
%e = sext i32 %s to i64
ret i64 %e
}
+
+; Negative: do not widen the arithmetic past a legal type. i128 is not a legal
+; integer for this data layout.
+
+define i128 @sext_add_nsw_past_legal_type(i128 %x) {
+; CHECK-LABEL: define i128 @sext_add_nsw_past_legal_type(
+; CHECK-SAME: i128 [[X:%.*]]) {
+; CHECK-NEXT: [[T:%.*]] = trunc nsw i128 [[X]] to i64
+; CHECK-NEXT: [[S:%.*]] = add nsw i64 [[T]], 1
+; CHECK-NEXT: [[E:%.*]] = sext i64 [[S]] to i128
+; CHECK-NEXT: ret i128 [[E]]
+;
+ %t = trunc nsw i128 %x to i64
+ %s = add nsw i64 %t, 1
+ %e = sext i64 %s to i128
+ ret i128 %e
+}
>From 54a8488c6e9a46b7154e332041d4939756a45c88 Mon Sep 17 00:00:00 2001
From: Junfeng Dong <junfengd at nvidia.com>
Date: Mon, 5 Oct 2026 14:19:28 -0700
Subject: [PATCH 3/4] Extend to support a variable.
---
.../InstCombine/InstCombineCasts.cpp | 59 ++++++++----
.../InstCombine/sext-of-binop-of-trunc-nsw.ll | 93 ++++++++++++++++++-
2 files changed, 132 insertions(+), 20 deletions(-)
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index e9bbec3894c328..3481cb29b8be6c 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1923,19 +1923,25 @@ bool TypeEvaluationHelper::canEvaluateSExtdPred(Value *V, Type *Ty) {
}
/// Fold
-/// sext (binop nsw (trunc nsw X to iN), C) to iM
+/// sext (binop nsw (trunc nsw X to iN), Y) to iM
/// to
-/// binop nsw X, sext(C)
-/// when X already has type iM. trunc nsw means X fits in iN, and nsw on the
-/// narrow binop means the result also fits in iN, so the sign-extended value
-/// is that same operation on X and the sign-extended other operand. The wide
-/// binop is nsw because its result fits in iN.
+/// binop nsw X, sext(Y)
+/// when X already has type iM. Y may be a constant, another trunc nsw back to
+/// an iM value, or any other iN value. trunc nsw means X fits in iN, and nsw
+/// on the narrow binop means the result also fits in iN, so the sign-extended
+/// value is that same operation on X and the sign-extended other operand. The
+/// wide binop is nsw because its result fits in iN.
+///
+/// A constant Y is folded into sext(Y) immediately. A non-constant Y becomes
+/// an explicit sext, so a loop-invariant narrow operand stays an nsw
+/// recurrence.
///
/// EvaluateInDifferentType rebuilds the binop without overflow flags. The
/// sign-bit check then fails and visitSExt emits a shl/ashr pair, which SCEV
/// cannot treat as a non-wrapping recurrence.
-static Instruction *foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext,
- const DataLayout &DL) {
+static Instruction *
+foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext, const DataLayout &DL,
+ InstCombiner::BuilderTy &Builder) {
auto *BinOp = dyn_cast<OverflowingBinaryOperator>(Sext.getOperand(0));
if (!BinOp || !BinOp->hasNoSignedWrap())
return nullptr;
@@ -1945,22 +1951,41 @@ static Instruction *foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext,
Opc != Instruction::Mul)
return nullptr;
+ // V is the widened operand. NeedsSExt means V still has the narrow type and
+ // must be sign-extended. FromWideTrunc means V is an existing iM value
+ // recovered from trunc nsw.
+ struct WideOp {
+ Value *V = nullptr;
+ bool NeedsSExt = false;
+ bool FromWideTrunc = false;
+ };
Type *DestTy = Sext.getType();
- auto widenOperand = [&](Value *V) -> Value * {
+ auto widenOperand = [&](Value *V) -> WideOp {
Value *X;
if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy)
- return X;
+ return {X, false, true};
if (auto *C = dyn_cast<Constant>(V))
- return ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL);
- return nullptr;
+ return {ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL), false,
+ false};
+ // Any other same-typed value sign-extends to its mathematical value.
+ // This is only used when the other operand recovers an existing iM value,
+ // so the fold does not widen arithmetic that was never connected to one.
+ if (V->getType() == BinOp->getType())
+ return {V, true, false};
+ return {};
};
- Value *LHS = widenOperand(BinOp->getOperand(0));
- Value *RHS = widenOperand(BinOp->getOperand(1));
- if (!LHS || !RHS)
+ WideOp LHS = widenOperand(BinOp->getOperand(0));
+ WideOp RHS = widenOperand(BinOp->getOperand(1));
+ if (!LHS.V || !RHS.V || !(LHS.FromWideTrunc || RHS.FromWideTrunc))
return nullptr;
- return BinaryOperator::CreateNSW(Opc, LHS, RHS);
+ auto materialize = [&](WideOp Op) -> Value * {
+ if (!Op.NeedsSExt)
+ return Op.V;
+ return Builder.CreateSExt(Op.V, DestTy);
+ };
+ return BinaryOperator::CreateNSW(Opc, materialize(LHS), materialize(RHS));
}
Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
@@ -1976,7 +2001,7 @@ Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
// shl/ashr. Do not widen the arithmetic past a legal type.
if (isa<VectorType>(Sext.getType()) ||
shouldChangeType(Sext.getSrcTy(), Sext.getType()))
- if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL))
+ if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL, Builder))
return I;
Value *Src = Sext.getOperand(0);
diff --git a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
index 5648120245ec0d..f4999fee3d522f 100644
--- a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
+++ b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
@@ -1,9 +1,10 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; RUN: opt < %s -passes=instcombine -S | FileCheck %s
-; sext(binop nsw (trunc nsw X), C) is the same operation on X when X already
-; has the destination type. Rebuilding that expression without nsw becomes a
-; shl/ashr pair, which SCEV cannot treat as a non-wrapping recurrence.
+; sext(binop nsw (trunc nsw X), Y) is the same operation on X when X already
+; has the destination type. Y may be a constant or any other value of the
+; narrow type. Rebuilding that expression without nsw becomes a shl/ashr pair,
+; which SCEV cannot treat as a non-wrapping recurrence.
; https://alive2.llvm.org/ce/z/CUWfpR
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
@@ -72,6 +73,92 @@ define i64 @sext_add_nsw_constant_on_lhs(i64 %x) {
ret i64 %e
}
+; The other operand is a non-constant value of the narrow type.
+
+define i64 @sext_add_nsw_of_trunc_nsw_var(i64 %x, i32 %y) {
+; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_nsw_var(
+; CHECK-SAME: i64 [[X:%.*]], i32 [[Y:%.*]]) {
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], [[Y_SEXT]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = add nsw i32 %t, %y
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_sub_nsw_of_trunc_nsw_var(i64 %x, i32 %y) {
+; CHECK-LABEL: define i64 @sext_sub_nsw_of_trunc_nsw_var(
+; CHECK-SAME: i64 [[X:%.*]], i32 [[Y:%.*]]) {
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
+; CHECK-NEXT: [[E:%.*]] = sub nsw i64 [[X]], [[Y_SEXT]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = sub nsw i32 %t, %y
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_sub_nsw_var_minus_trunc_nsw(i64 %x, i32 %y) {
+; CHECK-LABEL: define i64 @sext_sub_nsw_var_minus_trunc_nsw(
+; CHECK-SAME: i64 [[X:%.*]], i32 [[Y:%.*]]) {
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
+; CHECK-NEXT: [[E:%.*]] = sub nsw i64 [[Y_SEXT]], [[X]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = sub nsw i32 %y, %t
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define i64 @sext_mul_nsw_of_trunc_nsw_var(i64 %x, i32 %y) {
+; CHECK-LABEL: define i64 @sext_mul_nsw_of_trunc_nsw_var(
+; CHECK-SAME: i64 [[X:%.*]], i32 [[Y:%.*]]) {
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
+; CHECK-NEXT: [[E:%.*]] = mul nsw i64 [[X]], [[Y_SEXT]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = mul nsw i32 %t, %y
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
+define <2 x i64> @sext_add_nsw_of_trunc_nsw_var_vec(<2 x i64> %x, <2 x i32> %y) {
+; CHECK-LABEL: define <2 x i64> @sext_add_nsw_of_trunc_nsw_var_vec(
+; CHECK-SAME: <2 x i64> [[X:%.*]], <2 x i32> [[Y:%.*]]) {
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext <2 x i32> [[Y]] to <2 x i64>
+; CHECK-NEXT: [[E:%.*]] = add nsw <2 x i64> [[X]], [[Y_SEXT]]
+; CHECK-NEXT: ret <2 x i64> [[E]]
+;
+ %t = trunc nsw <2 x i64> %x to <2 x i32>
+ %s = add nsw <2 x i32> %t, %y
+ %e = sext <2 x i32> %s to <2 x i64>
+ ret <2 x i64> %e
+}
+
+; The narrow add has another use. The sext still widens; the add stays.
+
+define i64 @sext_add_nsw_of_trunc_nsw_var_extra_use(i64 %x, i32 %y) {
+; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_nsw_var_extra_use(
+; CHECK-SAME: i64 [[X:%.*]], i32 [[Y:%.*]]) {
+; CHECK-NEXT: [[T:%.*]] = trunc nsw i64 [[X]] to i32
+; CHECK-NEXT: [[S:%.*]] = add nsw i32 [[Y]], [[T]]
+; CHECK-NEXT: call void @use32(i32 [[S]])
+; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
+; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], [[Y_SEXT]]
+; CHECK-NEXT: ret i64 [[E]]
+;
+ %t = trunc nsw i64 %x to i32
+ %s = add nsw i32 %t, %y
+ call void @use32(i32 %s)
+ %e = sext i32 %s to i64
+ ret i64 %e
+}
+
define <2 x i64> @sext_add_nsw_of_trunc_nsw_vec(<2 x i64> %x) {
; CHECK-LABEL: define <2 x i64> @sext_add_nsw_of_trunc_nsw_vec(
; CHECK-SAME: <2 x i64> [[X:%.*]]) {
>From 6fc4f014f630d21a8d1eac3513e917c2460f1319 Mon Sep 17 00:00:00 2001
From: Junfeng Dong <junfengd at nvidia.com>
Date: Tue, 6 Oct 2026 09:53:37 -0700
Subject: [PATCH 4/4] Require one use when widening sext of an nsw binop
---
.../InstCombine/InstCombineCasts.cpp | 78 +++++++------------
.../InstCombine/sext-of-binop-of-trunc-nsw.ll | 8 +-
2 files changed, 32 insertions(+), 54 deletions(-)
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
index 3481cb29b8be6c..e57ec815b0d1c0 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
@@ -1926,66 +1926,47 @@ bool TypeEvaluationHelper::canEvaluateSExtdPred(Value *V, Type *Ty) {
/// sext (binop nsw (trunc nsw X to iN), Y) to iM
/// to
/// binop nsw X, sext(Y)
-/// when X already has type iM. Y may be a constant, another trunc nsw back to
-/// an iM value, or any other iN value. trunc nsw means X fits in iN, and nsw
-/// on the narrow binop means the result also fits in iN, so the sign-extended
-/// value is that same operation on X and the sign-extended other operand. The
-/// wide binop is nsw because its result fits in iN.
+/// when X already has type iM and the binop has one use. Y may be a constant,
+/// another trunc nsw back to an iM value, or any other iN value. trunc nsw
+/// means X fits in iN, and nsw on the narrow binop means the result also fits
+/// in iN, so the sign-extended value is that same operation on X and the
+/// sign-extended other operand. The wide binop is nsw because its result fits
+/// in iN.
///
-/// A constant Y is folded into sext(Y) immediately. A non-constant Y becomes
-/// an explicit sext, so a loop-invariant narrow operand stays an nsw
-/// recurrence.
+/// CreateSExt folds a constant Y. A non-constant Y becomes an explicit sext,
+/// so a loop-invariant narrow operand stays an nsw recurrence.
///
/// EvaluateInDifferentType rebuilds the binop without overflow flags. The
/// sign-bit check then fails and visitSExt emits a shl/ashr pair, which SCEV
/// cannot treat as a non-wrapping recurrence.
static Instruction *
-foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext, const DataLayout &DL,
- InstCombiner::BuilderTy &Builder) {
+foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext, InstCombiner::BuilderTy &Builder) {
auto *BinOp = dyn_cast<OverflowingBinaryOperator>(Sext.getOperand(0));
- if (!BinOp || !BinOp->hasNoSignedWrap())
+ if (!BinOp || !BinOp->hasOneUse() || !BinOp->hasNoSignedWrap())
return nullptr;
- auto Opc = static_cast<Instruction::BinaryOps>(BinOp->getOpcode());
+ Instruction::BinaryOps Opc =
+ static_cast<Instruction::BinaryOps>(BinOp->getOpcode());
if (Opc != Instruction::Add && Opc != Instruction::Sub &&
Opc != Instruction::Mul)
return nullptr;
- // V is the widened operand. NeedsSExt means V still has the narrow type and
- // must be sign-extended. FromWideTrunc means V is an existing iM value
- // recovered from trunc nsw.
- struct WideOp {
- Value *V = nullptr;
- bool NeedsSExt = false;
- bool FromWideTrunc = false;
- };
+ // At least one operand must be an existing iM value recovered from trunc nsw,
+ // so the fold does not widen arithmetic that was never connected to one.
+ Value *Op0 = BinOp->getOperand(0), *Op1 = BinOp->getOperand(1);
Type *DestTy = Sext.getType();
- auto widenOperand = [&](Value *V) -> WideOp {
- Value *X;
- if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy)
- return {X, false, true};
- if (auto *C = dyn_cast<Constant>(V))
- return {ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL), false,
- false};
- // Any other same-typed value sign-extends to its mathematical value.
- // This is only used when the other operand recovers an existing iM value,
- // so the fold does not widen arithmetic that was never connected to one.
- if (V->getType() == BinOp->getType())
- return {V, true, false};
- return {};
- };
-
- WideOp LHS = widenOperand(BinOp->getOperand(0));
- WideOp RHS = widenOperand(BinOp->getOperand(1));
- if (!LHS.V || !RHS.V || !(LHS.FromWideTrunc || RHS.FromWideTrunc))
+ Value *X0 = nullptr, *X1 = nullptr;
+ bool IsWide0 = match(Op0, m_NSWTrunc(m_SpecificType(DestTy, X0)));
+ bool IsWide1 = match(Op1, m_NSWTrunc(m_SpecificType(DestTy, X1)));
+ if (!IsWide0 && !IsWide1)
return nullptr;
- auto materialize = [&](WideOp Op) -> Value * {
- if (!Op.NeedsSExt)
- return Op.V;
- return Builder.CreateSExt(Op.V, DestTy);
- };
- return BinaryOperator::CreateNSW(Opc, materialize(LHS), materialize(RHS));
+ // CreateSExt folds constants and names the new instruction after Y.
+ Value *Wide0 =
+ IsWide0 ? X0 : Builder.CreateSExt(Op0, DestTy, Op0->getName() + ".sext");
+ Value *Wide1 =
+ IsWide1 ? X1 : Builder.CreateSExt(Op1, DestTy, Op1->getName() + ".sext");
+ return BinaryOperator::CreateNSW(Opc, Wide0, Wide1);
}
Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
@@ -1998,10 +1979,11 @@ Instruction *InstCombinerImpl::visitSExt(SExtInst &Sext) {
return I;
// Do this before EvaluateInDifferentType, which drops nsw and may emit
- // shl/ashr. Do not widen the arithmetic past a legal type.
- if (isa<VectorType>(Sext.getType()) ||
- shouldChangeType(Sext.getSrcTy(), Sext.getType()))
- if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, DL, Builder))
+ // shl/ashr. Do not widen the arithmetic past a legal type; check the scalar
+ // types so that vectors follow the same rule as scalars.
+ if (shouldChangeType(Sext.getSrcTy()->getScalarType(),
+ Sext.getType()->getScalarType()))
+ if (Instruction *I = foldSExtOfNSWBinOpOfTrunc(Sext, Builder))
return I;
Value *Src = Sext.getOperand(0);
diff --git a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
index f4999fee3d522f..9d88068b12185f 100644
--- a/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
+++ b/llvm/test/Transforms/InstCombine/sext-of-binop-of-trunc-nsw.ll
@@ -7,9 +7,6 @@
; which SCEV cannot treat as a non-wrapping recurrence.
; https://alive2.llvm.org/ce/z/CUWfpR
-target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-unknown-linux-gnu"
-
declare void @use32(i32)
define i64 @sext_add_nsw_of_trunc_nsw(i64 %x) {
@@ -140,7 +137,7 @@ define <2 x i64> @sext_add_nsw_of_trunc_nsw_var_vec(<2 x i64> %x, <2 x i32> %y)
ret <2 x i64> %e
}
-; The narrow add has another use. The sext still widens; the add stays.
+; The narrow add has another use, so widening it would duplicate the add.
define i64 @sext_add_nsw_of_trunc_nsw_var_extra_use(i64 %x, i32 %y) {
; CHECK-LABEL: define i64 @sext_add_nsw_of_trunc_nsw_var_extra_use(
@@ -148,8 +145,7 @@ define i64 @sext_add_nsw_of_trunc_nsw_var_extra_use(i64 %x, i32 %y) {
; CHECK-NEXT: [[T:%.*]] = trunc nsw i64 [[X]] to i32
; CHECK-NEXT: [[S:%.*]] = add nsw i32 [[Y]], [[T]]
; CHECK-NEXT: call void @use32(i32 [[S]])
-; CHECK-NEXT: [[Y_SEXT:%.*]] = sext i32 [[Y]] to i64
-; CHECK-NEXT: [[E:%.*]] = add nsw i64 [[X]], [[Y_SEXT]]
+; CHECK-NEXT: [[E:%.*]] = sext i32 [[S]] to i64
; CHECK-NEXT: ret i64 [[E]]
;
%t = trunc nsw i64 %x to i32
More information about the llvm-commits
mailing list