[llvm] [GlobalsAA] Port to LazyCallGraph (PR #223413)

Clemens Wasser via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 14 06:48:41 PDT 2026


https://github.com/clemenswasser created https://github.com/llvm/llvm-project/pull/223413

Port `GlobalsAA` to `LazyCallGraph` so it no longer requires `CallGraphAnalysis`, reusing the usually available `LazyCallGraphAnalysis`.

Direct calls to declarations are tracked per node and modeled from attributes. Indirect calls poison the caller, which is also what makes skipping ref edges sound: callbacks can only fire through one of those two poisoned paths. This is intentionally as close to a 1:1 port of the legacy implementation as the LCG API allows.

Compile-time impact:
geomean: -0.13%, stage2-clang: -0.16%
https://llvm-compile-time-tracker.com/compare.php?from=e6734a41bb41d91cb880fe7abce46d8146182518&to=114c1022c95848ab19887feee5c4a0b4858eea3c&stat=instructions%3Au

Assisted-by: Muse Spark 1.3



>From 095b709cbd4cf3beea3ad47c995a6e840e018adb Mon Sep 17 00:00:00 2001
From: Clemens Wasser <clemens.wasser at gmail.com>
Date: Mon, 14 Sep 2026 15:01:04 +0200
Subject: [PATCH 1/3] [GlobalsAA] Remove dead SCC membership tracking

---
 llvm/include/llvm/Analysis/GlobalsModRef.h |  6 ------
 llvm/lib/Analysis/GlobalsModRef.cpp        | 20 --------------------
 2 files changed, 26 deletions(-)

diff --git a/llvm/include/llvm/Analysis/GlobalsModRef.h b/llvm/include/llvm/Analysis/GlobalsModRef.h
index 108135e15adf4..3ad0606cfa0b2 100644
--- a/llvm/include/llvm/Analysis/GlobalsModRef.h
+++ b/llvm/include/llvm/Analysis/GlobalsModRef.h
@@ -51,11 +51,6 @@ class GlobalsAAResult : public AAResultBase {
   /// For each function, keep track of what globals are modified or read.
   DenseMap<const Function *, FunctionInfo> FunctionInfos;
 
-  /// A map of functions to SCC. The SCCs are described by a simple integer
-  /// ID that is only useful for comparing for equality (are two functions
-  /// in the same SCC or not?)
-  DenseMap<const Function *, unsigned> FunctionToSCCMap;
-
   /// Handle to clear this analysis on deletion of values.
   struct LLVM_ABI DeletionCallbackHandle final : CallbackVH {
     GlobalsAAResult *GAR;
@@ -119,7 +114,6 @@ class GlobalsAAResult : public AAResultBase {
                             SmallPtrSetImpl<Function *> *Writers = nullptr,
                             GlobalValue *OkayStoreDest = nullptr);
   bool AnalyzeIndirectGlobalMemory(GlobalVariable *GV);
-  void CollectSCCMembership(CallGraph &CG);
 
   bool isNonEscapingGlobalNoAlias(const GlobalValue *GV, const Value *V,
                                   const Instruction *CtxI);
diff --git a/llvm/lib/Analysis/GlobalsModRef.cpp b/llvm/lib/Analysis/GlobalsModRef.cpp
index 059ebed787c6b..5643e576ba480 100644
--- a/llvm/lib/Analysis/GlobalsModRef.cpp
+++ b/llvm/lib/Analysis/GlobalsModRef.cpp
@@ -472,21 +472,6 @@ bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
   return true;
 }
 
-void GlobalsAAResult::CollectSCCMembership(CallGraph &CG) {
-  // We do a bottom-up SCC traversal of the call graph.  In other words, we
-  // visit all callees before callers (leaf-first).
-  unsigned SCCID = 0;
-  for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
-    const std::vector<CallGraphNode *> &SCC = *I;
-    assert(!SCC.empty() && "SCC with no functions?");
-
-    for (auto *CGN : SCC)
-      if (Function *F = CGN->getFunction())
-        FunctionToSCCMap[F] = SCCID;
-    ++SCCID;
-  }
-}
-
 /// AnalyzeCallGraph - At this point, we know the functions where globals are
 /// immediately stored to and read from.  Propagate this information up the call
 /// graph to all callers and compute the mod/ref info for all memory for each
@@ -994,9 +979,6 @@ GlobalsAAResult::~GlobalsAAResult() = default;
     CallGraph &CG) {
   GlobalsAAResult Result(M.getDataLayout(), GetTLI);
 
-  // Discover which functions aren't recursive, to feed into AnalyzeGlobals.
-  Result.CollectSCCMembership(CG);
-
   // Find non-addr taken globals.
   Result.AnalyzeGlobals(M);
 
@@ -1027,9 +1009,7 @@ PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
     G->IndirectGlobals.clear();
     G->AllocsForIndirectGlobals.clear();
     G->FunctionInfos.clear();
-    G->FunctionToSCCMap.clear();
     G->Handles.clear();
-    G->CollectSCCMembership(CG);
     G->AnalyzeGlobals(M);
     G->AnalyzeCallGraph(CG, M);
   }

