[llvm] [DeadStoreElimination] Optimize tautological assignments (PR #75744)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 3 01:16:18 PST 2024


================
@@ -1901,6 +1901,63 @@ struct DSEState {
     return true;
   }
 
+  // Check if there is a dominating condition, that implies that the value
+  // being stored in a ptr is already present in the ptr.
+  bool dominatingConditionImpliesValue(MemoryDef *Def) {
+    StoreInst *StoreI = dyn_cast<StoreInst>(Def->getMemoryInst());
+    BasicBlock *StoreBB = StoreI->getParent();
+    Value *StorePtr = StoreI->getPointerOperand();
+    Value *StoreVal = StoreI->getValueOperand();
+
+    DomTreeNode *IDom = DT.getNode(StoreBB)->getIDom();
+    if (!IDom)
+      return false;
+
+    auto *BI = dyn_cast<BranchInst>(IDom->getBlock()->getTerminator());
+    if (!BI || !BI->isConditional())
+      return false;
+
+    // In case both blocks are the same, we cannot optimize the FalseBB when the
+    // condition is true and vice versa. Return false in this case.
+    if (BI->getSuccessor(0) == BI->getSuccessor(1))
+      return false;
+
+    // Load can be either of the two operands
+    ICmpInst *CI = dyn_cast<ICmpInst>(BI->getCondition());
+    if (!CI || !CI->isEquality())
+      return false;
+    // Check if load is from the operand that we are storing to.
+    LoadInst *ICmpL = nullptr;
+    Value *ICmpV = nullptr;
+    for (Value *Op : CI->operands()) {
+      LLVM_DEBUG(dbgs() << "Operand: " << *Op << "\n");
+      auto *LI = dyn_cast<LoadInst>(Op);
+      if (LI && LI->getPointerOperand() == StorePtr)
+        ICmpL = LI;
+      if (Op == StoreVal)
+        ICmpV = Op;
+    }
+
+    if (!ICmpL || !ICmpV)
+      return false;
----------------
nikic wrote:

```suggestion
    Instruction *ICmpL;
    ICmpInst::Predicate Pred;
    if (!match(BI->getCondition(), m_c_ICmp(Pred, m_CombineOr(m_Load(StorePtr), m_Instruction(ICmpL)), m_Specific(StoreVal))) ||
        !ICmpInst::isEquality(Pred))
      return false;
```
or so

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


More information about the llvm-commits mailing list