[llvm] [MemorySSA] Make getPreviousDef iterative to avoid stack overflow (PR #205159)

Antonio Frighetto via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 23 01:37:51 PDT 2026


================
@@ -33,101 +33,214 @@ using namespace llvm;
 // that there are two or more definitions needing to be merged.
 // This still will leave non-minimal form in the case of irreducible control
 // flow, where phi nodes may be in cycles with themselves, but unnecessary.
-MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(
+//
+// This is an iterative (explicit worklist) reformulation of the previously
+// recursive getPreviousDefRecursive, which was mutually recursive with
+// getPreviousDefFromEnd. The recursion depth scaled with the length of the
+// predecessor walk, so deep CFGs (e.g. long block chains in large generated
+// kernels/shaders) could overflow the native stack. Each StackFrame mirrors
+// one getPreviousDefRecursive activation; the Stage records where to resume
+// after a spawned child block has produced its result (returned via Returned).
+// All observable behaviour is preserved: cache lookups/inserts, VisitedBlocks
+// cycle detection (including the single-predecessor insert-without-erase
+// asymmetry), predecessor operand order, and phi simplification/creation.
+MemoryAccess *MemorySSAUpdater::getPreviousDefIterative(
     BasicBlock *BB,
     DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
-  // First, do a cache lookup. Without this cache, certain CFG structures
-  // (like a series of if statements) take exponential time to visit.
-  auto Cached = CachedPreviousDef.find(BB);
-  if (Cached != CachedPreviousDef.end())
-    return Cached->second;
-
-  // If this method is called from an unreachable block, return LoE.
-  if (!MSSA->DT->isReachableFromEntry(BB))
-    return MSSA->getLiveOnEntryDef();
-
-  if (BasicBlock *Pred = BB->getUniquePredecessor()) {
-    VisitedBlocks.insert(BB);
-    // Single predecessor case, just recurse, we can only have one definition.
-    MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef);
-    CachedPreviousDef.insert({BB, Result});
-    return Result;
-  }
-
-  if (VisitedBlocks.count(BB)) {
-    // We hit our node again, meaning we had a cycle, we must insert a phi
-    // node to break it so we have an operand. The only case this will
-    // insert useless phis is if we have irreducible control flow.
-    MemoryAccess *Result = MSSA->createMemoryPhi(BB);
-    CachedPreviousDef.insert({BB, Result});
-    return Result;
-  }
+  // Resume point for a frame after a child block's result becomes available.
+  enum class Stage {
+    EnterBlock,       // initial entry into getPreviousDefRecursive(BB)
+    ResumeSinglePred, // resuming after the single-predecessor recursion
+    RunPredLoop,      // running/resuming the multi-predecessor loop
+  };
 
-  if (VisitedBlocks.insert(BB).second) {
-    // Mark us visited so we can detect a cycle
+  struct StackFrame {
+    BasicBlock *BB;
+    Stage St = Stage::EnterBlock;
+    // Multi-predecessor loop state.
     SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps;
-
-    // Recurse to get the values in our predecessors for placement of a
-    // potential phi node. This will insert phi nodes if we cycle in order to
-    // break the cycle and have an operand.
+    SmallVector<BasicBlock *, 8> Preds;
+    unsigned PredIdx = 0;
+    bool PendingIncoming =
+        false; // Returned holds the result for Preds[PredIdx]
     bool UniqueIncomingAccess = true;
     MemoryAccess *SingleAccess = nullptr;
-    for (auto *Pred : predecessors(BB)) {
-      if (MSSA->DT->isReachableFromEntry(Pred)) {
-        auto *IncomingAccess = getPreviousDefFromEnd(Pred, CachedPreviousDef);
-        if (!SingleAccess)
-          SingleAccess = IncomingAccess;
-        else if (IncomingAccess != SingleAccess)
-          UniqueIncomingAccess = false;
-        PhiOps.push_back(IncomingAccess);
-      } else
-        PhiOps.push_back(MSSA->getLiveOnEntryDef());
-    }
+  };
+
+  // Fold an incoming predecessor access into the current frame's phi operands,
+  // tracking whether all incoming accesses are identical (so the phi may be
+  // elided). Mirrors the body of the predecessor loop in the recursive version.
+  auto Incorporate = [](StackFrame &Fr, MemoryAccess *Incoming) {
+    if (!Fr.SingleAccess)
+      Fr.SingleAccess = Incoming;
+    else if (Incoming != Fr.SingleAccess)
+      Fr.UniqueIncomingAccess = false;
+    Fr.PhiOps.push_back(Incoming);
+  };
+
+  SmallVector<StackFrame, 8> WorkStack;
+  WorkStack.push_back({BB});
+  // Carries a completed child frame's result back to its parent, exactly as a
+  // recursive return value would.
+  MemoryAccess *Returned = nullptr;
+
+  while (!WorkStack.empty()) {
+    // NOTE: WorkStack.push_back below may reallocate and invalidate this
+    // reference, so every code path that pushes a new frame sets the resume
+    // Stage on the current frame *before* pushing and then continues the loop
+    // without touching the reference again.
+    StackFrame &F = WorkStack.back();
+    BasicBlock *CurBB = F.BB;
+
+    switch (F.St) {
+    case Stage::EnterBlock: {
+      // First, do a cache lookup. Without this cache, certain CFG structures
+      // (like a series of if statements) take exponential time to visit.
+      auto Cached = CachedPreviousDef.find(CurBB);
+      if (Cached != CachedPreviousDef.end()) {
+        Returned = Cached->second;
+        WorkStack.pop_back();
+        continue;
+      }
 
-    // Now try to simplify the ops to avoid placing a phi.
-    // This may return null if we never created a phi yet, that's okay
-    MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
-
-    // See if we can avoid the phi by simplifying it.
-    auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
-    // If we couldn't simplify, we may have to create a phi
-    if (Result == Phi && UniqueIncomingAccess && SingleAccess) {
-      // A concrete Phi only exists if we created an empty one to break a cycle.
-      if (Phi) {
-        assert(Phi->operands().empty() && "Expected empty Phi");
-        Phi->replaceAllUsesWith(SingleAccess);
-        removeMemoryAccess(Phi);
+      // If this method is called from an unreachable block, return LoE.
+      if (!MSSA->DT->isReachableFromEntry(CurBB)) {
+        Returned = MSSA->getLiveOnEntryDef();
+        WorkStack.pop_back();
+        continue;
       }
-      Result = SingleAccess;
-    } else if (Result == Phi && !(UniqueIncomingAccess && SingleAccess)) {
-      if (!Phi)
-        Phi = MSSA->createMemoryPhi(BB);
-
-      // See if the existing phi operands match what we need.
-      // Unlike normal SSA, we only allow one phi node per block, so we can't just
-      // create a new one.
-      if (Phi->getNumOperands() != 0) {
-        // FIXME: Figure out whether this is dead code and if so remove it.
-        if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
-          // These will have been filled in by the recursive read we did above.
-          llvm::copy(PhiOps, Phi->op_begin());
-          std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
+
+      if (BasicBlock *Pred = CurBB->getUniquePredecessor()) {
+        VisitedBlocks.insert(CurBB);
+        // Single predecessor case, just recurse, we can only have one
+        // definition. This inlines getPreviousDefFromEnd(Pred): if Pred has a
+        // local def we resolve it immediately (and cache it as that helper
+        // would); otherwise we recurse into getPreviousDefRecursive(Pred).
+        if (auto *Defs = MSSA->getBlockDefs(Pred)) {
+          MemoryAccess *Result = &*Defs->rbegin();
+          CachedPreviousDef.insert({Pred, Result});
+          CachedPreviousDef.insert({CurBB, Result});
+          Returned = Result;
+          WorkStack.pop_back();
+          continue;
         }
-      } else {
-        unsigned i = 0;
-        for (auto *Pred : predecessors(BB))
-          Phi->addIncoming(&*PhiOps[i++], Pred);
-        InsertedPHIs.push_back(Phi);
+        F.St = Stage::ResumeSinglePred;
+        WorkStack.push_back({Pred});
+        continue;
+      }
+
+      if (VisitedBlocks.count(CurBB)) {
+        // We hit our node again, meaning we had a cycle, we must insert a phi
+        // node to break it so we have an operand. The only case this will
+        // insert useless phis is if we have irreducible control flow.
+        MemoryAccess *Result = MSSA->createMemoryPhi(CurBB);
+        CachedPreviousDef.insert({CurBB, Result});
+        Returned = Result;
+        WorkStack.pop_back();
+        continue;
       }
-      Result = Phi;
+
+      // Mark us visited so we can detect a cycle, then walk the predecessors.
+      VisitedBlocks.insert(CurBB);
+      for (BasicBlock *Pred : predecessors(CurBB))
+        F.Preds.push_back(Pred);
+      F.St = Stage::RunPredLoop;
+      continue;
+    }
+
+    case Stage::ResumeSinglePred: {
+      // The single predecessor's getPreviousDefFromEnd result is in Returned.
+      CachedPreviousDef.insert({CurBB, Returned});
+      WorkStack.pop_back();
+      continue;
     }
 
-    // Set ourselves up for the next variable by resetting visited state.
-    VisitedBlocks.erase(BB);
-    CachedPreviousDef.insert({BB, Result});
-    return Result;
+    case Stage::RunPredLoop: {
+      // Recurse to get the values in our predecessors for placement of a
+      // potential phi node. This will insert phi nodes if we cycle in order to
+      // break the cycle and have an operand.
+      if (F.PendingIncoming) {
+        // Returned holds getPreviousDefFromEnd(Preds[PredIdx]) for the
+        // reachable predecessor we just recursed into.
+        Incorporate(F, Returned);
+        F.PendingIncoming = false;
+        ++F.PredIdx;
+      }
+
+      bool Suspended = false;
+      for (; F.PredIdx < F.Preds.size(); ++F.PredIdx) {
+        BasicBlock *Pred = F.Preds[F.PredIdx];
+        if (MSSA->DT->isReachableFromEntry(Pred)) {
+          // Inline getPreviousDefFromEnd(Pred): local def resolves now,
+          // otherwise recurse into getPreviousDefRecursive(Pred).
+          if (auto *Defs = MSSA->getBlockDefs(Pred)) {
+            MemoryAccess *IncomingAccess = &*Defs->rbegin();
+            CachedPreviousDef.insert({Pred, IncomingAccess});
+            Incorporate(F, IncomingAccess);
+          } else {
+            F.PendingIncoming = true;
+            WorkStack.push_back({Pred});
+            Suspended = true;
+            break;
+          }
+        } else
+          F.PhiOps.push_back(MSSA->getLiveOnEntryDef());
+      }
+      if (Suspended)
+        continue;
+
+      // Now try to simplify the ops to avoid placing a phi.
+      // This may return null if we never created a phi yet, that's okay
+      MemoryPhi *Phi =
+          dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(CurBB));
+
+      // See if we can avoid the phi by simplifying it.
+      auto *Result = tryRemoveTrivialPhi(Phi, F.PhiOps);
+      // If we couldn't simplify, we may have to create a phi
+      if (Result == Phi && F.UniqueIncomingAccess && F.SingleAccess) {
+        // A concrete Phi only exists if we created an empty one to break a
+        // cycle.
+        if (Phi) {
+          assert(Phi->operands().empty() && "Expected empty Phi");
+          Phi->replaceAllUsesWith(F.SingleAccess);
+          removeMemoryAccess(Phi);
+        }
+        Result = F.SingleAccess;
+      } else if (Result == Phi && !(F.UniqueIncomingAccess && F.SingleAccess)) {
+        if (!Phi)
+          Phi = MSSA->createMemoryPhi(CurBB);
+
+        // See if the existing phi operands match what we need.
+        // Unlike normal SSA, we only allow one phi node per block, so we can't
+        // just create a new one.
+        if (Phi->getNumOperands() != 0) {
+          // FIXME: Figure out whether this is dead code and if so remove it.
+          if (!std::equal(Phi->op_begin(), Phi->op_end(), F.PhiOps.begin())) {
+            // These will have been filled in by the recursive read we did
+            // above.
+            llvm::copy(F.PhiOps, Phi->op_begin());
+            std::copy(pred_begin(CurBB), pred_end(CurBB), Phi->block_begin());
----------------
antoniofrighetto wrote:

```suggestion
            llvm::copy(predecessors(CurBB), Phi->block_begin());
```

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


More information about the llvm-commits mailing list