>From 7f4b6148db62e507c851e039a66d3e55185a5986 Mon Sep 17 00:00:00 2001
From: Clemens Wasser <clemens.wasser at gmail.com>
Date: Mon, 14 Sep 2026 15:03:19 +0200
Subject: [PATCH 2/3] [GlobalsAA] Extract shared helpers

---
 llvm/include/llvm/Analysis/GlobalsModRef.h |  3 +
 llvm/lib/Analysis/GlobalsModRef.cpp        | 99 ++++++++++++----------
 2 files changed, 57 insertions(+), 45 deletions(-)

diff --git a/llvm/include/llvm/Analysis/GlobalsModRef.h b/llvm/include/llvm/Analysis/GlobalsModRef.h
index 3ad0606cfa0b2..16b983df6642c 100644
--- a/llvm/include/llvm/Analysis/GlobalsModRef.h
+++ b/llvm/include/llvm/Analysis/GlobalsModRef.h
@@ -109,6 +109,9 @@ class GlobalsAAResult : public AAResultBase {
 
   void AnalyzeGlobals(Module &M);
   void AnalyzeCallGraph(CallGraph &CG, Module &M);
+  static bool maySyncOrCallIntoModule(const Function &F);
+  static bool addFunctionAttributeInfo(const Function &F, FunctionInfo &FI);
+  static void scanFunctionBodyForModRef(Function &F, FunctionInfo &FI);
   bool AnalyzeUsesOfPointer(Value *V,
                             SmallPtrSetImpl<Function *> *Readers = nullptr,
                             SmallPtrSetImpl<Function *> *Writers = nullptr,
diff --git a/llvm/lib/Analysis/GlobalsModRef.cpp b/llvm/lib/Analysis/GlobalsModRef.cpp
index 5643e576ba480..56a2fe3df12f5 100644
--- a/llvm/lib/Analysis/GlobalsModRef.cpp
+++ b/llvm/lib/Analysis/GlobalsModRef.cpp
@@ -472,6 +472,56 @@ bool GlobalsAAResult::AnalyzeIndirectGlobalMemory(GlobalVariable *GV) {
   return true;
 }
 
+// Intrinsics, like any other synchronizing function, can make effects
+// of other threads visible. Without nosync we know nothing really.
+// Similarly, if `nocallback` is missing the function, or intrinsic,
+// can call into the module arbitrarily. If both are set the function
+// has an effect but will not interact with accesses of internal
+// globals inside the module. We are conservative here for optnone
+// functions, might not be necessary.
+bool GlobalsAAResult::maySyncOrCallIntoModule(const Function &F) {
+  return !F.isDeclaration() || !F.hasNoSync() ||
+         !F.hasFnAttribute(Attribute::NoCallback);
+}
+
+bool GlobalsAAResult::addFunctionAttributeInfo(const Function &F,
+                                               FunctionInfo &FI) {
+  // Try to get mod/ref behaviour from function attributes.
+  if (F.doesNotAccessMemory()) {
+    // Can't do better than that!
+  } else if (F.onlyReadsMemory()) {
+    FI.addModRefInfo(ModRefInfo::Ref);
+    if (!F.onlyAccessesArgMemory() && maySyncOrCallIntoModule(F))
+      // This function might call back into the module and read a global -
+      // consider every global as possibly being read by this function.
+      FI.setMayReadAnyGlobal();
+  } else {
+    FI.addModRefInfo(ModRefInfo::ModRef);
+    if (!F.onlyAccessesArgMemory())
+      FI.setMayReadAnyGlobal();
+    if (maySyncOrCallIntoModule(F))
+      return false;
+  }
+  return true;
+}
+
+void GlobalsAAResult::scanFunctionBodyForModRef(Function &F, FunctionInfo &FI) {
+  for (Instruction &I : instructions(&F)) {
+    if (isModAndRefSet(FI.getModRefInfo()))
+      break; // The mod/ref lattice saturates here.
+    // We handle calls specially because the graph-relevant aspects are
+    // handled above.
+    if (isa<CallBase>(&I))
+      continue;
+    // All non-call instructions we use the primary predicates for whether
+    // they read or write memory.
+    if (I.mayReadFromMemory())
+      FI.addModRefInfo(ModRefInfo::Ref);
+    if (I.mayWriteToMemory())
+      FI.addModRefInfo(ModRefInfo::Mod);
+  }
+}
+
 /// AnalyzeCallGraph - At this point, we know the functions where globals are
 /// immediately stored to and read from.  Propagate this information up the call
 /// graph to all callers and compute the mod/ref info for all memory for each
@@ -499,18 +549,6 @@ void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
     Handles.front().I = Handles.begin();
     bool KnowNothing = false;
 
-    // Intrinsics, like any other synchronizing function, can make effects
-    // of other threads visible. Without nosync we know nothing really.
-    // Similarly, if `nocallback` is missing the function, or intrinsic,
-    // can call into the module arbitrarily. If both are set the function
-    // has an effect but will not interact with accesses of internal
-    // globals inside the module. We are conservative here for optnone
-    // functions, might not be necessary.
-    auto MaySyncOrCallIntoModule = [](const Function &F) {
-      return !F.isDeclaration() || !F.hasNoSync() ||
-             !F.hasFnAttribute(Attribute::NoCallback);
-    };
-
     // Collect the mod/ref properties due to called functions.  We only compute
     // one mod-ref set.
     for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
@@ -521,23 +559,9 @@ void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
       }
 
       if (F->isDeclaration() || F->hasOptNone()) {
-        // Try to get mod/ref behaviour from function attributes.
-        if (F->doesNotAccessMemory()) {
-          // Can't do better than that!
-        } else if (F->onlyReadsMemory()) {
-          FI.addModRefInfo(ModRefInfo::Ref);
-          if (!F->onlyAccessesArgMemory() && MaySyncOrCallIntoModule(*F))
-            // This function might call back into the module and read a global -
-            // consider every global as possibly being read by this function.
-            FI.setMayReadAnyGlobal();
-        } else {
-          FI.addModRefInfo(ModRefInfo::ModRef);
-          if (!F->onlyAccessesArgMemory())
-            FI.setMayReadAnyGlobal();
-          if (MaySyncOrCallIntoModule(*F)) {
-            KnowNothing = true;
-            break;
-          }
+        if (!addFunctionAttributeInfo(*F, FI)) {
+          KnowNothing = true;
+          break;
         }
         continue;
       }
@@ -579,22 +603,7 @@ void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
       if (Node->getFunction()->hasOptNone())
         continue;
 
-      for (Instruction &I : instructions(Node->getFunction())) {
-        if (isModAndRefSet(FI.getModRefInfo()))
-          break; // The mod/ref lattice saturates here.
-
-        // We handle calls specially because the graph-relevant aspects are
-        // handled above.
-        if (isa<CallBase>(&I))
-          continue;
-
-        // All non-call instructions we use the primary predicates for whether
-        // they read or write memory.
-        if (I.mayReadFromMemory())
-          FI.addModRefInfo(ModRefInfo::Ref);
-        if (I.mayWriteToMemory())
-          FI.addModRefInfo(ModRefInfo::Mod);
-      }
+      scanFunctionBodyForModRef(*Node->getFunction(), FI);
     }
 
     if (!isModSet(FI.getModRefInfo()))

>From 114c1022c95848ab19887feee5c4a0b4858eea3c Mon Sep 17 00:00:00 2001
From: Clemens Wasser <clemens.wasser at gmail.com>
Date: Mon, 14 Sep 2026 15:03:57 +0200
Subject: [PATCH 3/3] [GlobalsAA] Port to LazyCallGraph

---
 llvm/include/llvm/Analysis/GlobalsModRef.h    |   7 +
 llvm/include/llvm/Analysis/LazyCallGraph.h    |  25 ++-
 llvm/lib/Analysis/GlobalsModRef.cpp           | 156 +++++++++++++++++-
 llvm/lib/Analysis/LazyCallGraph.cpp           |  17 +-
 .../Analysis/GlobalsModRef/lazy-decl-calls.ll |  55 ++++++
 llvm/test/Other/new-pm-defaults.ll            |   3 +-
 llvm/test/Other/new-pm-lto-defaults.ll        |   1 -
 .../Other/new-pm-thinlto-postlink-defaults.ll |   3 +-
 .../new-pm-thinlto-postlink-pgo-defaults.ll   |   3 +-
 ...-pm-thinlto-postlink-samplepgo-defaults.ll |   1 -
 .../Other/new-pm-thinlto-prelink-defaults.ll  |   3 +-
 .../new-pm-thinlto-prelink-pgo-defaults.ll    |   5 +-
 ...w-pm-thinlto-prelink-samplepgo-defaults.ll |   1 -
 13 files changed, 257 insertions(+), 23 deletions(-)
 create mode 100644 llvm/test/Analysis/GlobalsModRef/lazy-decl-calls.ll

diff --git a/llvm/include/llvm/Analysis/GlobalsModRef.h b/llvm/include/llvm/Analysis/GlobalsModRef.h
index 16b983df6642c..d156c875fb299 100644
--- a/llvm/include/llvm/Analysis/GlobalsModRef.h
+++ b/llvm/include/llvm/Analysis/GlobalsModRef.h
@@ -23,6 +23,7 @@
 namespace llvm {
 class CallGraph;
 class Function;
+class LazyCallGraph;
 
 /// An alias analysis result set for globals.
 ///
@@ -86,6 +87,11 @@ class GlobalsAAResult : public AAResultBase {
                 std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
                 CallGraph &CG);
 
+  LLVM_ABI static GlobalsAAResult
+  analyzeModule(Module &M,
+                std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
+                LazyCallGraph &LCG);
+
   //------------------------------------------------
   // Implement the AliasAnalysis API
   //
@@ -109,6 +115,7 @@ class GlobalsAAResult : public AAResultBase {
 
   void AnalyzeGlobals(Module &M);
   void AnalyzeCallGraph(CallGraph &CG, Module &M);
+  void AnalyzeCallGraph(LazyCallGraph &LCG, Module &M);
   static bool maySyncOrCallIntoModule(const Function &F);
   static bool addFunctionAttributeInfo(const Function &F, FunctionInfo &FI);
   static void scanFunctionBodyForModRef(Function &F, FunctionInfo &FI);
diff --git a/llvm/include/llvm/Analysis/LazyCallGraph.h b/llvm/include/llvm/Analysis/LazyCallGraph.h
index ffc50388391fa..8d498c8512ab9 100644
--- a/llvm/include/llvm/Analysis/LazyCallGraph.h
+++ b/llvm/include/llvm/Analysis/LazyCallGraph.h
@@ -366,6 +366,20 @@ class LazyCallGraph {
       return populateSlow();
     }
 
+    /// Returns the deduplicated list of declaration functions directly called
+    /// by this node's function. Populated during populateSlow() at no
+    /// additional scan cost.
+    ArrayRef<Function *> getDeclarationCallees() const {
+      assert(Edges && "Node must be populated before querying decl callees!");
+      return DeclCallees;
+    }
+
+    /// Returns true if this function contains any indirect calls.
+    bool hasIndirectCalls() const {
+      assert(Edges && "Node must be populated before querying indirect calls!");
+      return HasIndirectCalls;
+    }
+
   private:
     LazyCallGraph *G;
     Function *F;
@@ -378,6 +392,9 @@ class LazyCallGraph {
 
     std::optional<EdgeSequence> Edges;
 
+    SmallVector<Function *, 2> DeclCallees;
+    bool HasIndirectCalls = false;
+
     /// Basic constructor implements the scanning of F into Edges and
     /// EdgeIndexMap.
     Node(LazyCallGraph &G, Function &F) : G(&G), F(&F) {}
@@ -392,7 +409,11 @@ class LazyCallGraph {
     /// the other.
     void replaceFunction(Function &NewF);
 
-    void clear() { Edges.reset(); }
+    void clear() {
+      Edges.reset();
+      DeclCallees.clear();
+      HasIndirectCalls = false;
+    }
 
     /// Print the name of this node's function.
     friend raw_ostream &operator<<(raw_ostream &OS, const Node &N) {
@@ -859,7 +880,7 @@ class LazyCallGraph {
     ///
     /// It requires that the old function in the provided node have zero uses
     /// and the new function must have calls and references to it establishing
-    /// an equivalent graph.
+    /// an equivalent graph, including DeclCallees/HasIndirectCalls.
     LLVM_ABI void replaceNodeFunction(Node &N, Function &NewF);
 
     ///@}
diff --git a/llvm/lib/Analysis/GlobalsModRef.cpp b/llvm/lib/Analysis/GlobalsModRef.cpp
index 56a2fe3df12f5..34d00d234893e 100644
--- a/llvm/lib/Analysis/GlobalsModRef.cpp
+++ b/llvm/lib/Analysis/GlobalsModRef.cpp
@@ -18,6 +18,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Analysis/CallGraph.h"
+#include "llvm/Analysis/LazyCallGraph.h"
 #include "llvm/Analysis/MemoryBuiltins.h"
 #include "llvm/Analysis/TargetLibraryInfo.h"
 #include "llvm/Analysis/ValueTracking.h"
@@ -621,6 +622,137 @@ void GlobalsAAResult::AnalyzeCallGraph(CallGraph &CG, Module &M) {
   }
 }
 
+void GlobalsAAResult::AnalyzeCallGraph(LazyCallGraph &LCG, Module &M) {
+  // LCG has no declaration nodes; model direct calls from attributes.
+  for (Function &F : M) {
+    if (!F.isDeclaration())
+      continue;
+
+    FunctionInfo &FI = FunctionInfos[&F];
+    if (!addFunctionAttributeInfo(F, FI)) {
+      FunctionInfos.erase(&F);
+      continue;
+    }
+
+    Handles.emplace_front(*this, &F);
+    Handles.front().I = Handles.begin();
+  }
+
+  // We do a bottom-up SCC traversal of the call graph.  In other words, we
+  // visit all callees before callers (leaf-first).
+  for (LazyCallGraph::RefSCC &RC : LCG.postorder_ref_sccs()) {
+    for (LazyCallGraph::SCC &C : RC) {
+      assert(C.size() > 0 && "SCC with no functions?");
+      Function *FirstF = &C.begin()->getFunction();
+      if (!FirstF->isDefinitionExact()) {
+        for (LazyCallGraph::Node &N : C)
+          FunctionInfos.erase(&N.getFunction());
+        continue;
+      }
+
+      FunctionInfo &FI = FunctionInfos[FirstF];
+      Handles.emplace_front(*this, FirstF);
+      Handles.front().I = Handles.begin();
+      bool KnowNothing = false;
+
+      // Collect the mod/ref properties due to called functions.  We only
+      // compute one mod-ref set.
+      for (LazyCallGraph::Node &N : C) {
+        if (KnowNothing)
+          break;
+        Function &NF = N.getFunction();
+        if (NF.hasOptNone()) {
+          if (!addFunctionAttributeInfo(NF, FI)) {
+            KnowNothing = true;
+            break;
+          }
+          continue;
+        }
+
+        // Only call edges need propagation; ref edges (incl. callbacks) can
+        // fire solely via indirect calls or non-nocallback decls, both poisoned
+        // below.
+        for (LazyCallGraph::Edge &E : N->calls()) {
+          if (KnowNothing)
+            break;
+          Function &Callee = E.getFunction();
+          if (FunctionInfo *CalleeFI = getFunctionInfo(&Callee)) {
+            // Propagate function effect up.
+            FI.addFunctionInfo(*CalleeFI);
+          } else {
+            // Can't say anything about it.  However, if it is inside our
+            // SCC, then nothing needs to be done.
+            LazyCallGraph::Node *CalleeN = LCG.lookup(Callee);
+            assert(CalleeN && "Call edge target must have a node");
+            if (LCG.lookupSCC(*CalleeN) != &C)
+              KnowNothing = true;
+          }
+        }
+
+        // Decls/indirect have no LCG edges; reuse the decl attribute logic.
+        if (!KnowNothing) {
+          if (N.hasIndirectCalls()) {
+            KnowNothing = true;
+            break;
+          }
+
+          for (Function *DeclCallee : N.getDeclarationCallees()) {
+            if (FunctionInfo *CalleeFI = getFunctionInfo(DeclCallee)) {
+              FI.addFunctionInfo(*CalleeFI);
+            } else {
+              // Unknown declaration; be conservative.
+              KnowNothing = true;
+              break;
+            }
+          }
+        }
+      }
+
+      // If we can't say anything useful about this SCC, remove all SCC
+      // functions from the FunctionInfos map.
+      if (KnowNothing) {
+        for (LazyCallGraph::Node &N : C)
+          FunctionInfos.erase(&N.getFunction());
+        continue;
+      }
+
+      // Scan the function bodies for explicit loads or stores.
+      for (LazyCallGraph::Node &N : C) {
+        if (isModAndRefSet(FI.getModRefInfo()))
+          break; // The mod/ref lattice saturates here.
+
+        // Don't prove any properties based on the implementation of an optnone
+        // function. Function attributes were already used as a best
+        // approximation above.
+        Function &NF = N.getFunction();
+        if (NF.hasOptNone())
+          continue;
+
+        scanFunctionBodyForModRef(NF, FI);
+      }
+
+      if (!isModSet(FI.getModRefInfo()))
+        ++NumReadMemFunctions;
+      if (!isModOrRefSet(FI.getModRefInfo()))
+        ++NumNoMemFunctions;
+
+      // Finally, now that we know the full effect on this SCC, clone the
+      // information to each function in the SCC.
+      // FI is a reference into FunctionInfos, so copy it now so that it doesn't
+      // get invalidated if DenseMap decides to re-hash.
+      FunctionInfo CachedFI = FI;
+      bool First = true;
+      for (LazyCallGraph::Node &N : C) {
+        if (First) {
+          First = false;
+          continue; // Skip the first function (already has FI).
+        }
+        FunctionInfos[&N.getFunction()] = CachedFI;
+      }
+    }
+  }
+}
+
 // GV is a non-escaping global. V is a pointer address that has been loaded from.
 // If we can prove that V must escape, we can conclude that a load from V cannot
 // alias GV.
@@ -997,6 +1129,20 @@ GlobalsAAResult::~GlobalsAAResult() = default;
   return Result;
 }
 
+/*static*/ GlobalsAAResult GlobalsAAResult::analyzeModule(
+    Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI,
+    LazyCallGraph &LCG) {
+  GlobalsAAResult Result(M.getDataLayout(), GetTLI);
+
+  // Find non-addr taken globals.
+  Result.AnalyzeGlobals(M);
+
+  // Propagate on LCG.
+  Result.AnalyzeCallGraph(LCG, M);
+
+  return Result;
+}
+
 AnalysisKey GlobalsAA::Key;
 
 GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
@@ -1005,14 +1151,16 @@ GlobalsAAResult GlobalsAA::run(Module &M, ModuleAnalysisManager &AM) {
   auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
     return FAM.getResult<TargetLibraryAnalysis>(F);
   };
-  return GlobalsAAResult::analyzeModule(M, GetTLI,
-                                        AM.getResult<CallGraphAnalysis>(M));
+  auto &LCG = AM.getResult<LazyCallGraphAnalysis>(M);
+  LCG.buildRefSCCs();
+  return GlobalsAAResult::analyzeModule(M, GetTLI, LCG);
 }
 
 PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
                                               ModuleAnalysisManager &AM) {
   if (auto *G = AM.getCachedResult<GlobalsAA>(M)) {
-    auto &CG = AM.getResult<CallGraphAnalysis>(M);
+    auto &LCG = AM.getResult<LazyCallGraphAnalysis>(M);
+    LCG.buildRefSCCs();
     G->NonAddressTakenGlobals.clear();
     G->UnknownFunctionsWithLocalLinkage = false;
     G->IndirectGlobals.clear();
@@ -1020,7 +1168,7 @@ PreservedAnalyses RecomputeGlobalsAAPass::run(Module &M,
     G->FunctionInfos.clear();
     G->Handles.clear();
     G->AnalyzeGlobals(M);
-    G->AnalyzeCallGraph(CG, M);
+    G->AnalyzeCallGraph(LCG, M);
   }
   return PreservedAnalyses::all();
 }
diff --git a/llvm/lib/Analysis/LazyCallGraph.cpp b/llvm/lib/Analysis/LazyCallGraph.cpp
index 0410e2fc5dd70..ab2af3de1fd62 100644
--- a/llvm/lib/Analysis/LazyCallGraph.cpp
+++ b/llvm/lib/Analysis/LazyCallGraph.cpp
@@ -77,6 +77,7 @@ LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
 
   SmallVector<Constant *, 16> Worklist;
   SmallPtrSet<Function *, 4> Callees;
+  SmallPtrSet<Function *, 4> SeenDeclCallees;
   SmallPtrSet<Constant *, 16> Visited;
 
   // Find all the potential call graph edges in this function. We track both
@@ -97,14 +98,24 @@ LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
   // safety of optimizing a direct call edge.
   for (BasicBlock &BB : *F)
     for (Instruction &I : BB) {
-      if (auto *CB = dyn_cast<CallBase>(&I))
-        if (Function *Callee = CB->getCalledFunction())
-          if (!Callee->isDeclaration())
+      if (auto *CB = dyn_cast<CallBase>(&I)) {
+        if (Function *Callee = CB->getCalledFunction()) {
+          if (!Callee->isDeclaration()) {
             if (Callees.insert(Callee).second) {
               Visited.insert(Callee);
               addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
                       LazyCallGraph::Edge::Call);
             }
+          } else {
+            if (SeenDeclCallees.insert(Callee).second) {
+              DeclCallees.push_back(Callee);
+              Visited.insert(Callee);
+            }
+          }
+        } else {
+          HasIndirectCalls = true;
+        }
+      }
 
       for (Value *Op : I.operand_values())
         if (Constant *C = dyn_cast<Constant>(Op))
diff --git a/llvm/test/Analysis/GlobalsModRef/lazy-decl-calls.ll b/llvm/test/Analysis/GlobalsModRef/lazy-decl-calls.ll
new file mode 100644
index 0000000000000..fc2e2b3a76d8f
--- /dev/null
+++ b/llvm/test/Analysis/GlobalsModRef/lazy-decl-calls.ll
@@ -0,0 +1,55 @@
+; RUN: opt < %s -aa-pipeline=globals-aa -passes='require<globals-aa>,dse' -S | FileCheck %s
+;
+; Direct calls to declarations use attribute modeling; readnone must not
+; block DSE, unknown decls and indirect calls stay conservative. Double call
+; covers DeclCallees dedup.
+
+ at X = internal global i32 0
+
+define void @test_readnone() {
+; CHECK-LABEL: @test_readnone
+; CHECK-NOT: store i32 1, ptr @X
+; CHECK: call void @decl_readnone()
+; CHECK-NEXT: store i32 2, ptr @X
+  store i32 1, ptr @X
+  call void @decl_readnone()
+  store i32 2, ptr @X
+  ret void
+}
+
+define void @test_readnone_twice() {
+; CHECK-LABEL: @test_readnone_twice
+; CHECK: call void @decl_readnone()
+; CHECK-NEXT: call void @decl_readnone()
+; CHECK-NEXT: store i32 4, ptr @X
+  store i32 3, ptr @X
+  call void @decl_readnone()
+  call void @decl_readnone()
+  store i32 4, ptr @X
+  ret void
+}
+
+define void @test_unknown() {
+; CHECK-LABEL: @test_unknown
+; CHECK: store i32 5, ptr @X
+; CHECK-NEXT: call void @decl_unknown()
+; CHECK-NEXT: store i32 6, ptr @X
+  store i32 5, ptr @X
+  call void @decl_unknown()
+  store i32 6, ptr @X
+  ret void
+}
+
+define void @test_indirect(ptr %fp) {
+; CHECK-LABEL: @test_indirect
+; CHECK: store i32 7, ptr @X
+; CHECK-NEXT: call void %fp()
+; CHECK-NEXT: store i32 8, ptr @X
+  store i32 7, ptr @X
+  call void %fp()
+  store i32 8, ptr @X
+  ret void
+}
+
+declare void @decl_readnone() readnone nounwind
+declare void @decl_unknown()
diff --git a/llvm/test/Other/new-pm-defaults.ll b/llvm/test/Other/new-pm-defaults.ll
index 2c1a57e00c9f1..0a113d3bba61f 100644
--- a/llvm/test/Other/new-pm-defaults.ll
+++ b/llvm/test/Other/new-pm-defaults.ll
@@ -120,12 +120,11 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
 ; CHECK-O-NEXT: Running analysis: InnerAnalysisManagerProxy
-; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running analysis: FunctionAnalysisManagerCGSCCProxy
 ; CHECK-O-NEXT: Running analysis: OuterAnalysisManagerProxy<{{.*}}LazyCallGraph::SCC{{.*}}>
 ; CHECK-O-NEXT: Running pass: DevirtSCCRepeatedPass
diff --git a/llvm/test/Other/new-pm-lto-defaults.ll b/llvm/test/Other/new-pm-lto-defaults.ll
index 14f189194d0e3..f2907ee2e1f42 100644
--- a/llvm/test/Other/new-pm-lto-defaults.ll
+++ b/llvm/test/Other/new-pm-lto-defaults.ll
@@ -100,7 +100,6 @@
 ; CHECK-O23-NEXT: Running pass: PostOrderFunctionAttrsPass on (foo)
 ; CHECK-O23-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O23-NEXT: Running analysis: GlobalsAA on [module]
-; CHECK-O23-NEXT: Running analysis: CallGraphAnalysis on [module]
 ; CHECK-O23-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O23-NEXT: Invalidating analysis: AAManager on foo
 ; CHECK-O23-NEXT: Running pass: OpenMPOptCGSCCPass on (foo)
diff --git a/llvm/test/Other/new-pm-thinlto-postlink-defaults.ll b/llvm/test/Other/new-pm-thinlto-postlink-defaults.ll
index b1fde57902b05..d6a4e079845bc 100644
--- a/llvm/test/Other/new-pm-thinlto-postlink-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-postlink-defaults.ll
@@ -62,12 +62,11 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
 ; CHECK-O-NEXT: Running analysis: InnerAnalysisManagerProxy
-; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running analysis: FunctionAnalysisManagerCGSCCProxy
 ; CHECK-O-NEXT: Running analysis: OuterAnalysisManagerProxy
 ; CHECK-O-NEXT: Running pass: DevirtSCCRepeatedPass
diff --git a/llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
index 441344250e2ff..47cb93ca564f8 100644
--- a/llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-postlink-pgo-defaults.ll
@@ -50,12 +50,11 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
 ; CHECK-O-NEXT: Running analysis: InnerAnalysisManagerProxy
-; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running analysis: FunctionAnalysisManagerCGSCCProxy
 ; CHECK-O-NEXT: Running analysis: OuterAnalysisManagerProxy<{{.*}}LazyCallGraph::SCC{{.*}}>
 ; CHECK-O-NEXT: Running pass: DevirtSCCRepeatedPass
diff --git a/llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
index 477e36e8d9aba..0183d38dd22cd 100644
--- a/llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-postlink-samplepgo-defaults.ll
@@ -58,7 +58,6 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
index b07825faaa873..766fda1c2d29d 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
@@ -88,12 +88,11 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
 ; CHECK-O-NEXT: Running analysis: InnerAnalysisManagerProxy
-; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
 ; CHECK-O-NEXT: Running analysis: FunctionAnalysisManagerCGSCCProxy
 ; CHECK-O-NEXT: Running analysis: OuterAnalysisManagerProxy
 ; CHECK-O-NEXT: Running pass: DevirtSCCRepeatedPass
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
index eafd8aad98e7a..03c8839c3da74 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
@@ -84,12 +84,11 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
+; CHECK-O-NEXT: Running analysis: TargetLibraryAnalysis on foo
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis
 ; CHECK-O-NEXT: Running analysis: InnerAnalysisManagerProxy
-; CHECK-O-NEXT: Running analysis: LazyCallGraphAnalysis
-; CHECK-O-NEXT: Running analysis: TargetLibraryAnalysis on foo
 ; CHECK-O-NEXT: Running analysis: FunctionAnalysisManagerCGSCCProxy
 ; CHECK-O-NEXT: Running analysis: OuterAnalysisManagerProxy<{{.*}}LazyCallGraph::SCC{{.*}}>
 ; CHECK-O-NEXT: Running pass: DevirtSCCRepeatedPass
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
index 8d42a45475c27..0bcc9a86df022 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
@@ -63,7 +63,6 @@
 ; CHECK-O-NEXT: Running analysis: InlineAdvisorAnalysis
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}GlobalsAA
 ; CHECK-O-NEXT: Running analysis: GlobalsAA
-; CHECK-O-NEXT: Running analysis: CallGraphAnalysis
 ; CHECK-O-NEXT: Running pass: InvalidateAnalysisPass<{{.*}}AAManager
 ; CHECK-O-NEXT: Invalidating analysis: AAManager
 ; CHECK-O-NEXT: Running pass: RequireAnalysisPass<{{.*}}ProfileSummaryAnalysis



More information about the llvm-commits mailing list