[llvm] [InstCombine] fold (A + B - C == B) -> (A == C). (PR #76129)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Thu Dec 28 23:59:57 PST 2023


================
@@ -4547,6 +4547,48 @@ static Instruction *foldICmpXorXX(ICmpInst &I, const SimplifyQuery &Q,
   return nullptr;
 }
 
+// extract common factors like ((A + B) - C == B) -> (A - C == 0)
+Instruction *InstCombinerImpl::foldICmpWithCommonFactors(ICmpInst &Cmp,
+                                                         BinaryOperator *LBO,
+                                                         Value *RHS) {
+  const CmpInst::Predicate Pred = Cmp.getPredicate();
+  if (!ICmpInst::isEquality(Pred))
+    return nullptr;
+
+  if (LBO->getOpcode() != Instruction::Add &&
+      LBO->getOpcode() != Instruction::Sub)
+    return nullptr;
+
+  SmallVector<BinaryOperator *, 16> worklist;
+
+  auto AddNextBO = [&](Value *Op) {
+    if (BinaryOperator *Next = dyn_cast<BinaryOperator>(Op))
+      worklist.push_back(Next);
+  };
+
+  AddNextBO(LBO->getOperand(0));
+  AddNextBO(LBO->getOperand(1));
+
+  while (!worklist.empty()) {
+    BinaryOperator *BO = worklist.pop_back_val();
+
+    if (Value * A; match(BO, m_OneUse(m_c_Add(m_Value(A), m_Specific(RHS))))) {
+      replaceInstUsesWith(*BO, A);
+      eraseInstFromFunction(*BO);
+      Constant *Zero = Constant::getNullValue(LBO->getType());
+      return new ICmpInst(Pred, LBO, Zero);
+    }
+
+    unsigned Opc = BO->getOpcode();
+    if (Opc == Instruction::Add || Opc == Instruction::Sub) {
----------------
dtcxzyw wrote:

I don't think it is correct.
`(A - (A + B)) == B` will be folded into `A - A == 0`.


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


More information about the llvm-commits mailing list