[llvm] [Analysis] No block map in MemoryDependenceAnalysis (PR #190367)

Alexis Engelke via llvm-commits llvm-commits at lists.llvm.org
Fri Apr 3 10:26:49 PDT 2026


https://github.com/aengelke created https://github.com/llvm/llvm-project/pull/190367

Avoid expensive hash map of block to value by using a vector. To avoid
allocating and clearing the entire vector per query, cache the
allocation and use an epoch to identify stale values from previous
queries.


>From 24163c22704caba34fd963ee0751091e3174abd6 Mon Sep 17 00:00:00 2001
From: Alexis Engelke <engelke at in.tum.de>
Date: Fri, 3 Apr 2026 17:26:10 +0000
Subject: [PATCH] [spr] initial version

Created using spr 1.3.8-wip
---
 .../llvm/Analysis/MemoryDependenceAnalysis.h  |   9 +-
 .../lib/Analysis/MemoryDependenceAnalysis.cpp | 110 ++++++++++--------
 2 files changed, 69 insertions(+), 50 deletions(-)

diff --git a/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h b/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h
index d6288f2aa061e..d4c8a784304c4 100644
--- a/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h
+++ b/llvm/include/llvm/Analysis/MemoryDependenceAnalysis.h
@@ -349,6 +349,12 @@ class MemoryDependenceResults {
   // A reverse mapping from dependencies to the non-local dependees.
   ReverseDepMapType ReverseNonLocalDeps;
 
+  /// Visited map for getNonLocalPointerDependency. Stored here to reuse the
+  /// allocation. Map from block number to Value; second value is epoch to
+  /// avoid clearing the vector for each query.
+  SmallVector<std::pair<Value *, unsigned>, 0> NonLocalPointerDepVisited;
+  unsigned NonLocalPointerDepEpoch = 0;
+
   /// Current AA implementation, just a cache.
   AAResults &AA;
   AssumptionCache &AC;
@@ -487,12 +493,13 @@ class MemoryDependenceResults {
   MemDepResult getCallDependencyFrom(CallBase *Call, bool isReadOnlyCall,
                                      BasicBlock::iterator ScanIt,
                                      BasicBlock *BB);
+  void setNonLocalPointerDepVisited(BasicBlock *BB, Value *V);
+  Value *lookupNonLocalPointerDepVisited(BasicBlock *BB) const;
   bool getNonLocalPointerDepFromBB(Instruction *QueryInst,
                                    const PHITransAddr &Pointer,
                                    const MemoryLocation &Loc, bool isLoad,
                                    BasicBlock *BB,
                                    SmallVectorImpl<NonLocalDepResult> &Result,
-                                   SmallDenseMap<BasicBlock *, Value *, 16> &Visited,
                                    bool SkipFirstBlock = false,
                                    bool IsIncomplete = false);
   MemDepResult getNonLocalInfoForBlock(Instruction *QueryInst,
diff --git a/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp b/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
index 9a022d9ed09ce..4431ed2357571 100644
--- a/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
+++ b/llvm/lib/Analysis/MemoryDependenceAnalysis.cpp
@@ -880,13 +880,16 @@ void MemoryDependenceResults::getNonLocalPointerDependency(
   const DataLayout &DL = FromBB->getDataLayout();
   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
 
-  // This is the set of blocks we've inspected, and the pointer we consider in
-  // each block.  Because of critical edges, we currently bail out if querying
-  // a block with multiple different pointers.  This can happen during PHI
-  // translation.
-  SmallDenseMap<BasicBlock *, Value *, 16> Visited;
+  // NonLocalPointerDepVisited is the set of blocks we've inspected, and the
+  // pointer we consider in each block.  Because of critical edges, we currently
+  // bail out if querying a block with multiple different pointers.  This can
+  // happen during PHI translation.
+  ++NonLocalPointerDepEpoch;
+  assert(NonLocalPointerDepEpoch > 0 &&
+         "NonLocalPointerDepVisitedEpoch overflow");
+  NonLocalPointerDepVisited.resize(FromBB->getParent()->getMaxBlockNumber());
   if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
-                                   Result, Visited, true))
+                                  Result, true))
     return;
   Result.clear();
   Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
@@ -1021,11 +1024,22 @@ SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
   }
 }
 
