[llvm] Add flipped version of (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C) (PR #97973)

via llvm-commits llvm-commits at lists.llvm.org
Sun Jul 7 15:00:28 PDT 2024


https://github.com/AtariDreams created https://github.com/llvm/llvm-project/pull/97973

For some reason, LLVM is not considering X u > C, a, b to be the same as X <= C, b, a, so add that case here.

>From 2fcb9c7e1f5f8893dff4de703abd3f5daaad7871 Mon Sep 17 00:00:00 2001
From: Rose <gfunni234 at gmail.com>
Date: Sun, 7 Jul 2024 17:51:02 -0400
Subject: [PATCH] Add flipped version of (X u< ~C) ? (X + C) : -1 -->
 uadd.sat(X, C)

For some reason, LLVM is not considering X u > C, a, b to be the same as X <= C, b, a, so add that case here.
---
 .../lib/Transforms/InstCombine/InstCombineSelect.cpp |  8 ++++++++
 .../Transforms/InstCombine/saturating-add-sub.ll     | 12 ++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
index 394dfca262e130..4ab8106d557616 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
@@ -985,6 +985,14 @@ static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
     return Builder.CreateBinaryIntrinsic(
         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
   }
+  if (Pred == ICmpInst::ICMP_UGT &&
+      match(FVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
+      match(TVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) &&
+      *CmpC == (~*C - 1)) {
+    // (X u > ~C - 1) ? -1, (X + C) --> uadd.sat(X, C)
+    return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X,
+                                         ConstantInt::get(X->getType(), *C));
+  }
 
   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
   // There are 8 commuted variants.
diff --git a/llvm/test/Transforms/InstCombine/saturating-add-sub.ll b/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
index bf1568f1cd8c09..d220109ac17c05 100644
--- a/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
+++ b/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
@@ -1395,6 +1395,18 @@ define i32 @uadd_sat(i32 %x, i32 %y) {
   %r = select i1 %c, i32 -1, i32 %a
   ret i32 %r
 }
+
+define i32 @uadd_sat_flipped(i32 %x) {
+; CHECK-LABEL: @uadd_sat_flipped(
+; CHECK-NEXT:    [[COND:%.*]] = tail call i32 @llvm.uadd.sat.i32(i32 %x, i32 9)
+; CHECK-NEXT:    ret i32 [[COND]]
+;
+  %cmp = icmp uge i32 %x, -10
+  %add = add i32 %x, 9
+  %cond = select i1 %cmp, i32 -1, i32 %add
+  ret i32 %cond
+}
+
 define i32 @uadd_sat_nonstrict(i32 %x, i32 %y) {
 ; CHECK-LABEL: @uadd_sat_nonstrict(
 ; CHECK-NEXT:    [[R:%.*]] = call i32 @llvm.uadd.sat.i32(i32 [[X:%.*]], i32 [[Y:%.*]])



More information about the llvm-commits mailing list