[llvm] [llvm] Optimize usub.sat fix for #79690 (PR #151044)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 24 04:56:33 PDT 2025


================
@@ -1993,6 +1991,85 @@ Value *InstCombinerImpl::foldSelectWithConstOpToBinOp(ICmpInst *Cmp,
   return BinOp;
 }
 
+/// Folds:
+///   %a_sub = call @llvm.usub.sat(x, IntConst1)
+///   %b_sub = call @llvm.usub.sat(y, IntConst2)
+///   %or = or %a_sub, %b_sub
+///   %cmp = icmp eq %or, 0
+///   %sel = select %cmp, 0, MostSignificantBit
+/// into:
+///   %a_sub' = usub.sat(x, IntConst1 - MostSignificantBit)
+///   %b_sub' = usub.sat(y, IntConst2 - MostSignificantBit)
+///   %or = or %a_sub', %b_sub'
+///   %and = and %or, MostSignificantBit
+/// Likewise, for vector arguments as well.
+static Instruction *foldICmpUSubSatWithAndForMostSignificantBitCmp(
+    SelectInst &SI, ICmpInst *ICI, InstCombiner::BuilderTy &Builder) {
+  auto *CI = dyn_cast<ICmpInst>(SI.getCondition());
+  if (!CI)
+    return nullptr;
+
+  Value *CmpLHS = CI->getOperand(0);
+  Value *CmpRHS = CI->getOperand(1);
+  if (!match(CmpRHS, m_Zero()))
+    return nullptr;
+
+  auto Pred = CI->getPredicate();
+  if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
+    return nullptr;
+
+  Value *A, *B;
+  const APInt *Constant1, *Constant2, *PossibleMSB;
+  if (!match(CmpLHS, m_Or(m_Intrinsic<Intrinsic::usub_sat>(m_Value(A),
+                                                           m_APInt(Constant1)),
+                          m_Intrinsic<Intrinsic::usub_sat>(
+                              m_Value(B), m_APInt(Constant2)))))
+    return nullptr;
+
+  Value *TrueVal = SI.getTrueValue();
+  Value *FalseVal = SI.getFalseValue();
+  if (!((match(TrueVal, m_Zero()) && match(FalseVal, m_APInt(PossibleMSB))) ||
+        (match(TrueVal, m_APInt(PossibleMSB)) && match(FalseVal, m_Zero()))))
+    return nullptr;
+
+  auto *Ty = A->getType();
+  auto *VecTy = dyn_cast<VectorType>(Ty);
+  unsigned BW = PossibleMSB->getBitWidth();
+  APInt MostSignificantBit = APInt::getOneBitSet(BW, BW - 1);
----------------
dtcxzyw wrote:

```suggestion
  APInt MostSignificantBit = APInt::getSignMask(BW);
```

https://github.com/llvm/llvm-project/pull/151044


More information about the llvm-commits mailing list