[llvm] Reland [InstCombine] Teach foldSelectOpOp about samesign (PR #124320)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jan 27 09:33:51 PST 2025


================
@@ -423,23 +423,28 @@ Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
       }
     }
 
+    auto CreateCmpSel = [&](CmpPredicate P, Value *MatchOp) {
+      Value *NewSel = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
+                                           SI.getName() + ".v", &SI);
+      return new ICmpInst(MatchIsOpZero ? P
+                                        : ICmpInst::getSwappedCmpPredicate(P),
+                          MatchOp, NewSel);
+    };
+
     // icmp with a common operand also can have the common operand
     // pulled after the select.
     CmpPredicate TPred, FPred;
     if (match(TI, m_ICmp(TPred, m_Value(), m_Value())) &&
         match(FI, m_ICmp(FPred, m_Value(), m_Value()))) {
-      // FIXME: Use CmpPredicate::getMatching here.
-      CmpInst::Predicate T = TPred, F = FPred;
-      if (T == F || T == ICmpInst::getSwappedCmpPredicate(F)) {
-        bool Swapped = T != F;
+      if (auto P = CmpPredicate::getMatching(TPred, FPred)) {
         if (Value *MatchOp =
-                getCommonOp(TI, FI, ICmpInst::isEquality(TPred), Swapped)) {
-          Value *NewSel = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
-                                               SI.getName() + ".v", &SI);
-          return new ICmpInst(
-              MatchIsOpZero ? TPred : ICmpInst::getSwappedCmpPredicate(TPred),
-              MatchOp, NewSel);
-        }
+                getCommonOp(TI, FI, ICmpInst::isEquality(*P), false))
+          return CreateCmpSel(*P, MatchOp);
+      } else if (auto P = CmpPredicate::getMatching(
+                     TPred, ICmpInst::getSwappedCmpPredicate(FPred))) {
+        if (Value *MatchOp =
+                getCommonOp(TI, FI, ICmpInst::isEquality(*P), true))
+          return CreateCmpSel(*P, MatchOp);
----------------
goldsteinn wrote:

Think could be simplified a fair bit if you factored more logic into `CreateCmpSel`:
i.e

```
auto CreateCmpSel = [&](std::optional<CmpPredicate> P, bool Swapped) {
  if(!P)
    return nullptr;
  auto * MatchOp = getCommonOp(TI, FI, ICmpInst::isEquality(*P), Swapped);
  if (!MatchOp)
    return nullptr;
  // What you currently have.
};

if(auto * R = CreateCmpSel(CmpPredicate::getMatching(TPred, FPred), /*Swapped=*/false))
  return R;
if(auto * R = CreateCmpSel(CmpPredicate::getMatching(TPred,ICmpInst::getSwappedCmpPredicate(FPred)), /*Swapped=*/true))
  return R;

```

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


More information about the llvm-commits mailing list