[llvm] [MemorySSA] Make getPreviousDef iterative to avoid stack overflow (PR #205159)
Antonio Frighetto via llvm-commits
llvm-commits at lists.llvm.org
Wed Jun 24 02:19:18 PDT 2026
================
@@ -33,101 +33,222 @@ 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(
+//
+// The predecessor walk is driven by an explicit worklist rather than native
+// recursion: it used to be mutually recursive with getPreviousDefFromEnd, and
+// the recursion depth scaled with the length of the walk, so deep CFGs (e.g.
+// long block chains in large generated kernels/shaders) could overflow the
+// native stack. Each StackFrame mirrors one activation of that walk; 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, // first visit to the frame's block
+ ResumeSinglePred, // resuming after the unique predecessor is resolved
+ 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 this frame's phi operands,
+ // tracking whether all incoming accesses are identical (so the phi may be
+ // elided). Mirrors the per-predecessor body of the walk.
+ void incorporate(MemoryAccess *Incoming) {
+ if (!SingleAccess)
+ SingleAccess = Incoming;
+ else if (Incoming != SingleAccess)
+ UniqueIncomingAccess = false;
+ PhiOps.push_back(Incoming);
}
+ };
- // 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);
+ // Non-recursive part of getPreviousDefFromEnd(Pred): if Pred has a local
+ // definition, return its last def and cache it under Pred (exactly as that
+ // helper does). Returns nullptr when Pred has no local def, signalling that
+ // it must instead be visited via its own worklist frame (the part of
+ // getPreviousDefFromEnd that used to recurse).
+ auto localDefFromEnd = [&](BasicBlock *Pred) -> MemoryAccess * {
----------------
antoniofrighetto wrote:
```suggestion
auto GetLocalDefFromEnd = [&](BasicBlock *Pred) -> MemoryAccess * {
```
https://github.com/llvm/llvm-project/pull/205159
More information about the llvm-commits
mailing list