[llvm] [InstCombine] Use sadd.sat for chained ldexp fold (PR #199274)

Justin Lebar via llvm-commits llvm-commits at lists.llvm.org
Fri May 22 16:45:12 PDT 2026


https://github.com/jlebar updated https://github.com/llvm/llvm-project/pull/199274

>From c73fc8663a9a6a327d77acb28d8c9f5dc93a33f0 Mon Sep 17 00:00:00 2001
From: Justin Lebar <justin.lebar at gmail.com>
Date: Fri, 22 May 2026 01:05:43 -0700
Subject: [PATCH 1/3] [InstCombine] Use sadd.sat for chained ldexp fold

ldexp(ldexp(x, a), b) -> ldexp(x, a + b) didn't consider the fact that
`a + b` may overflow!  Use a saturating add instead.

This bug was found by a large run of Opus 4.7 looking for bugs in LLVM.
---
 .../lib/Transforms/InstCombine/InstCombineCalls.cpp |  7 +++----
 llvm/test/Transforms/InstCombine/ldexp.ll           | 13 ++++++++-----
 2 files changed, 11 insertions(+), 9 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 2a8bf3ffecd6f..bff5366520328 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -3198,7 +3198,7 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     break;
   }
   case Intrinsic::ldexp: {
-    // ldexp(ldexp(x, a), b) -> ldexp(x, a + b)
+    // ldexp(ldexp(x, a), b) -> ldexp(x, add.sat(a, b))
     //
     // The danger is if the first ldexp would overflow to infinity or underflow
     // to zero, but the combined exponent avoids it. We ignore this with
@@ -3238,9 +3238,8 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
 
       if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
           signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II))) {
-        // TODO: Add nsw/nuw probably safe if integer type exceeds exponent
-        // width.
-        Value *NewExp = Builder.CreateAdd(InnerExp, Exp);
+        Value *NewExp =
+            Builder.CreateBinaryIntrinsic(Intrinsic::sadd_sat, InnerExp, Exp);
         II->setArgOperand(1, NewExp);
         II->setFastMathFlags(InnerFlags); // Or the inner flags.
         return replaceOperand(*II, 0, InnerSrc);
diff --git a/llvm/test/Transforms/InstCombine/ldexp.ll b/llvm/test/Transforms/InstCombine/ldexp.ll
index e1fd5b45190ac..08a00b8d364e6 100644
--- a/llvm/test/Transforms/InstCombine/ldexp.ll
+++ b/llvm/test/Transforms/InstCombine/ldexp.ll
@@ -368,7 +368,7 @@ define float @ldexp_ldexp_reassoc(float %x, i32 %a, i32 %b) {
 define float @ldexp_reassoc_ldexp_reassoc(float %x, i32 %a, i32 %b) {
 ; CHECK-LABEL: define float @ldexp_reassoc_ldexp_reassoc
 ; CHECK-SAME: (float [[X:%.*]], i32 [[A:%.*]], i32 [[B:%.*]]) {
-; CHECK-NEXT:    [[TMP1:%.*]] = add i32 [[A]], [[B]]
+; CHECK-NEXT:    [[TMP1:%.*]] = call i32 @llvm.sadd.sat.i32(i32 [[A]], i32 [[B]])
 ; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc float @llvm.ldexp.f32.i32(float [[X]], i32 [[TMP1]])
 ; CHECK-NEXT:    ret float [[LDEXP1]]
 ;
@@ -380,7 +380,7 @@ define float @ldexp_reassoc_ldexp_reassoc(float %x, i32 %a, i32 %b) {
 define float @ldexp_reassoc_nsz_ldexp_reassoc_nsz(float %x, i32 %a, i32 %b) {
 ; CHECK-LABEL: define float @ldexp_reassoc_nsz_ldexp_reassoc_nsz
 ; CHECK-SAME: (float [[X:%.*]], i32 [[A:%.*]], i32 [[B:%.*]]) {
-; CHECK-NEXT:    [[TMP1:%.*]] = add i32 [[A]], [[B]]
+; CHECK-NEXT:    [[TMP1:%.*]] = call i32 @llvm.sadd.sat.i32(i32 [[A]], i32 [[B]])
 ; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc nsz float @llvm.ldexp.f32.i32(float [[X]], i32 [[TMP1]])
 ; CHECK-NEXT:    ret float [[LDEXP1]]
 ;
@@ -393,7 +393,7 @@ define float @ldexp_reassoc_nsz_ldexp_reassoc_nsz(float %x, i32 %a, i32 %b) {
 define float @ldexp_reassoc_ldexp_reassoc_preserve_flags(float %x, i32 %a, i32 %b) {
 ; CHECK-LABEL: define float @ldexp_reassoc_ldexp_reassoc_preserve_flags
 ; CHECK-SAME: (float [[X:%.*]], i32 [[A:%.*]], i32 [[B:%.*]]) {
-; CHECK-NEXT:    [[TMP1:%.*]] = add i32 [[A]], [[B]]
+; CHECK-NEXT:    [[TMP1:%.*]] = call i32 @llvm.sadd.sat.i32(i32 [[A]], i32 [[B]])
 ; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc nnan ninf float @llvm.ldexp.f32.i32(float [[X]], i32 [[TMP1]])
 ; CHECK-NEXT:    ret float [[LDEXP1]]
 ;
@@ -405,7 +405,7 @@ define float @ldexp_reassoc_ldexp_reassoc_preserve_flags(float %x, i32 %a, i32 %
 define <2 x float> @ldexp_reassoc_ldexp_reassoc_vec(<2 x float> %x, <2 x i32> %a, <2 x i32> %b) {
 ; CHECK-LABEL: define <2 x float> @ldexp_reassoc_ldexp_reassoc_vec
 ; CHECK-SAME: (<2 x float> [[X:%.*]], <2 x i32> [[A:%.*]], <2 x i32> [[B:%.*]]) {
-; CHECK-NEXT:    [[TMP1:%.*]] = add <2 x i32> [[A]], [[B]]
+; CHECK-NEXT:    [[TMP1:%.*]] = call <2 x i32> @llvm.sadd.sat.v2i32(<2 x i32> [[A]], <2 x i32> [[B]])
 ; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc <2 x float> @llvm.ldexp.v2f32.v2i32(<2 x float> [[X]], <2 x i32> [[TMP1]])
 ; CHECK-NEXT:    ret <2 x float> [[LDEXP1]]
 ;
@@ -498,7 +498,10 @@ define float @ldexp_ldexp_opposite_constants(float %x) {
 define float @ldexp_ldexp_negated_variable_reassoc(float %x, i32 %a) {
 ; CHECK-LABEL: define float @ldexp_ldexp_negated_variable_reassoc
 ; CHECK-SAME: (float [[X:%.*]], i32 [[A:%.*]]) {
-; CHECK-NEXT:    ret float [[X]]
+; CHECK-NEXT:    [[NEG_A:%.*]] = sub i32 0, [[A]]
+; CHECK-NEXT:    [[TMP1:%.*]] = call i32 @llvm.sadd.sat.i32(i32 [[A]], i32 [[NEG_A]])
+; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc float @llvm.ldexp.f32.i32(float [[X]], i32 [[TMP1]])
+; CHECK-NEXT:    ret float [[LDEXP1]]
 ;
   %ldexp0 = call reassoc float @llvm.ldexp.f32.i32(float %x, i32 %a)
   %neg.a = sub i32 0, %a

>From fef5a127fe019ea4b51ef840a99002eb7d08a64a Mon Sep 17 00:00:00 2001
From: Justin Lebar <justin.lebar at gmail.com>
Date: Fri, 22 May 2026 16:42:29 -0700
Subject: [PATCH 2/3] Handle the case where INT_MAX isn't big enough to pin
 ldexp to 0 or inf.

---
 .../InstCombine/InstCombineCalls.cpp          | 60 ++++++++++++++-----
 llvm/test/Transforms/InstCombine/ldexp.ll     | 51 ++++++++++++++++
 2 files changed, 96 insertions(+), 15 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index bff5366520328..1449700bb4343 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -1224,6 +1224,32 @@ static bool signBitMustBeTheSame(Value *Op0, Value *Op1,
   return *Known0 == *Known1;
 }
 
+// Determines if ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b)) is safe.
+//
+// This is true if, when the add saturates, the resulting ldexp is guaranteed to
+// produce 0 or inf.
+static bool ldexpSaturatingAddIsSafe(Type *FpTy, Type *ExpTy) {
+  const fltSemantics &FltSem = FpTy->getScalarType()->getFltSemantics();
+  if (!APFloat::semanticsHasInf(FltSem))
+    return false;
+
+  // scalbn takes int, but proving that i32 bounds already force
+  // overflow/underflow is sufficient for wider exponent types.
+  unsigned ExpBits = std::min(ExpTy->getScalarSizeInBits(), 32u);
+  int SignedMax =
+      static_cast<int>(APInt::getSignedMaxValue(ExpBits).getSExtValue());
+  int SignedMin =
+      static_cast<int>(APInt::getSignedMinValue(ExpBits).getSExtValue());
+
+  APFloat ScaledUp =
+      scalbn(APFloat::getSmallest(FltSem), SignedMax,
+             APFloat::rmNearestTiesToEven);
+  APFloat ScaledDown =
+      scalbn(APFloat::getLargest(FltSem), SignedMin,
+             APFloat::rmNearestTiesToEven);
+  return ScaledUp.isInfinity() && ScaledDown.isZero();
+}
+
 /// Try to canonicalize min/max(X + C0, C1) as min/max(X, C1 - C0) + C0. This
 /// can trigger other combines.
 static Instruction *moveAddAfterMinMax(IntrinsicInst *II,
@@ -3198,24 +3224,12 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     break;
   }
   case Intrinsic::ldexp: {
-    // ldexp(ldexp(x, a), b) -> ldexp(x, add.sat(a, b))
-    //
-    // The danger is if the first ldexp would overflow to infinity or underflow
-    // to zero, but the combined exponent avoids it. We ignore this with
-    // reassoc.
-    //
-    // It's also safe to fold if we know both exponents are >= 0 or <= 0 since
-    // it would just double down on the overflow/underflow which would occur
-    // anyway.
-    //
-    // TODO: Could do better if we had range tracking for the input value
-    // exponent. Also could broaden sign check to cover == 0 case.
     Value *Src = II->getArgOperand(0);
     Value *Exp = II->getArgOperand(1);
 
+    // ldexp(x, K) -> fmul x, 2^K
     uint64_t ConstExp;
     if (match(Exp, m_ConstantInt(ConstExp))) {
-      // ldexp(x, K) -> fmul x, 2^K
       const fltSemantics &FPTy =
           Src->getType()->getScalarType()->getFltSemantics();
 
@@ -3228,6 +3242,21 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
       }
     }
 
+    // ldexp(ldexp(x, a), b) -> ldexp(x, sadd.sat(a, b))
+    //
+    // A danger is if the first ldexp would overflow to infinity or underflow to
+    // zero, but the combined exponent avoids it.
+    //
+    // We ignore this with reassoc, or if we know both exponents have the same
+    // sign (since then we'd just double down on the over/underflow which would
+    // occur anyway).
+    //
+    // ldexp can take arbitrary integer types, so we also need to ensure that our
+    // exponent type is wide enough so that if sadd.sat(a, b) saturates, then
+    // ldexp at the saturated exponent saturates to inf or zero as well.
+    //
+    // TODO: Could do better if we had range tracking for the input value
+    // exponent. Also could broaden sign check to cover == 0 case.
     Value *InnerSrc;
     Value *InnerExp;
     if (match(Src, m_OneUse(m_Intrinsic<Intrinsic::ldexp>(
@@ -3236,8 +3265,9 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
       FastMathFlags FMF = II->getFastMathFlags();
       FastMathFlags InnerFlags = cast<FPMathOperator>(Src)->getFastMathFlags();
 
-      if ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
-          signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II))) {
+      if (ldexpSaturatingAddIsSafe(II->getType(), Exp->getType()) &&
+          ((FMF.allowReassoc() && InnerFlags.allowReassoc()) ||
+           signBitMustBeTheSame(Exp, InnerExp, SQ.getWithInstruction(II)))) {
         Value *NewExp =
             Builder.CreateBinaryIntrinsic(Intrinsic::sadd_sat, InnerExp, Exp);
         II->setArgOperand(1, NewExp);
diff --git a/llvm/test/Transforms/InstCombine/ldexp.ll b/llvm/test/Transforms/InstCombine/ldexp.ll
index 08a00b8d364e6..a68cb2bc1fd05 100644
--- a/llvm/test/Transforms/InstCombine/ldexp.ll
+++ b/llvm/test/Transforms/InstCombine/ldexp.ll
@@ -4,6 +4,9 @@
 declare float @llvm.ldexp.f32.i32(float, i32)
 declare <2 x float> @llvm.ldexp.v2f32.v2i32(<2 x float>, <2 x i32>)
 declare float @llvm.ldexp.f32.i64(float, i64)
+declare half @llvm.ldexp.f16.i8(half, i8)
+declare float @llvm.ldexp.f32.i8(float, i8)
+declare ppc_fp128 @llvm.ldexp.ppcf128.i32(ppc_fp128, i32)
 
 ; select c, (ldexp val, e0), (ldexp val, e1) -> ldexp val, (select c, e0, e1)
 define float @select_ldexp_f32_sameval_differentexp(i1 %cond, float %val, i32 %exp0, i32 %exp1) {
@@ -414,6 +417,54 @@ define <2 x float> @ldexp_reassoc_ldexp_reassoc_vec(<2 x float> %x, <2 x i32> %a
   ret <2 x float> %ldexp1
 }
 
+define float @ldexp_reassoc_ldexp_reassoc_i8_exp_not_safe(float %x, i8 %a, i8 %b) {
+; CHECK-LABEL: define float @ldexp_reassoc_ldexp_reassoc_i8_exp_not_safe
+; CHECK-SAME: (float [[X:%.*]], i8 [[A:%.*]], i8 [[B:%.*]]) {
+; CHECK-NEXT:    [[LDEXP0:%.*]] = call reassoc float @llvm.ldexp.f32.i8(float [[X]], i8 [[A]])
+; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc float @llvm.ldexp.f32.i8(float [[LDEXP0]], i8 [[B]])
+; CHECK-NEXT:    ret float [[LDEXP1]]
+;
+  %ldexp0 = call reassoc float @llvm.ldexp.f32.i8(float %x, i8 %a)
+  %ldexp1 = call reassoc float @llvm.ldexp.f32.i8(float %ldexp0, i8 %b)
+  ret float %ldexp1
+}
+
+define float @ldexp_reassoc_ldexp_reassoc_i64_exp_safe(float %x, i64 %a, i64 %b) {
+; CHECK-LABEL: define float @ldexp_reassoc_ldexp_reassoc_i64_exp_safe
+; CHECK-SAME: (float [[X:%.*]], i64 [[A:%.*]], i64 [[B:%.*]]) {
+; CHECK-NEXT:    [[TMP1:%.*]] = call i64 @llvm.sadd.sat.i64(i64 [[A]], i64 [[B]])
+; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc float @llvm.ldexp.f32.i64(float [[X]], i64 [[TMP1]])
+; CHECK-NEXT:    ret float [[LDEXP1]]
+;
+  %ldexp0 = call reassoc float @llvm.ldexp.f32.i64(float %x, i64 %a)
+  %ldexp1 = call reassoc float @llvm.ldexp.f32.i64(float %ldexp0, i64 %b)
+  ret float %ldexp1
+}
+
+define half @ldexp_reassoc_ldexp_reassoc_f16_i8_exp_safe(half %x, i8 %a, i8 %b) {
+; CHECK-LABEL: define half @ldexp_reassoc_ldexp_reassoc_f16_i8_exp_safe
+; CHECK-SAME: (half [[X:%.*]], i8 [[A:%.*]], i8 [[B:%.*]]) {
+; CHECK-NEXT:    [[TMP1:%.*]] = call i8 @llvm.sadd.sat.i8(i8 [[A]], i8 [[B]])
+; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc half @llvm.ldexp.f16.i8(half [[X]], i8 [[TMP1]])
+; CHECK-NEXT:    ret half [[LDEXP1]]
+;
+  %ldexp0 = call reassoc half @llvm.ldexp.f16.i8(half %x, i8 %a)
+  %ldexp1 = call reassoc half @llvm.ldexp.f16.i8(half %ldexp0, i8 %b)
+  ret half %ldexp1
+}
+
+define ppc_fp128 @ldexp_reassoc_ldexp_reassoc_ppcf128(ppc_fp128 %x, i32 %a, i32 %b) {
+; CHECK-LABEL: define ppc_fp128 @ldexp_reassoc_ldexp_reassoc_ppcf128
+; CHECK-SAME: (ppc_fp128 [[X:%.*]], i32 [[A:%.*]], i32 [[B:%.*]]) {
+; CHECK-NEXT:    [[TMP1:%.*]] = call i32 @llvm.sadd.sat.i32(i32 [[A]], i32 [[B]])
+; CHECK-NEXT:    [[LDEXP1:%.*]] = call reassoc ppc_fp128 @llvm.ldexp.ppcf128.i32(ppc_fp128 [[X]], i32 [[TMP1]])
+; CHECK-NEXT:    ret ppc_fp128 [[LDEXP1]]
+;
+  %ldexp0 = call reassoc ppc_fp128 @llvm.ldexp.ppcf128.i32(ppc_fp128 %x, i32 %a)
+  %ldexp1 = call reassoc ppc_fp128 @llvm.ldexp.ppcf128.i32(ppc_fp128 %ldexp0, i32 %b)
+  ret ppc_fp128 %ldexp1
+}
+
 define float @ldexp_multi_use_ldexp(float %x, i32 %a, i32 %b, ptr %ptr) {
 ; CHECK-LABEL: define float @ldexp_multi_use_ldexp
 ; CHECK-SAME: (float [[X:%.*]], i32 [[A:%.*]], i32 [[B:%.*]], ptr [[PTR:%.*]]) {

>From fcb66cabce5d43730e141dbf0a5e6d597244ddc6 Mon Sep 17 00:00:00 2001
From: Justin Lebar <justin.lebar at gmail.com>
Date: Fri, 22 May 2026 16:44:58 -0700
Subject: [PATCH 3/3] clang-format

---
 .../Transforms/InstCombine/InstCombineCalls.cpp  | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 1449700bb4343..d323511e2d380 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -1241,12 +1241,10 @@ static bool ldexpSaturatingAddIsSafe(Type *FpTy, Type *ExpTy) {
   int SignedMin =
       static_cast<int>(APInt::getSignedMinValue(ExpBits).getSExtValue());
 
-  APFloat ScaledUp =
-      scalbn(APFloat::getSmallest(FltSem), SignedMax,
-             APFloat::rmNearestTiesToEven);
-  APFloat ScaledDown =
-      scalbn(APFloat::getLargest(FltSem), SignedMin,
-             APFloat::rmNearestTiesToEven);
+  APFloat ScaledUp = scalbn(APFloat::getSmallest(FltSem), SignedMax,
+                            APFloat::rmNearestTiesToEven);
+  APFloat ScaledDown = scalbn(APFloat::getLargest(FltSem), SignedMin,
+                              APFloat::rmNearestTiesToEven);
   return ScaledUp.isInfinity() && ScaledDown.isZero();
 }
 
@@ -3251,9 +3249,9 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     // sign (since then we'd just double down on the over/underflow which would
     // occur anyway).
     //
-    // ldexp can take arbitrary integer types, so we also need to ensure that our
-    // exponent type is wide enough so that if sadd.sat(a, b) saturates, then
-    // ldexp at the saturated exponent saturates to inf or zero as well.
+    // ldexp can take arbitrary integer types, so we also need to ensure that
+    // our exponent type is wide enough so that if sadd.sat(a, b) saturates,
+    // then ldexp at the saturated exponent saturates to inf or zero as well.
     //
     // TODO: Could do better if we had range tracking for the input value
     // exponent. Also could broaden sign check to cover == 0 case.



More information about the llvm-commits mailing list