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

Shreyansh Chouhan via llvm-commits llvm-commits at lists.llvm.org
Sat Jan 6 09:01:54 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;
+
+    MemoryAccess *LoadAcc, *ClobAcc;
+    LoadAcc = MSSA.getMemoryAccess(ICmpL)->getDefiningAccess();
----------------
BK1603 wrote:

I was using the code in `storeIsNoop` function as reference, we perform a similar check there where we check if we are storing to a pointer a load from the same pointer.
Over there we check for equality between the defining access of the load and the clobbering access of the store instead of checking if the clobbering access of the store dominates the load (which is what I think we are effectiively checking?) so I thought of it as the way it is done instead.

In case I understood this wrong please correct me.

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


More information about the llvm-commits mailing list