+void MemoryDependenceResults::setNonLocalPointerDepVisited(BasicBlock *BB,
+                                                           Value *V) {
+  NonLocalPointerDepVisited[BB->getNumber()] = {V, NonLocalPointerDepEpoch};
+}
+
+Value *
+MemoryDependenceResults::lookupNonLocalPointerDepVisited(BasicBlock *BB) const {
+  auto &Entry = NonLocalPointerDepVisited[BB->getNumber()];
+  return Entry.second == NonLocalPointerDepEpoch ? Entry.first : nullptr;
+}
+
 /// Perform a dependency query based on pointer/pointeesize starting at the end
 /// of StartBB.
 ///
 /// Add any clobber/def results to the results vector and keep track of which
-/// blocks are visited in 'Visited'.
+/// blocks are visited in 'NonLocalPointerDepVisited'.
 ///
 /// This has special behavior for the first block queries (when SkipFirstBlock
 /// is true).  In this special case, it ignores the contents of the specified
@@ -1037,8 +1051,7 @@ SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
 bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
     Instruction *QueryInst, const PHITransAddr &Pointer,
     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
-    SmallVectorImpl<NonLocalDepResult> &Result,
-    SmallDenseMap<BasicBlock *, Value *, 16> &Visited, bool SkipFirstBlock,
+    SmallVectorImpl<NonLocalDepResult> &Result, bool SkipFirstBlock,
     bool IsIncomplete) {
   // Look up the cached info for Pointer.
   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
@@ -1099,7 +1112,7 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
       if (Loc.AATags)
         return getNonLocalPointerDepFromBB(
             QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
-            Visited, SkipFirstBlock, IsIncomplete);
+            SkipFirstBlock, IsIncomplete);
     }
   }
 
@@ -1116,23 +1129,20 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
     // that we don't already have conflicting results for these blocks.  Check
     // to ensure that if a block in the results set is in the visited set that
     // it was for the same pointer query.
