[llvm] [InstCombine] Fold shifts + selects with -1 to scmp(X, 0) (PR #164129)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Mon Oct 20 09:35:23 PDT 2025


================
@@ -4680,5 +4680,31 @@ Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
                                      Align(MaskedLoadAlignment->getZExtValue()),
                                      CondVal, FalseVal));
 
+  // Canonicalize sign function ashr pattern: select (icmp slt X, 1), ashr X,
+  // bitwidth-1, 1 -> scmp(X, 0)
+  // Also handles: select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
+  Value *X;
+  unsigned BitWidth = SI.getType()->getScalarSizeInBits();
+  CmpPredicate Pred;
+  Value *CmpLHS, *CmpRHS;
+
+  // Canonicalize sign function ashr patterns:
+  // select (icmp slt X, 1), ashr X, bitwidth-1, 1 -> scmp(X, 0)
+  // select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
+  if (match(&SI, m_Select(m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)),
+                          m_Value(TrueVal), m_Value(FalseVal))) &&
+      ((Pred == ICmpInst::ICMP_SLT && match(CmpLHS, m_Value(X)) &&
+        match(CmpRHS, m_One()) &&
+        match(TrueVal, m_AShr(m_Deferred(X), m_SpecificInt(BitWidth - 1))) &&
+        match(FalseVal, m_One())) ||
+       (Pred == ICmpInst::ICMP_SGT && match(CmpLHS, m_Value(X)) &&
+        match(CmpRHS, m_Zero()) && match(TrueVal, m_One()) &&
+        match(FalseVal, m_AShr(m_Deferred(X), m_SpecificInt(BitWidth - 1)))))) {
----------------
dtcxzyw wrote:

```suggestion
      ((Pred == ICmpInst::ICMP_SLT &&
        match(CmpRHS, m_One()) &&
        match(TrueVal, m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1))) &&
        match(FalseVal, m_One())) ||
       (Pred == ICmpInst::ICMP_SGT &&
        match(CmpRHS, m_Zero()) && match(TrueVal, m_One()) &&
        match(FalseVal, m_AShr(m_Specific(CmpLHS), m_SpecificInt(BitWidth - 1)))))) {
```


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


More information about the llvm-commits mailing list