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

Shreyansh Chouhan via llvm-commits llvm-commits at lists.llvm.org
Wed Dec 20 09:32:39 PST 2023


================
@@ -1926,6 +1926,43 @@ struct DSEState {
       if (InitC && InitC == StoredConstant)
         return MSSA.isLiveOnEntryDef(
             MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def, BatchAA));
+
+      if (!Store)
+        return false;
+
+      // If there is a dominating condition, that ensures that the value
+      // being stored in a memory location is already present at the
+      // memory location, the store is a noop.
+      BasicBlock *StoreBB = DefI->getParent();
+      auto *StorePtr = Store->getOperand(1);
+
+      DomTreeNode *IDom = DT.getNode(StoreBB)->getIDom();
+      if (!IDom)
+        return false;
+
+      auto *TI = IDom->getBlock()->getTerminator();
+      ICmpInst::Predicate Pred;
+      BasicBlock *TrueBB, *FalseBB;
+
+      if (!match(TI, m_Br(m_ICmp(Pred, m_Load(m_Specific(StorePtr)),
+                                 m_Specific(StoredConstant)),
+                          TrueBB, FalseBB)))
+        return false;
+
+      MemoryAccess *LastMod =
+          MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def, BatchAA);
+
+      DomTreeNode *CDom = DT.getNode(LastMod->getBlock());
----------------
BK1603 wrote:

Hi @nikic, was not able to understand the concern here. Can you please explain it in more detail?

I'm assuming the line inside the `if` block says `store v, p` (store the value `p` in `v`, if it does not then I do not understand the optimization that is supposed to be happening here. And the patch I pushed should not optimize this either since we would check for both `x` and `p` when we run a match on the icmp statement.)

This should not be optimized and will not be optimized with the current code. The current code checks for exactly StorePtr (v) and StoredConstant(p) in the `icmp` for the `br` that dominates the assignment, and whether these two are related by equality. If they are, and we have entered the current branch, and there were no clobbering accesses in between the current assignment and the conditional check, StorePtr should already contain the value that is being assigned to it.

And if any of these conditions are not met then we assume that the assignment is not redundant.

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


More information about the llvm-commits mailing list