-    if (!Visited.empty()) {
-      for (auto &Entry : *Cache) {
-        DenseMap<BasicBlock *, Value *>::iterator VI =
-            Visited.find(Entry.getBB());
-        if (VI == Visited.end() || VI->second == Pointer.getAddr())
-          continue;
+    for (auto &Entry : *Cache) {
+      Value *Prev = lookupNonLocalPointerDepVisited(Entry.getBB());
+      if (!Prev || Prev == Pointer.getAddr())
+        continue;
 
-        // We have a pointer mismatch in a block.  Just return false, saying
-        // that something was clobbered in this result.  We could also do a
-        // non-fully cached query, but there is little point in doing this.
-        return false;
-      }
+      // We have a pointer mismatch in a block.  Just return false, saying
+      // that something was clobbered in this result.  We could also do a
+      // non-fully cached query, but there is little point in doing this.
+      return false;
     }
 
     Value *Addr = Pointer.getAddr();
     for (auto &Entry : *Cache) {
-      Visited.insert(std::make_pair(Entry.getBB(), Addr));
+      setNonLocalPointerDepVisited(Entry.getBB(), Addr);
       if (Entry.getResult().isNonLocal()) {
         continue;
       }
@@ -1205,7 +1215,8 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
     if (!SkipFirstBlock) {
       // Analyze the dependency of *Pointer in FromBB.  See if we already have
       // been here.
-      assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
+      assert(lookupNonLocalPointerDepVisited(BB) &&
+             "Should check 'visited' before adding to WL");
 
       // Get the dependency info for Pointer in BB.  If we have cached
       // information, we will use it, otherwise we compute it.
@@ -1231,9 +1242,9 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
       SmallVector<BasicBlock *, 16> NewBlocks;
       for (BasicBlock *Pred : PredCache.get(BB)) {
         // Verify that we haven't looked at this block yet.
-        std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
-            Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
-        if (InsertRes.second) {
+        Value *Prev = lookupNonLocalPointerDepVisited(Pred);
+        if (!Prev) {
+          setNonLocalPointerDepVisited(Pred, Pointer.getAddr());
           // First time we've looked at *PI.
           NewBlocks.push_back(Pred);
           continue;
@@ -1242,11 +1253,11 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
         // If we have seen this block before, but it was with a different
         // pointer then we have a phi translation failure and we have to treat
         // this as a clobber.
-        if (InsertRes.first->second != Pointer.getAddr()) {
+        if (Prev != Pointer.getAddr()) {
           // Make sure to clean up the Visited map before continuing on to
           // PredTranslationFailure.
           for (auto *NewBlock : NewBlocks)
-            Visited.erase(NewBlock);
+            setNonLocalPointerDepVisited(NewBlock, nullptr);
           goto PredTranslationFailure;
         }
       }
@@ -1254,7 +1265,7 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
         // Make sure to clean up the Visited map before continuing on to
         // PredTranslationFailure.
         for (auto *NewBlock : NewBlocks)
-          Visited.erase(NewBlock);
+          setNonLocalPointerDepVisited(NewBlock, nullptr);
         GotWorklistLimit = true;
         goto PredTranslationFailure;
       }
@@ -1294,29 +1305,30 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
       // with PHI translation when a critical edge exists and the PHI node in
       // the successor translates to a pointer value different than the
       // pointer the block was first analyzed with.
-      std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
-          Visited.insert(std::make_pair(Pred, PredPtrVal));
+      Value *PrevVal = lookupNonLocalPointerDepVisited(Pred);
+      if (!PrevVal) {
+        setNonLocalPointerDepVisited(Pred, PredPtrVal);
+        continue;
+      }
 
-      if (!InsertRes.second) {
-        // We found the pred; take it off the list of preds to visit.
-        PredList.pop_back();
+      // We found the pred; take it off the list of preds to visit.
+      PredList.pop_back();
 
-        // If the predecessor was visited with PredPtr, then we already did
-        // the analysis and can ignore it.
-        if (InsertRes.first->second == PredPtrVal)
-          continue;
+      // If the predecessor was visited with PredPtr, then we already did
+      // the analysis and can ignore it.
+      if (PrevVal == PredPtrVal)
+        continue;
 
-        // Otherwise, the block was previously analyzed with a different
-        // pointer.  We can't represent the result of this case, so we just
-        // treat this as a phi translation failure.
+      // Otherwise, the block was previously analyzed with a different
+      // pointer.  We can't represent the result of this case, so we just
+      // treat this as a phi translation failure.
 
-        // Make sure to clean up the Visited map before continuing on to
-        // PredTranslationFailure.
-        for (const auto &Pred : PredList)
-          Visited.erase(Pred.first);
+      // Make sure to clean up the Visited map before continuing on to
+      // PredTranslationFailure.
+      for (const auto &Pred : PredList)
+        setNonLocalPointerDepVisited(Pred.first, nullptr);
 
-        goto PredTranslationFailure;
-      }
+      goto PredTranslationFailure;
     }
 
     // Actually process results here; this need to be a separate loop to avoid
@@ -1347,8 +1359,8 @@ bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
       // assume it is unknown, but this also does not block PRE of the load.
       if (!CanTranslate ||
           !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
-                                      Loc.getWithNewPtr(PredPtrVal), isLoad,
-                                      Pred, Result, Visited)) {
+                                       Loc.getWithNewPtr(PredPtrVal), isLoad,
+                                       Pred, Result)) {
         // Add the entry to the Result list.
         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
         Result.push_back(Entry);



More information about the llvm-commits mailing list