1bf71a34eSChandler Carruth //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2bf71a34eSChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bf71a34eSChandler Carruth //
7bf71a34eSChandler Carruth //===----------------------------------------------------------------------===//
8bf71a34eSChandler Carruth 
9bf71a34eSChandler Carruth #include "llvm/Analysis/LazyCallGraph.h"
10530851c2SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
1118eadd92SChandler Carruth #include "llvm/ADT/STLExtras.h"
126bda14b3SChandler Carruth #include "llvm/ADT/Sequence.h"
13530851c2SEugene Zelenko #include "llvm/ADT/SmallPtrSet.h"
14530851c2SEugene Zelenko #include "llvm/ADT/SmallVector.h"
15530851c2SEugene Zelenko #include "llvm/ADT/iterator_range.h"
16530851c2SEugene Zelenko #include "llvm/Analysis/TargetLibraryInfo.h"
17432a3883SNico Weber #include "llvm/Config/llvm-config.h"
1871c3a551Sserge-sans-paille #include "llvm/IR/Constants.h"
19530851c2SEugene Zelenko #include "llvm/IR/Function.h"
20530851c2SEugene Zelenko #include "llvm/IR/GlobalVariable.h"
217fea561eSArthur Eubanks #include "llvm/IR/InstIterator.h"
22530851c2SEugene Zelenko #include "llvm/IR/Instruction.h"
23530851c2SEugene Zelenko #include "llvm/IR/Module.h"
24bf71a34eSChandler Carruth #include "llvm/IR/PassManager.h"
25530851c2SEugene Zelenko #include "llvm/Support/Casting.h"
26530851c2SEugene Zelenko #include "llvm/Support/Compiler.h"
2799b756dbSChandler Carruth #include "llvm/Support/Debug.h"
287cb30664SSean Silva #include "llvm/Support/GraphWriter.h"
29530851c2SEugene Zelenko #include "llvm/Support/raw_ostream.h"
30530851c2SEugene Zelenko #include <algorithm>
31530851c2SEugene Zelenko #include <cassert>
32530851c2SEugene Zelenko #include <iterator>
33530851c2SEugene Zelenko #include <string>
34530851c2SEugene Zelenko #include <tuple>
352e0fe3e6SChandler Carruth #include <utility>
36bf71a34eSChandler Carruth 
37*3d219d80Sserge-sans-paille #ifdef EXPENSIVE_CHECKS
38*3d219d80Sserge-sans-paille #include "llvm/ADT/ScopeExit.h"
39*3d219d80Sserge-sans-paille #endif
40*3d219d80Sserge-sans-paille 
41bf71a34eSChandler Carruth using namespace llvm;
42bf71a34eSChandler Carruth 
43f1221bd0SChandler Carruth #define DEBUG_TYPE "lcg"
44f1221bd0SChandler Carruth 
insertEdgeInternal(Node & TargetN,Edge::Kind EK)45aaad9f84SChandler Carruth void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
46aaad9f84SChandler Carruth                                                      Edge::Kind EK) {
47aaad9f84SChandler Carruth   EdgeIndexMap.insert({&TargetN, Edges.size()});
48aaad9f84SChandler Carruth   Edges.emplace_back(TargetN, EK);
4999b756dbSChandler Carruth }
50a4499e9fSChandler Carruth 
setEdgeKind(Node & TargetN,Edge::Kind EK)51aaad9f84SChandler Carruth void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
52aaad9f84SChandler Carruth   Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
53aaad9f84SChandler Carruth }
54aaad9f84SChandler Carruth 
removeEdgeInternal(Node & TargetN)55aaad9f84SChandler Carruth bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
56aaad9f84SChandler Carruth   auto IndexMapI = EdgeIndexMap.find(&TargetN);
57aaad9f84SChandler Carruth   if (IndexMapI == EdgeIndexMap.end())
58aaad9f84SChandler Carruth     return false;
59aaad9f84SChandler Carruth 
60aaad9f84SChandler Carruth   Edges[IndexMapI->second] = Edge();
61aaad9f84SChandler Carruth   EdgeIndexMap.erase(IndexMapI);
62aaad9f84SChandler Carruth   return true;
63aaad9f84SChandler Carruth }
64aaad9f84SChandler Carruth 
addEdge(SmallVectorImpl<LazyCallGraph::Edge> & Edges,DenseMap<LazyCallGraph::Node *,int> & EdgeIndexMap,LazyCallGraph::Node & N,LazyCallGraph::Edge::Kind EK)65aaad9f84SChandler Carruth static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
66aaad9f84SChandler Carruth                     DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
67aaad9f84SChandler Carruth                     LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
68aaad9f84SChandler Carruth   if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
69aaad9f84SChandler Carruth     return;
70aaad9f84SChandler Carruth 
71d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "    Added callable function: " << N.getName() << "\n");
72aaad9f84SChandler Carruth   Edges.emplace_back(LazyCallGraph::Edge(N, EK));
73aaad9f84SChandler Carruth }
74aaad9f84SChandler Carruth 
populateSlow()75aaad9f84SChandler Carruth LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
76aaad9f84SChandler Carruth   assert(!Edges && "Must not have already populated the edges for this node!");
77aaad9f84SChandler Carruth 
78d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Adding functions called by '" << getName()
7999b756dbSChandler Carruth                     << "' to the graph.\n");
8099b756dbSChandler Carruth 
81aaad9f84SChandler Carruth   Edges = EdgeSequence();
82aaad9f84SChandler Carruth 
83bf71a34eSChandler Carruth   SmallVector<Constant *, 16> Worklist;
84a4499e9fSChandler Carruth   SmallPtrSet<Function *, 4> Callees;
85bf71a34eSChandler Carruth   SmallPtrSet<Constant *, 16> Visited;
86a4499e9fSChandler Carruth 
87a4499e9fSChandler Carruth   // Find all the potential call graph edges in this function. We track both
88a4499e9fSChandler Carruth   // actual call edges and indirect references to functions. The direct calls
89a4499e9fSChandler Carruth   // are trivially added, but to accumulate the latter we walk the instructions
90a4499e9fSChandler Carruth   // and add every operand which is a constant to the worklist to process
91a4499e9fSChandler Carruth   // afterward.
9286f0bdf8SChandler Carruth   //
9386f0bdf8SChandler Carruth   // Note that we consider *any* function with a definition to be a viable
9486f0bdf8SChandler Carruth   // edge. Even if the function's definition is subject to replacement by
9586f0bdf8SChandler Carruth   // some other module (say, a weak definition) there may still be
9686f0bdf8SChandler Carruth   // optimizations which essentially speculate based on the definition and
9786f0bdf8SChandler Carruth   // a way to check that the specific definition is in fact the one being
9886f0bdf8SChandler Carruth   // used. For example, this could be done by moving the weak definition to
9986f0bdf8SChandler Carruth   // a strong (internal) definition and making the weak definition be an
10086f0bdf8SChandler Carruth   // alias. Then a test of the address of the weak function against the new
10186f0bdf8SChandler Carruth   // strong definition's address would be an effective way to determine the
10286f0bdf8SChandler Carruth   // safety of optimizing a direct call edge.
103aaad9f84SChandler Carruth   for (BasicBlock &BB : *F)
104a4499e9fSChandler Carruth     for (Instruction &I : BB) {
105447e2c30SMircea Trofin       if (auto *CB = dyn_cast<CallBase>(&I))
106447e2c30SMircea Trofin         if (Function *Callee = CB->getCalledFunction())
10786f0bdf8SChandler Carruth           if (!Callee->isDeclaration())
108a4499e9fSChandler Carruth             if (Callees.insert(Callee).second) {
109a4499e9fSChandler Carruth               Visited.insert(Callee);
110aaad9f84SChandler Carruth               addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
11131a47f98SBenjamin Kramer                       LazyCallGraph::Edge::Call);
112a4499e9fSChandler Carruth             }
113a4499e9fSChandler Carruth 
114b9e2f8c4SChandler Carruth       for (Value *Op : I.operand_values())
1151583e99cSChandler Carruth         if (Constant *C = dyn_cast<Constant>(Op))
11670573dcdSDavid Blaikie           if (Visited.insert(C).second)
117bf71a34eSChandler Carruth             Worklist.push_back(C);
118a4499e9fSChandler Carruth     }
119bf71a34eSChandler Carruth 
120bf71a34eSChandler Carruth   // We've collected all the constant (and thus potentially function or
121bf71a34eSChandler Carruth   // function containing) operands to all of the instructions in the function.
122bf71a34eSChandler Carruth   // Process them (recursively) collecting every function found.
12388823468SChandler Carruth   visitReferences(Worklist, Visited, [&](Function &F) {
124aaad9f84SChandler Carruth     addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
125aaad9f84SChandler Carruth             LazyCallGraph::Edge::Ref);
12688823468SChandler Carruth   });
127aaad9f84SChandler Carruth 
128f59a8387SChandler Carruth   // Add implicit reference edges to any defined libcall functions (if we
129f59a8387SChandler Carruth   // haven't found an explicit edge).
130f59a8387SChandler Carruth   for (auto *F : G->LibFunctions)
131f59a8387SChandler Carruth     if (!Visited.count(F))
132f59a8387SChandler Carruth       addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
133f59a8387SChandler Carruth               LazyCallGraph::Edge::Ref);
134f59a8387SChandler Carruth 
135aaad9f84SChandler Carruth   return *Edges;
136bf71a34eSChandler Carruth }
137bf71a34eSChandler Carruth 
replaceFunction(Function & NewF)138aaad9f84SChandler Carruth void LazyCallGraph::Node::replaceFunction(Function &NewF) {
139aaad9f84SChandler Carruth   assert(F != &NewF && "Must not replace a function with itself!");
140aaad9f84SChandler Carruth   F = &NewF;
141aa839b22SChandler Carruth }
142aa839b22SChandler Carruth 
143615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const1448c209aa8SMatthias Braun LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
145dca83408SChandler Carruth   dbgs() << *this << '\n';
146dca83408SChandler Carruth }
1478c209aa8SMatthias Braun #endif
148dca83408SChandler Carruth 
isKnownLibFunction(Function & F,TargetLibraryInfo & TLI)149f59a8387SChandler Carruth static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
150f59a8387SChandler Carruth   LibFunc LF;
151f59a8387SChandler Carruth 
15266c120f0SFrancesco Petrogalli   // Either this is a normal library function or a "vectorizable"
15366c120f0SFrancesco Petrogalli   // function.  Not using the VFDatabase here because this query
15466c120f0SFrancesco Petrogalli   // is related only to libraries handled via the TLI.
15566c120f0SFrancesco Petrogalli   return TLI.getLibFunc(F, LF) ||
15666c120f0SFrancesco Petrogalli          TLI.isKnownVectorFunctionInLibrary(F.getName());
157f59a8387SChandler Carruth }
158f59a8387SChandler Carruth 
LazyCallGraph(Module & M,function_ref<TargetLibraryInfo & (Function &)> GetTLI)1599c27b59cSTeresa Johnson LazyCallGraph::LazyCallGraph(
1609c27b59cSTeresa Johnson     Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
161d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
16299b756dbSChandler Carruth                     << "\n");
163f59a8387SChandler Carruth   for (Function &F : M) {
164f59a8387SChandler Carruth     if (F.isDeclaration())
165f59a8387SChandler Carruth       continue;
166f59a8387SChandler Carruth     // If this function is a known lib function to LLVM then we want to
167f59a8387SChandler Carruth     // synthesize reference edges to it to model the fact that LLVM can turn
168f59a8387SChandler Carruth     // arbitrary code into a library function call.
1699c27b59cSTeresa Johnson     if (isKnownLibFunction(F, GetTLI(F)))
17006a86301SChandler Carruth       LibFunctions.insert(&F);
171f59a8387SChandler Carruth 
172f59a8387SChandler Carruth     if (F.hasLocalLinkage())
173f59a8387SChandler Carruth       continue;
174f59a8387SChandler Carruth 
175f59a8387SChandler Carruth     // External linkage defined functions have edges to them from other
176f59a8387SChandler Carruth     // modules.
177d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "  Adding '" << F.getName()
17899b756dbSChandler Carruth                       << "' to entry set of the graph.\n");
179aaad9f84SChandler Carruth     addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
18099b756dbSChandler Carruth   }
181bf71a34eSChandler Carruth 
18236fc9c31SGuozhi Wei   // Externally visible aliases of internal functions are also viable entry
18336fc9c31SGuozhi Wei   // edges to the module.
18436fc9c31SGuozhi Wei   for (auto &A : M.aliases()) {
18536fc9c31SGuozhi Wei     if (A.hasLocalLinkage())
18636fc9c31SGuozhi Wei       continue;
18736fc9c31SGuozhi Wei     if (Function* F = dyn_cast<Function>(A.getAliasee())) {
18836fc9c31SGuozhi Wei       LLVM_DEBUG(dbgs() << "  Adding '" << F->getName()
18936fc9c31SGuozhi Wei                         << "' with alias '" << A.getName()
19036fc9c31SGuozhi Wei                         << "' to entry set of the graph.\n");
19136fc9c31SGuozhi Wei       addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(*F), Edge::Ref);
19236fc9c31SGuozhi Wei     }
19336fc9c31SGuozhi Wei   }
19436fc9c31SGuozhi Wei 
195bf71a34eSChandler Carruth   // Now add entry nodes for functions reachable via initializers to globals.
196bf71a34eSChandler Carruth   SmallVector<Constant *, 16> Worklist;
197bf71a34eSChandler Carruth   SmallPtrSet<Constant *, 16> Visited;
198b9e2f8c4SChandler Carruth   for (GlobalVariable &GV : M.globals())
199b9e2f8c4SChandler Carruth     if (GV.hasInitializer())
20070573dcdSDavid Blaikie       if (Visited.insert(GV.getInitializer()).second)
201b9e2f8c4SChandler Carruth         Worklist.push_back(GV.getInitializer());
202bf71a34eSChandler Carruth 
203d34e60caSNicola Zaghen   LLVM_DEBUG(
204d34e60caSNicola Zaghen       dbgs() << "  Adding functions referenced by global initializers to the "
20599b756dbSChandler Carruth                 "entry set.\n");
20688823468SChandler Carruth   visitReferences(Worklist, Visited, [&](Function &F) {
207aaad9f84SChandler Carruth     addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
208aaad9f84SChandler Carruth             LazyCallGraph::Edge::Ref);
20988823468SChandler Carruth   });
210c5026b67SChandler Carruth }
211bf71a34eSChandler Carruth 
LazyCallGraph(LazyCallGraph && G)212bf71a34eSChandler Carruth LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
2132174f44fSChandler Carruth     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
214aaad9f84SChandler Carruth       EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
215adbf14abSChandler Carruth       SCCMap(std::move(G.SCCMap)),
216f59a8387SChandler Carruth       LibFunctions(std::move(G.LibFunctions)) {
217d8d865e2SChandler Carruth   updateGraphPtrs();
218d8d865e2SChandler Carruth }
219d8d865e2SChandler Carruth 
invalidate(Module &,const PreservedAnalyses & PA,ModuleAnalysisManager::Invalidator &)22078d4096dSAlina Sbirlea bool LazyCallGraph::invalidate(Module &, const PreservedAnalyses &PA,
22178d4096dSAlina Sbirlea                                ModuleAnalysisManager::Invalidator &) {
22278d4096dSAlina Sbirlea   // Check whether the analysis, all analyses on functions, or the function's
22378d4096dSAlina Sbirlea   // CFG have been preserved.
22478d4096dSAlina Sbirlea   auto PAC = PA.getChecker<llvm::LazyCallGraphAnalysis>();
225259390deSArthur Eubanks   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>());
22678d4096dSAlina Sbirlea }
22778d4096dSAlina Sbirlea 
operator =(LazyCallGraph && G)228d8d865e2SChandler Carruth LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
229d8d865e2SChandler Carruth   BPA = std::move(G.BPA);
2302174f44fSChandler Carruth   NodeMap = std::move(G.NodeMap);
231a4499e9fSChandler Carruth   EntryEdges = std::move(G.EntryEdges);
232d8d865e2SChandler Carruth   SCCBPA = std::move(G.SCCBPA);
233d8d865e2SChandler Carruth   SCCMap = std::move(G.SCCMap);
234f59a8387SChandler Carruth   LibFunctions = std::move(G.LibFunctions);
235d8d865e2SChandler Carruth   updateGraphPtrs();
236d8d865e2SChandler Carruth   return *this;
237d8d865e2SChandler Carruth }
238d8d865e2SChandler Carruth 
239615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const2408c209aa8SMatthias Braun LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
241dca83408SChandler Carruth   dbgs() << *this << '\n';
242dca83408SChandler Carruth }
2438c209aa8SMatthias Braun #endif
244dca83408SChandler Carruth 
2451bcfa84aSTomas Matheson #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
verify()246e5944d97SChandler Carruth void LazyCallGraph::SCC::verify() {
247e5944d97SChandler Carruth   assert(OuterRefSCC && "Can't have a null RefSCC!");
248e5944d97SChandler Carruth   assert(!Nodes.empty() && "Can't have an empty SCC!");
249e5944d97SChandler Carruth 
250e5944d97SChandler Carruth   for (Node *N : Nodes) {
251e5944d97SChandler Carruth     assert(N && "Can't have a null node!");
252e5944d97SChandler Carruth     assert(OuterRefSCC->G->lookupSCC(*N) == this &&
253e5944d97SChandler Carruth            "Node does not map to this SCC!");
254e5944d97SChandler Carruth     assert(N->DFSNumber == -1 &&
255e5944d97SChandler Carruth            "Must set DFS numbers to -1 when adding a node to an SCC!");
256e5944d97SChandler Carruth     assert(N->LowLink == -1 &&
257e5944d97SChandler Carruth            "Must set low link to -1 when adding a node to an SCC!");
258aaad9f84SChandler Carruth     for (Edge &E : **N)
25939df40d8SChandler Carruth       assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
2607fea561eSArthur Eubanks 
2617fea561eSArthur Eubanks #ifdef EXPENSIVE_CHECKS
2627fea561eSArthur Eubanks     // Verify that all nodes in this SCC can reach all other nodes.
2637fea561eSArthur Eubanks     SmallVector<Node *, 4> Worklist;
2647fea561eSArthur Eubanks     SmallPtrSet<Node *, 4> Visited;
2657fea561eSArthur Eubanks     Worklist.push_back(N);
2667fea561eSArthur Eubanks     while (!Worklist.empty()) {
2677fea561eSArthur Eubanks       Node *VisitingNode = Worklist.pop_back_val();
2687fea561eSArthur Eubanks       if (!Visited.insert(VisitingNode).second)
2697fea561eSArthur Eubanks         continue;
2707fea561eSArthur Eubanks       for (Edge &E : (*VisitingNode)->calls())
2717fea561eSArthur Eubanks         Worklist.push_back(&E.getNode());
2727fea561eSArthur Eubanks     }
2737fea561eSArthur Eubanks     for (Node *NodeToVisit : Nodes) {
2747fea561eSArthur Eubanks       assert(Visited.contains(NodeToVisit) &&
2757fea561eSArthur Eubanks              "Cannot reach all nodes within SCC");
2767fea561eSArthur Eubanks     }
2777fea561eSArthur Eubanks #endif
278e5944d97SChandler Carruth   }
279e5944d97SChandler Carruth }
280e5944d97SChandler Carruth #endif
281e5944d97SChandler Carruth 
isParentOf(const SCC & C) const282bae595b7SChandler Carruth bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
283bae595b7SChandler Carruth   if (this == &C)
284bae595b7SChandler Carruth     return false;
285bae595b7SChandler Carruth 
286bae595b7SChandler Carruth   for (Node &N : *this)
287aaad9f84SChandler Carruth     for (Edge &E : N->calls())
288aaad9f84SChandler Carruth       if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
289bae595b7SChandler Carruth         return true;
290bae595b7SChandler Carruth 
291bae595b7SChandler Carruth   // No edges found.
292bae595b7SChandler Carruth   return false;
293bae595b7SChandler Carruth }
294bae595b7SChandler Carruth 
isAncestorOf(const SCC & TargetC) const295bae595b7SChandler Carruth bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
296bae595b7SChandler Carruth   if (this == &TargetC)
297bae595b7SChandler Carruth     return false;
298bae595b7SChandler Carruth 
299bae595b7SChandler Carruth   LazyCallGraph &G = *OuterRefSCC->G;
300bae595b7SChandler Carruth 
301bae595b7SChandler Carruth   // Start with this SCC.
302bae595b7SChandler Carruth   SmallPtrSet<const SCC *, 16> Visited = {this};
303bae595b7SChandler Carruth   SmallVector<const SCC *, 16> Worklist = {this};
304bae595b7SChandler Carruth 
305bae595b7SChandler Carruth   // Walk down the graph until we run out of edges or find a path to TargetC.
306bae595b7SChandler Carruth   do {
307bae595b7SChandler Carruth     const SCC &C = *Worklist.pop_back_val();
308bae595b7SChandler Carruth     for (Node &N : C)
309aaad9f84SChandler Carruth       for (Edge &E : N->calls()) {
310aaad9f84SChandler Carruth         SCC *CalleeC = G.lookupSCC(E.getNode());
311bae595b7SChandler Carruth         if (!CalleeC)
312bae595b7SChandler Carruth           continue;
313bae595b7SChandler Carruth 
314bae595b7SChandler Carruth         // If the callee's SCC is the TargetC, we're done.
315bae595b7SChandler Carruth         if (CalleeC == &TargetC)
316bae595b7SChandler Carruth           return true;
317bae595b7SChandler Carruth 
318bae595b7SChandler Carruth         // If this is the first time we've reached this SCC, put it on the
319bae595b7SChandler Carruth         // worklist to recurse through.
320bae595b7SChandler Carruth         if (Visited.insert(CalleeC).second)
321bae595b7SChandler Carruth           Worklist.push_back(CalleeC);
322bae595b7SChandler Carruth       }
323bae595b7SChandler Carruth   } while (!Worklist.empty());
324bae595b7SChandler Carruth 
325bae595b7SChandler Carruth   // No paths found.
326bae595b7SChandler Carruth   return false;
327bae595b7SChandler Carruth }
328bae595b7SChandler Carruth 
RefSCC(LazyCallGraph & G)329e5944d97SChandler Carruth LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
330e5944d97SChandler Carruth 
331615eb470SAaron Ballman #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const3328c209aa8SMatthias Braun LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
333dca83408SChandler Carruth   dbgs() << *this << '\n';
334dca83408SChandler Carruth }
3358c209aa8SMatthias Braun #endif
336dca83408SChandler Carruth 
3371bcfa84aSTomas Matheson #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
verify()338e5944d97SChandler Carruth void LazyCallGraph::RefSCC::verify() {
339e5944d97SChandler Carruth   assert(G && "Can't have a null graph!");
340e5944d97SChandler Carruth   assert(!SCCs.empty() && "Can't have an empty SCC!");
341e5944d97SChandler Carruth 
342e5944d97SChandler Carruth   // Verify basic properties of the SCCs.
34388823468SChandler Carruth   SmallPtrSet<SCC *, 4> SCCSet;
344e5944d97SChandler Carruth   for (SCC *C : SCCs) {
345e5944d97SChandler Carruth     assert(C && "Can't have a null SCC!");
346e5944d97SChandler Carruth     C->verify();
347e5944d97SChandler Carruth     assert(&C->getOuterRefSCC() == this &&
348e5944d97SChandler Carruth            "SCC doesn't think it is inside this RefSCC!");
34988823468SChandler Carruth     bool Inserted = SCCSet.insert(C).second;
35088823468SChandler Carruth     assert(Inserted && "Found a duplicate SCC!");
35123a6c3f7SChandler Carruth     auto IndexIt = SCCIndices.find(C);
35223a6c3f7SChandler Carruth     assert(IndexIt != SCCIndices.end() &&
35323a6c3f7SChandler Carruth            "Found an SCC that doesn't have an index!");
3548f92d6dbSChandler Carruth   }
3558f92d6dbSChandler Carruth 
356e5944d97SChandler Carruth   // Check that our indices map correctly.
357e5944d97SChandler Carruth   for (auto &SCCIndexPair : SCCIndices) {
358e5944d97SChandler Carruth     SCC *C = SCCIndexPair.first;
359e5944d97SChandler Carruth     int i = SCCIndexPair.second;
360e5944d97SChandler Carruth     assert(C && "Can't have a null SCC in the indices!");
36188823468SChandler Carruth     assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
362e5944d97SChandler Carruth     assert(SCCs[i] == C && "Index doesn't point to SCC!");
363e5944d97SChandler Carruth   }
364e5944d97SChandler Carruth 
365e5944d97SChandler Carruth   // Check that the SCCs are in fact in post-order.
366e5944d97SChandler Carruth   for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
367e5944d97SChandler Carruth     SCC &SourceSCC = *SCCs[i];
368e5944d97SChandler Carruth     for (Node &N : SourceSCC)
369aaad9f84SChandler Carruth       for (Edge &E : *N) {
370e5944d97SChandler Carruth         if (!E.isCall())
371e5944d97SChandler Carruth           continue;
372aaad9f84SChandler Carruth         SCC &TargetSCC = *G->lookupSCC(E.getNode());
373e5944d97SChandler Carruth         if (&TargetSCC.getOuterRefSCC() == this) {
374e5944d97SChandler Carruth           assert(SCCIndices.find(&TargetSCC)->second <= i &&
375e5944d97SChandler Carruth                  "Edge between SCCs violates post-order relationship.");
376e5944d97SChandler Carruth           continue;
377e5944d97SChandler Carruth         }
378e5944d97SChandler Carruth       }
379e5944d97SChandler Carruth   }
3807fea561eSArthur Eubanks 
3817fea561eSArthur Eubanks #ifdef EXPENSIVE_CHECKS
3827fea561eSArthur Eubanks   // Verify that all nodes in this RefSCC can reach all other nodes.
3837fea561eSArthur Eubanks   SmallVector<Node *> Nodes;
3847fea561eSArthur Eubanks   for (SCC *C : SCCs) {
3857fea561eSArthur Eubanks     for (Node &N : *C)
3867fea561eSArthur Eubanks       Nodes.push_back(&N);
3877fea561eSArthur Eubanks   }
3887fea561eSArthur Eubanks   for (Node *N : Nodes) {
3897fea561eSArthur Eubanks     SmallVector<Node *, 4> Worklist;
3907fea561eSArthur Eubanks     SmallPtrSet<Node *, 4> Visited;
3917fea561eSArthur Eubanks     Worklist.push_back(N);
3927fea561eSArthur Eubanks     while (!Worklist.empty()) {
3937fea561eSArthur Eubanks       Node *VisitingNode = Worklist.pop_back_val();
3947fea561eSArthur Eubanks       if (!Visited.insert(VisitingNode).second)
3957fea561eSArthur Eubanks         continue;
3967fea561eSArthur Eubanks       for (Edge &E : **VisitingNode)
3977fea561eSArthur Eubanks         Worklist.push_back(&E.getNode());
3987fea561eSArthur Eubanks     }
3997fea561eSArthur Eubanks     for (Node *NodeToVisit : Nodes) {
4007fea561eSArthur Eubanks       assert(Visited.contains(NodeToVisit) &&
4017fea561eSArthur Eubanks              "Cannot reach all nodes within RefSCC");
4027fea561eSArthur Eubanks     }
4037fea561eSArthur Eubanks   }
4047fea561eSArthur Eubanks #endif
405e5944d97SChandler Carruth }
406e5944d97SChandler Carruth #endif
407e5944d97SChandler Carruth 
isParentOf(const RefSCC & RC) const40838bd6b50SChandler Carruth bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
40938bd6b50SChandler Carruth   if (&RC == this)
41038bd6b50SChandler Carruth     return false;
41138bd6b50SChandler Carruth 
41238bd6b50SChandler Carruth   // Search all edges to see if this is a parent.
41338bd6b50SChandler Carruth   for (SCC &C : *this)
41438bd6b50SChandler Carruth     for (Node &N : C)
41538bd6b50SChandler Carruth       for (Edge &E : *N)
41638bd6b50SChandler Carruth         if (G->lookupRefSCC(E.getNode()) == &RC)
4174b096741SChandler Carruth           return true;
41838bd6b50SChandler Carruth 
41938bd6b50SChandler Carruth   return false;
42038bd6b50SChandler Carruth }
42138bd6b50SChandler Carruth 
isAncestorOf(const RefSCC & RC) const42238bd6b50SChandler Carruth bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
42338bd6b50SChandler Carruth   if (&RC == this)
42438bd6b50SChandler Carruth     return false;
42538bd6b50SChandler Carruth 
42638bd6b50SChandler Carruth   // For each descendant of this RefSCC, see if one of its children is the
42738bd6b50SChandler Carruth   // argument. If not, add that descendant to the worklist and continue
42838bd6b50SChandler Carruth   // searching.
42938bd6b50SChandler Carruth   SmallVector<const RefSCC *, 4> Worklist;
43038bd6b50SChandler Carruth   SmallPtrSet<const RefSCC *, 4> Visited;
43138bd6b50SChandler Carruth   Worklist.push_back(this);
43238bd6b50SChandler Carruth   Visited.insert(this);
43338bd6b50SChandler Carruth   do {
43438bd6b50SChandler Carruth     const RefSCC &DescendantRC = *Worklist.pop_back_val();
43538bd6b50SChandler Carruth     for (SCC &C : DescendantRC)
43638bd6b50SChandler Carruth       for (Node &N : C)
43738bd6b50SChandler Carruth         for (Edge &E : *N) {
43838bd6b50SChandler Carruth           auto *ChildRC = G->lookupRefSCC(E.getNode());
43938bd6b50SChandler Carruth           if (ChildRC == &RC)
44038bd6b50SChandler Carruth             return true;
44138bd6b50SChandler Carruth           if (!ChildRC || !Visited.insert(ChildRC).second)
44238bd6b50SChandler Carruth             continue;
44338bd6b50SChandler Carruth           Worklist.push_back(ChildRC);
44438bd6b50SChandler Carruth         }
44538bd6b50SChandler Carruth   } while (!Worklist.empty());
4464b096741SChandler Carruth 
4474b096741SChandler Carruth   return false;
4484b096741SChandler Carruth }
4494b096741SChandler Carruth 
4501f621f0aSChandler Carruth /// Generic helper that updates a postorder sequence of SCCs for a potentially
4511f621f0aSChandler Carruth /// cycle-introducing edge insertion.
4521f621f0aSChandler Carruth ///
4531f621f0aSChandler Carruth /// A postorder sequence of SCCs of a directed graph has one fundamental
4541f621f0aSChandler Carruth /// property: all deges in the DAG of SCCs point "up" the sequence. That is,
4551f621f0aSChandler Carruth /// all edges in the SCC DAG point to prior SCCs in the sequence.
4561f621f0aSChandler Carruth ///
4571f621f0aSChandler Carruth /// This routine both updates a postorder sequence and uses that sequence to
4581f621f0aSChandler Carruth /// compute the set of SCCs connected into a cycle. It should only be called to
4591f621f0aSChandler Carruth /// insert a "downward" edge which will require changing the sequence to
4601f621f0aSChandler Carruth /// restore it to a postorder.
4611f621f0aSChandler Carruth ///
4621f621f0aSChandler Carruth /// When inserting an edge from an earlier SCC to a later SCC in some postorder
4631f621f0aSChandler Carruth /// sequence, all of the SCCs which may be impacted are in the closed range of
4641f621f0aSChandler Carruth /// those two within the postorder sequence. The algorithm used here to restore
4651f621f0aSChandler Carruth /// the state is as follows:
4661f621f0aSChandler Carruth ///
4671f621f0aSChandler Carruth /// 1) Starting from the source SCC, construct a set of SCCs which reach the
4681f621f0aSChandler Carruth ///    source SCC consisting of just the source SCC. Then scan toward the
4691f621f0aSChandler Carruth ///    target SCC in postorder and for each SCC, if it has an edge to an SCC
4701f621f0aSChandler Carruth ///    in the set, add it to the set. Otherwise, the source SCC is not
4711f621f0aSChandler Carruth ///    a successor, move it in the postorder sequence to immediately before
4721f621f0aSChandler Carruth ///    the source SCC, shifting the source SCC and all SCCs in the set one
4731f621f0aSChandler Carruth ///    position toward the target SCC. Stop scanning after processing the
4741f621f0aSChandler Carruth ///    target SCC.
4751f621f0aSChandler Carruth /// 2) If the source SCC is now past the target SCC in the postorder sequence,
4761f621f0aSChandler Carruth ///    and thus the new edge will flow toward the start, we are done.
4771f621f0aSChandler Carruth /// 3) Otherwise, starting from the target SCC, walk all edges which reach an
4781f621f0aSChandler Carruth ///    SCC between the source and the target, and add them to the set of
4791f621f0aSChandler Carruth ///    connected SCCs, then recurse through them. Once a complete set of the
4801f621f0aSChandler Carruth ///    SCCs the target connects to is known, hoist the remaining SCCs between
4811f621f0aSChandler Carruth ///    the source and the target to be above the target. Note that there is no
4821f621f0aSChandler Carruth ///    need to process the source SCC, it is already known to connect.
4831f621f0aSChandler Carruth /// 4) At this point, all of the SCCs in the closed range between the source
4841f621f0aSChandler Carruth ///    SCC and the target SCC in the postorder sequence are connected,
4851f621f0aSChandler Carruth ///    including the target SCC and the source SCC. Inserting the edge from
4861f621f0aSChandler Carruth ///    the source SCC to the target SCC will form a cycle out of precisely
4871f621f0aSChandler Carruth ///    these SCCs. Thus we can merge all of the SCCs in this closed range into
4881f621f0aSChandler Carruth ///    a single SCC.
4891f621f0aSChandler Carruth ///
4901f621f0aSChandler Carruth /// This process has various important properties:
4911f621f0aSChandler Carruth /// - Only mutates the SCCs when adding the edge actually changes the SCC
4921f621f0aSChandler Carruth ///   structure.
4931f621f0aSChandler Carruth /// - Never mutates SCCs which are unaffected by the change.
4941f621f0aSChandler Carruth /// - Updates the postorder sequence to correctly satisfy the postorder
4951f621f0aSChandler Carruth ///   constraint after the edge is inserted.
4961f621f0aSChandler Carruth /// - Only reorders SCCs in the closed postorder sequence from the source to
4971f621f0aSChandler Carruth ///   the target, so easy to bound how much has changed even in the ordering.
4981f621f0aSChandler Carruth /// - Big-O is the number of edges in the closed postorder range of SCCs from
4991f621f0aSChandler Carruth ///   source to target.
5001f621f0aSChandler Carruth ///
5011f621f0aSChandler Carruth /// This helper routine, in addition to updating the postorder sequence itself
5021a8456daSVedant Kumar /// will also update a map from SCCs to indices within that sequence.
5031f621f0aSChandler Carruth ///
5041f621f0aSChandler Carruth /// The sequence and the map must operate on pointers to the SCC type.
5051f621f0aSChandler Carruth ///
5061f621f0aSChandler Carruth /// Two callbacks must be provided. The first computes the subset of SCCs in
5071f621f0aSChandler Carruth /// the postorder closed range from the source to the target which connect to
5081f621f0aSChandler Carruth /// the source SCC via some (transitive) set of edges. The second computes the
5091f621f0aSChandler Carruth /// subset of the same range which the target SCC connects to via some
5101f621f0aSChandler Carruth /// (transitive) set of edges. Both callbacks should populate the set argument
5111f621f0aSChandler Carruth /// provided.
5121f621f0aSChandler Carruth template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
5131f621f0aSChandler Carruth           typename ComputeSourceConnectedSetCallableT,
5141f621f0aSChandler Carruth           typename ComputeTargetConnectedSetCallableT>
5151f621f0aSChandler Carruth static iterator_range<typename PostorderSequenceT::iterator>
updatePostorderSequenceForEdgeInsertion(SCCT & SourceSCC,SCCT & TargetSCC,PostorderSequenceT & SCCs,SCCIndexMapT & SCCIndices,ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet)5161f621f0aSChandler Carruth updatePostorderSequenceForEdgeInsertion(
5171f621f0aSChandler Carruth     SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
5181f621f0aSChandler Carruth     SCCIndexMapT &SCCIndices,
5191f621f0aSChandler Carruth     ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
5201f621f0aSChandler Carruth     ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
5211f621f0aSChandler Carruth   int SourceIdx = SCCIndices[&SourceSCC];
5221f621f0aSChandler Carruth   int TargetIdx = SCCIndices[&TargetSCC];
5231f621f0aSChandler Carruth   assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
5241f621f0aSChandler Carruth 
5251f621f0aSChandler Carruth   SmallPtrSet<SCCT *, 4> ConnectedSet;
5261f621f0aSChandler Carruth 
5271f621f0aSChandler Carruth   // Compute the SCCs which (transitively) reach the source.
5281f621f0aSChandler Carruth   ComputeSourceConnectedSet(ConnectedSet);
5291f621f0aSChandler Carruth 
5301f621f0aSChandler Carruth   // Partition the SCCs in this part of the port-order sequence so only SCCs
5311f621f0aSChandler Carruth   // connecting to the source remain between it and the target. This is
5321f621f0aSChandler Carruth   // a benign partition as it preserves postorder.
5331f621f0aSChandler Carruth   auto SourceI = std::stable_partition(
5341f621f0aSChandler Carruth       SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
5351f621f0aSChandler Carruth       [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
5361f621f0aSChandler Carruth   for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
5371f621f0aSChandler Carruth     SCCIndices.find(SCCs[i])->second = i;
5381f621f0aSChandler Carruth 
5391f621f0aSChandler Carruth   // If the target doesn't connect to the source, then we've corrected the
5401f621f0aSChandler Carruth   // post-order and there are no cycles formed.
5411f621f0aSChandler Carruth   if (!ConnectedSet.count(&TargetSCC)) {
5421f621f0aSChandler Carruth     assert(SourceI > (SCCs.begin() + SourceIdx) &&
5431f621f0aSChandler Carruth            "Must have moved the source to fix the post-order.");
5441f621f0aSChandler Carruth     assert(*std::prev(SourceI) == &TargetSCC &&
5451f621f0aSChandler Carruth            "Last SCC to move should have bene the target.");
5461f621f0aSChandler Carruth 
5471f621f0aSChandler Carruth     // Return an empty range at the target SCC indicating there is nothing to
5481f621f0aSChandler Carruth     // merge.
5491f621f0aSChandler Carruth     return make_range(std::prev(SourceI), std::prev(SourceI));
5501f621f0aSChandler Carruth   }
5511f621f0aSChandler Carruth 
5521f621f0aSChandler Carruth   assert(SCCs[TargetIdx] == &TargetSCC &&
5531f621f0aSChandler Carruth          "Should not have moved target if connected!");
5541f621f0aSChandler Carruth   SourceIdx = SourceI - SCCs.begin();
5551f621f0aSChandler Carruth   assert(SCCs[SourceIdx] == &SourceSCC &&
5561f621f0aSChandler Carruth          "Bad updated index computation for the source SCC!");
5571f621f0aSChandler Carruth 
5581f621f0aSChandler Carruth 
5591f621f0aSChandler Carruth   // See whether there are any remaining intervening SCCs between the source
5601f621f0aSChandler Carruth   // and target. If so we need to make sure they all are reachable form the
5611f621f0aSChandler Carruth   // target.
5621f621f0aSChandler Carruth   if (SourceIdx + 1 < TargetIdx) {
5631f621f0aSChandler Carruth     ConnectedSet.clear();
5641f621f0aSChandler Carruth     ComputeTargetConnectedSet(ConnectedSet);
5651f621f0aSChandler Carruth 
5661f621f0aSChandler Carruth     // Partition SCCs so that only SCCs reached from the target remain between
5671f621f0aSChandler Carruth     // the source and the target. This preserves postorder.
5681f621f0aSChandler Carruth     auto TargetI = std::stable_partition(
5691f621f0aSChandler Carruth         SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
5701f621f0aSChandler Carruth         [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
5711f621f0aSChandler Carruth     for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
5721f621f0aSChandler Carruth       SCCIndices.find(SCCs[i])->second = i;
5731f621f0aSChandler Carruth     TargetIdx = std::prev(TargetI) - SCCs.begin();
5741f621f0aSChandler Carruth     assert(SCCs[TargetIdx] == &TargetSCC &&
5751f621f0aSChandler Carruth            "Should always end with the target!");
5761f621f0aSChandler Carruth   }
5771f621f0aSChandler Carruth 
5781f621f0aSChandler Carruth   // At this point, we know that connecting source to target forms a cycle
5791f621f0aSChandler Carruth   // because target connects back to source, and we know that all of the SCCs
5801f621f0aSChandler Carruth   // between the source and target in the postorder sequence participate in that
5811f621f0aSChandler Carruth   // cycle.
5821f621f0aSChandler Carruth   return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
5831f621f0aSChandler Carruth }
5841f621f0aSChandler Carruth 
585c213c67dSChandler Carruth bool
switchInternalEdgeToCall(Node & SourceN,Node & TargetN,function_ref<void (ArrayRef<SCC * > MergeSCCs)> MergeCB)586c213c67dSChandler Carruth LazyCallGraph::RefSCC::switchInternalEdgeToCall(
587c213c67dSChandler Carruth     Node &SourceN, Node &TargetN,
588c213c67dSChandler Carruth     function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
589aaad9f84SChandler Carruth   assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
590e5944d97SChandler Carruth   SmallVector<SCC *, 1> DeletedSCCs;
5915217c945SChandler Carruth 
592468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
59311b3f60cSChandler Carruth   verify();
59411b3f60cSChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
59511b3f60cSChandler Carruth #endif
59611b3f60cSChandler Carruth 
597e5944d97SChandler Carruth   SCC &SourceSCC = *G->lookupSCC(SourceN);
598e5944d97SChandler Carruth   SCC &TargetSCC = *G->lookupSCC(TargetN);
599e5944d97SChandler Carruth 
600e5944d97SChandler Carruth   // If the two nodes are already part of the same SCC, we're also done as
601e5944d97SChandler Carruth   // we've just added more connectivity.
602e5944d97SChandler Carruth   if (&SourceSCC == &TargetSCC) {
603aaad9f84SChandler Carruth     SourceN->setEdgeKind(TargetN, Edge::Call);
604c213c67dSChandler Carruth     return false; // No new cycle.
6055217c945SChandler Carruth   }
6065217c945SChandler Carruth 
607e5944d97SChandler Carruth   // At this point we leverage the postorder list of SCCs to detect when the
608e5944d97SChandler Carruth   // insertion of an edge changes the SCC structure in any way.
609e5944d97SChandler Carruth   //
610e5944d97SChandler Carruth   // First and foremost, we can eliminate the need for any changes when the
611e5944d97SChandler Carruth   // edge is toward the beginning of the postorder sequence because all edges
612e5944d97SChandler Carruth   // flow in that direction already. Thus adding a new one cannot form a cycle.
613e5944d97SChandler Carruth   int SourceIdx = SCCIndices[&SourceSCC];
614e5944d97SChandler Carruth   int TargetIdx = SCCIndices[&TargetSCC];
615e5944d97SChandler Carruth   if (TargetIdx < SourceIdx) {
616aaad9f84SChandler Carruth     SourceN->setEdgeKind(TargetN, Edge::Call);
617c213c67dSChandler Carruth     return false; // No new cycle.
618e5944d97SChandler Carruth   }
619e5944d97SChandler Carruth 
620e5944d97SChandler Carruth   // Compute the SCCs which (transitively) reach the source.
6211f621f0aSChandler Carruth   auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
622468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
6231f621f0aSChandler Carruth     // Check that the RefSCC is still valid before computing this as the
6241f621f0aSChandler Carruth     // results will be nonsensical of we've broken its invariants.
6251f621f0aSChandler Carruth     verify();
6261f621f0aSChandler Carruth #endif
627e5944d97SChandler Carruth     ConnectedSet.insert(&SourceSCC);
628e5944d97SChandler Carruth     auto IsConnected = [&](SCC &C) {
629e5944d97SChandler Carruth       for (Node &N : C)
630aaad9f84SChandler Carruth         for (Edge &E : N->calls())
631aaad9f84SChandler Carruth           if (ConnectedSet.count(G->lookupSCC(E.getNode())))
632e5944d97SChandler Carruth             return true;
633e5944d97SChandler Carruth 
634e5944d97SChandler Carruth       return false;
635e5944d97SChandler Carruth     };
636e5944d97SChandler Carruth 
637e5944d97SChandler Carruth     for (SCC *C :
638e5944d97SChandler Carruth          make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
639e5944d97SChandler Carruth       if (IsConnected(*C))
640e5944d97SChandler Carruth         ConnectedSet.insert(C);
6411f621f0aSChandler Carruth   };
642e5944d97SChandler Carruth 
643e5944d97SChandler Carruth   // Use a normal worklist to find which SCCs the target connects to. We still
644e5944d97SChandler Carruth   // bound the search based on the range in the postorder list we care about,
645e5944d97SChandler Carruth   // but because this is forward connectivity we just "recurse" through the
646e5944d97SChandler Carruth   // edges.
6471f621f0aSChandler Carruth   auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
648468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
6491f621f0aSChandler Carruth     // Check that the RefSCC is still valid before computing this as the
6501f621f0aSChandler Carruth     // results will be nonsensical of we've broken its invariants.
6511f621f0aSChandler Carruth     verify();
6521f621f0aSChandler Carruth #endif
653e5944d97SChandler Carruth     ConnectedSet.insert(&TargetSCC);
654e5944d97SChandler Carruth     SmallVector<SCC *, 4> Worklist;
655e5944d97SChandler Carruth     Worklist.push_back(&TargetSCC);
656e5944d97SChandler Carruth     do {
657e5944d97SChandler Carruth       SCC &C = *Worklist.pop_back_val();
658e5944d97SChandler Carruth       for (Node &N : C)
659aaad9f84SChandler Carruth         for (Edge &E : *N) {
660e5944d97SChandler Carruth           if (!E.isCall())
661e5944d97SChandler Carruth             continue;
662aaad9f84SChandler Carruth           SCC &EdgeC = *G->lookupSCC(E.getNode());
663e5944d97SChandler Carruth           if (&EdgeC.getOuterRefSCC() != this)
664e5944d97SChandler Carruth             // Not in this RefSCC...
665e5944d97SChandler Carruth             continue;
666e5944d97SChandler Carruth           if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
667e5944d97SChandler Carruth             // Not in the postorder sequence between source and target.
668e5944d97SChandler Carruth             continue;
669e5944d97SChandler Carruth 
670e5944d97SChandler Carruth           if (ConnectedSet.insert(&EdgeC).second)
671e5944d97SChandler Carruth             Worklist.push_back(&EdgeC);
672e5944d97SChandler Carruth         }
673e5944d97SChandler Carruth     } while (!Worklist.empty());
6741f621f0aSChandler Carruth   };
675e5944d97SChandler Carruth 
6761f621f0aSChandler Carruth   // Use a generic helper to update the postorder sequence of SCCs and return
6771f621f0aSChandler Carruth   // a range of any SCCs connected into a cycle by inserting this edge. This
6781f621f0aSChandler Carruth   // routine will also take care of updating the indices into the postorder
6791f621f0aSChandler Carruth   // sequence.
6801f621f0aSChandler Carruth   auto MergeRange = updatePostorderSequenceForEdgeInsertion(
6811f621f0aSChandler Carruth       SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
6821f621f0aSChandler Carruth       ComputeTargetConnectedSet);
683e5944d97SChandler Carruth 
684c213c67dSChandler Carruth   // Run the user's callback on the merged SCCs before we actually merge them.
685c213c67dSChandler Carruth   if (MergeCB)
686c213c67dSChandler Carruth     MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
687c213c67dSChandler Carruth 
6881f621f0aSChandler Carruth   // If the merge range is empty, then adding the edge didn't actually form any
6891f621f0aSChandler Carruth   // new cycles. We're done.
690fdaa7421SJordan Rose   if (MergeRange.empty()) {
6911f621f0aSChandler Carruth     // Now that the SCC structure is finalized, flip the kind to call.
692aaad9f84SChandler Carruth     SourceN->setEdgeKind(TargetN, Edge::Call);
693c213c67dSChandler Carruth     return false; // No new cycle.
694e5944d97SChandler Carruth   }
695e5944d97SChandler Carruth 
696468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
6971f621f0aSChandler Carruth   // Before merging, check that the RefSCC remains valid after all the
6981f621f0aSChandler Carruth   // postorder updates.
6991f621f0aSChandler Carruth   verify();
7001f621f0aSChandler Carruth #endif
7011f621f0aSChandler Carruth 
7021f621f0aSChandler Carruth   // Otherwise we need to merge all of the SCCs in the cycle into a single
703e5944d97SChandler Carruth   // result SCC.
704e5944d97SChandler Carruth   //
705e5944d97SChandler Carruth   // NB: We merge into the target because all of these functions were already
706e5944d97SChandler Carruth   // reachable from the target, meaning any SCC-wide properties deduced about it
707e5944d97SChandler Carruth   // other than the set of functions within it will not have changed.
708e5944d97SChandler Carruth   for (SCC *C : MergeRange) {
709e5944d97SChandler Carruth     assert(C != &TargetSCC &&
710e5944d97SChandler Carruth            "We merge *into* the target and shouldn't process it here!");
711e5944d97SChandler Carruth     SCCIndices.erase(C);
712e5944d97SChandler Carruth     TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
713e5944d97SChandler Carruth     for (Node *N : C->Nodes)
714e5944d97SChandler Carruth       G->SCCMap[N] = &TargetSCC;
715e5944d97SChandler Carruth     C->clear();
716e5944d97SChandler Carruth     DeletedSCCs.push_back(C);
717e5944d97SChandler Carruth   }
718e5944d97SChandler Carruth 
719e5944d97SChandler Carruth   // Erase the merged SCCs from the list and update the indices of the
720e5944d97SChandler Carruth   // remaining SCCs.
721e5944d97SChandler Carruth   int IndexOffset = MergeRange.end() - MergeRange.begin();
722e5944d97SChandler Carruth   auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
723e5944d97SChandler Carruth   for (SCC *C : make_range(EraseEnd, SCCs.end()))
724e5944d97SChandler Carruth     SCCIndices[C] -= IndexOffset;
725e5944d97SChandler Carruth 
726e5944d97SChandler Carruth   // Now that the SCC structure is finalized, flip the kind to call.
727aaad9f84SChandler Carruth   SourceN->setEdgeKind(TargetN, Edge::Call);
728e5944d97SChandler Carruth 
729c213c67dSChandler Carruth   // And we're done, but we did form a new cycle.
730c213c67dSChandler Carruth   return true;
731e5944d97SChandler Carruth }
732e5944d97SChandler Carruth 
switchTrivialInternalEdgeToRef(Node & SourceN,Node & TargetN)733443e57e0SChandler Carruth void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
734443e57e0SChandler Carruth                                                            Node &TargetN) {
735aaad9f84SChandler Carruth   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
736443e57e0SChandler Carruth 
737468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
738443e57e0SChandler Carruth   verify();
739443e57e0SChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
740443e57e0SChandler Carruth #endif
741443e57e0SChandler Carruth 
742443e57e0SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this &&
743443e57e0SChandler Carruth          "Source must be in this RefSCC.");
744443e57e0SChandler Carruth   assert(G->lookupRefSCC(TargetN) == this &&
745443e57e0SChandler Carruth          "Target must be in this RefSCC.");
746443e57e0SChandler Carruth   assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
747443e57e0SChandler Carruth          "Source and Target must be in separate SCCs for this to be trivial!");
748443e57e0SChandler Carruth 
749443e57e0SChandler Carruth   // Set the edge kind.
750aaad9f84SChandler Carruth   SourceN->setEdgeKind(TargetN, Edge::Ref);
751443e57e0SChandler Carruth }
752443e57e0SChandler Carruth 
75388823468SChandler Carruth iterator_range<LazyCallGraph::RefSCC::iterator>
switchInternalEdgeToRef(Node & SourceN,Node & TargetN)75488823468SChandler Carruth LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
755aaad9f84SChandler Carruth   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
756e5944d97SChandler Carruth 
757468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
75811b3f60cSChandler Carruth   verify();
75911b3f60cSChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
76011b3f60cSChandler Carruth #endif
76111b3f60cSChandler Carruth 
762443e57e0SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this &&
763e5944d97SChandler Carruth          "Source must be in this RefSCC.");
764443e57e0SChandler Carruth   assert(G->lookupRefSCC(TargetN) == this &&
765e5944d97SChandler Carruth          "Target must be in this RefSCC.");
766e5944d97SChandler Carruth 
767443e57e0SChandler Carruth   SCC &TargetSCC = *G->lookupSCC(TargetN);
768443e57e0SChandler Carruth   assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
769443e57e0SChandler Carruth                                                 "the same SCC to require the "
770443e57e0SChandler Carruth                                                 "full CG update.");
771443e57e0SChandler Carruth 
772e5944d97SChandler Carruth   // Set the edge kind.
773aaad9f84SChandler Carruth   SourceN->setEdgeKind(TargetN, Edge::Ref);
774e5944d97SChandler Carruth 
775e5944d97SChandler Carruth   // Otherwise we are removing a call edge from a single SCC. This may break
776e5944d97SChandler Carruth   // the cycle. In order to compute the new set of SCCs, we need to do a small
777e5944d97SChandler Carruth   // DFS over the nodes within the SCC to form any sub-cycles that remain as
778e5944d97SChandler Carruth   // distinct SCCs and compute a postorder over the resulting SCCs.
779e5944d97SChandler Carruth   //
780e5944d97SChandler Carruth   // However, we specially handle the target node. The target node is known to
781e5944d97SChandler Carruth   // reach all other nodes in the original SCC by definition. This means that
7821a8456daSVedant Kumar   // we want the old SCC to be replaced with an SCC containing that node as it
783e5944d97SChandler Carruth   // will be the root of whatever SCC DAG results from the DFS. Assumptions
784e5944d97SChandler Carruth   // about an SCC such as the set of functions called will continue to hold,
785e5944d97SChandler Carruth   // etc.
786e5944d97SChandler Carruth 
787e5944d97SChandler Carruth   SCC &OldSCC = TargetSCC;
788aaad9f84SChandler Carruth   SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
789e5944d97SChandler Carruth   SmallVector<Node *, 16> PendingSCCStack;
790e5944d97SChandler Carruth   SmallVector<SCC *, 4> NewSCCs;
791e5944d97SChandler Carruth 
792e5944d97SChandler Carruth   // Prepare the nodes for a fresh DFS.
793e5944d97SChandler Carruth   SmallVector<Node *, 16> Worklist;
794e5944d97SChandler Carruth   Worklist.swap(OldSCC.Nodes);
795e5944d97SChandler Carruth   for (Node *N : Worklist) {
796e5944d97SChandler Carruth     N->DFSNumber = N->LowLink = 0;
797e5944d97SChandler Carruth     G->SCCMap.erase(N);
798e5944d97SChandler Carruth   }
799e5944d97SChandler Carruth 
800e5944d97SChandler Carruth   // Force the target node to be in the old SCC. This also enables us to take
801e5944d97SChandler Carruth   // a very significant short-cut in the standard Tarjan walk to re-form SCCs
802e5944d97SChandler Carruth   // below: whenever we build an edge that reaches the target node, we know
803e5944d97SChandler Carruth   // that the target node eventually connects back to all other nodes in our
804e5944d97SChandler Carruth   // walk. As a consequence, we can detect and handle participants in that
805e5944d97SChandler Carruth   // cycle without walking all the edges that form this connection, and instead
806e5944d97SChandler Carruth   // by relying on the fundamental guarantee coming into this operation (all
807e5944d97SChandler Carruth   // nodes are reachable from the target due to previously forming an SCC).
808e5944d97SChandler Carruth   TargetN.DFSNumber = TargetN.LowLink = -1;
809e5944d97SChandler Carruth   OldSCC.Nodes.push_back(&TargetN);
810e5944d97SChandler Carruth   G->SCCMap[&TargetN] = &OldSCC;
811e5944d97SChandler Carruth 
812e5944d97SChandler Carruth   // Scan down the stack and DFS across the call edges.
813e5944d97SChandler Carruth   for (Node *RootN : Worklist) {
814e5944d97SChandler Carruth     assert(DFSStack.empty() &&
815e5944d97SChandler Carruth            "Cannot begin a new root with a non-empty DFS stack!");
816e5944d97SChandler Carruth     assert(PendingSCCStack.empty() &&
817e5944d97SChandler Carruth            "Cannot begin a new root with pending nodes for an SCC!");
818e5944d97SChandler Carruth 
819e5944d97SChandler Carruth     // Skip any nodes we've already reached in the DFS.
820e5944d97SChandler Carruth     if (RootN->DFSNumber != 0) {
821e5944d97SChandler Carruth       assert(RootN->DFSNumber == -1 &&
822e5944d97SChandler Carruth              "Shouldn't have any mid-DFS root nodes!");
823e5944d97SChandler Carruth       continue;
824e5944d97SChandler Carruth     }
825e5944d97SChandler Carruth 
826e5944d97SChandler Carruth     RootN->DFSNumber = RootN->LowLink = 1;
827e5944d97SChandler Carruth     int NextDFSNumber = 2;
828e5944d97SChandler Carruth 
829aaad9f84SChandler Carruth     DFSStack.push_back({RootN, (*RootN)->call_begin()});
830e5944d97SChandler Carruth     do {
831e5944d97SChandler Carruth       Node *N;
832aaad9f84SChandler Carruth       EdgeSequence::call_iterator I;
833e5944d97SChandler Carruth       std::tie(N, I) = DFSStack.pop_back_val();
834aaad9f84SChandler Carruth       auto E = (*N)->call_end();
835e5944d97SChandler Carruth       while (I != E) {
836aaad9f84SChandler Carruth         Node &ChildN = I->getNode();
837e5944d97SChandler Carruth         if (ChildN.DFSNumber == 0) {
838e5944d97SChandler Carruth           // We haven't yet visited this child, so descend, pushing the current
839e5944d97SChandler Carruth           // node onto the stack.
840e5944d97SChandler Carruth           DFSStack.push_back({N, I});
841e5944d97SChandler Carruth 
842e5944d97SChandler Carruth           assert(!G->SCCMap.count(&ChildN) &&
843e5944d97SChandler Carruth                  "Found a node with 0 DFS number but already in an SCC!");
844e5944d97SChandler Carruth           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
845e5944d97SChandler Carruth           N = &ChildN;
846aaad9f84SChandler Carruth           I = (*N)->call_begin();
847aaad9f84SChandler Carruth           E = (*N)->call_end();
848e5944d97SChandler Carruth           continue;
849e5944d97SChandler Carruth         }
850e5944d97SChandler Carruth 
851e5944d97SChandler Carruth         // Check for the child already being part of some component.
852e5944d97SChandler Carruth         if (ChildN.DFSNumber == -1) {
853e5944d97SChandler Carruth           if (G->lookupSCC(ChildN) == &OldSCC) {
854e5944d97SChandler Carruth             // If the child is part of the old SCC, we know that it can reach
855e5944d97SChandler Carruth             // every other node, so we have formed a cycle. Pull the entire DFS
856e5944d97SChandler Carruth             // and pending stacks into it. See the comment above about setting
857e5944d97SChandler Carruth             // up the old SCC for why we do this.
858e5944d97SChandler Carruth             int OldSize = OldSCC.size();
859e5944d97SChandler Carruth             OldSCC.Nodes.push_back(N);
860e5944d97SChandler Carruth             OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
861e5944d97SChandler Carruth             PendingSCCStack.clear();
862e5944d97SChandler Carruth             while (!DFSStack.empty())
863e5944d97SChandler Carruth               OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
8642efcbe24SKazu Hirata             for (Node &N : drop_begin(OldSCC, OldSize)) {
865e5944d97SChandler Carruth               N.DFSNumber = N.LowLink = -1;
866e5944d97SChandler Carruth               G->SCCMap[&N] = &OldSCC;
867e5944d97SChandler Carruth             }
868e5944d97SChandler Carruth             N = nullptr;
869e5944d97SChandler Carruth             break;
870e5944d97SChandler Carruth           }
871e5944d97SChandler Carruth 
872e5944d97SChandler Carruth           // If the child has already been added to some child component, it
873e5944d97SChandler Carruth           // couldn't impact the low-link of this parent because it isn't
874e5944d97SChandler Carruth           // connected, and thus its low-link isn't relevant so skip it.
875e5944d97SChandler Carruth           ++I;
876e5944d97SChandler Carruth           continue;
877e5944d97SChandler Carruth         }
878e5944d97SChandler Carruth 
879e5944d97SChandler Carruth         // Track the lowest linked child as the lowest link for this node.
880e5944d97SChandler Carruth         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
881e5944d97SChandler Carruth         if (ChildN.LowLink < N->LowLink)
882e5944d97SChandler Carruth           N->LowLink = ChildN.LowLink;
883e5944d97SChandler Carruth 
884e5944d97SChandler Carruth         // Move to the next edge.
885e5944d97SChandler Carruth         ++I;
886e5944d97SChandler Carruth       }
887e5944d97SChandler Carruth       if (!N)
888e5944d97SChandler Carruth         // Cleared the DFS early, start another round.
889e5944d97SChandler Carruth         break;
890e5944d97SChandler Carruth 
8911a8456daSVedant Kumar       // We've finished processing N and its descendants, put it on our pending
892e5944d97SChandler Carruth       // SCC stack to eventually get merged into an SCC of nodes.
893e5944d97SChandler Carruth       PendingSCCStack.push_back(N);
894e5944d97SChandler Carruth 
895e5944d97SChandler Carruth       // If this node is linked to some lower entry, continue walking up the
896e5944d97SChandler Carruth       // stack.
897e5944d97SChandler Carruth       if (N->LowLink != N->DFSNumber)
898e5944d97SChandler Carruth         continue;
899e5944d97SChandler Carruth 
900e5944d97SChandler Carruth       // Otherwise, we've completed an SCC. Append it to our post order list of
901e5944d97SChandler Carruth       // SCCs.
902e5944d97SChandler Carruth       int RootDFSNumber = N->DFSNumber;
903e5944d97SChandler Carruth       // Find the range of the node stack by walking down until we pass the
904e5944d97SChandler Carruth       // root DFS number.
905e5944d97SChandler Carruth       auto SCCNodes = make_range(
906e5944d97SChandler Carruth           PendingSCCStack.rbegin(),
90742531260SDavid Majnemer           find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
908e5944d97SChandler Carruth             return N->DFSNumber < RootDFSNumber;
909e5944d97SChandler Carruth           }));
910e5944d97SChandler Carruth 
911e5944d97SChandler Carruth       // Form a new SCC out of these nodes and then clear them off our pending
912e5944d97SChandler Carruth       // stack.
913e5944d97SChandler Carruth       NewSCCs.push_back(G->createSCC(*this, SCCNodes));
914e5944d97SChandler Carruth       for (Node &N : *NewSCCs.back()) {
915e5944d97SChandler Carruth         N.DFSNumber = N.LowLink = -1;
916e5944d97SChandler Carruth         G->SCCMap[&N] = NewSCCs.back();
917e5944d97SChandler Carruth       }
918e5944d97SChandler Carruth       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
919e5944d97SChandler Carruth     } while (!DFSStack.empty());
920e5944d97SChandler Carruth   }
921e5944d97SChandler Carruth 
922e5944d97SChandler Carruth   // Insert the remaining SCCs before the old one. The old SCC can reach all
923e5944d97SChandler Carruth   // other SCCs we form because it contains the target node of the removed edge
924e5944d97SChandler Carruth   // of the old SCC. This means that we will have edges into all of the new
925e5944d97SChandler Carruth   // SCCs, which means the old one must come last for postorder.
926e5944d97SChandler Carruth   int OldIdx = SCCIndices[&OldSCC];
927e5944d97SChandler Carruth   SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
928e5944d97SChandler Carruth 
929e5944d97SChandler Carruth   // Update the mapping from SCC* to index to use the new SCC*s, and remove the
930e5944d97SChandler Carruth   // old SCC from the mapping.
931e5944d97SChandler Carruth   for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
932e5944d97SChandler Carruth     SCCIndices[SCCs[Idx]] = Idx;
933e5944d97SChandler Carruth 
93488823468SChandler Carruth   return make_range(SCCs.begin() + OldIdx,
93588823468SChandler Carruth                     SCCs.begin() + OldIdx + NewSCCs.size());
936e5944d97SChandler Carruth }
937e5944d97SChandler Carruth 
switchOutgoingEdgeToCall(Node & SourceN,Node & TargetN)938e5944d97SChandler Carruth void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
939e5944d97SChandler Carruth                                                      Node &TargetN) {
940aaad9f84SChandler Carruth   assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
941e5944d97SChandler Carruth 
942e5944d97SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
943e5944d97SChandler Carruth   assert(G->lookupRefSCC(TargetN) != this &&
944e5944d97SChandler Carruth          "Target must not be in this RefSCC.");
945262ad16aSFrancis Visoiu Mistrih #ifdef EXPENSIVE_CHECKS
946e5944d97SChandler Carruth   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
947e5944d97SChandler Carruth          "Target must be a descendant of the Source.");
9482e0fe3e6SChandler Carruth #endif
949e5944d97SChandler Carruth 
950e5944d97SChandler Carruth   // Edges between RefSCCs are the same regardless of call or ref, so we can
951e5944d97SChandler Carruth   // just flip the edge here.
952aaad9f84SChandler Carruth   SourceN->setEdgeKind(TargetN, Edge::Call);
953e5944d97SChandler Carruth 
954468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
955e5944d97SChandler Carruth   verify();
956e5944d97SChandler Carruth #endif
957e5944d97SChandler Carruth }
958e5944d97SChandler Carruth 
switchOutgoingEdgeToRef(Node & SourceN,Node & TargetN)959e5944d97SChandler Carruth void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
960e5944d97SChandler Carruth                                                     Node &TargetN) {
961aaad9f84SChandler Carruth   assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
962e5944d97SChandler Carruth 
963e5944d97SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
964e5944d97SChandler Carruth   assert(G->lookupRefSCC(TargetN) != this &&
965e5944d97SChandler Carruth          "Target must not be in this RefSCC.");
966262ad16aSFrancis Visoiu Mistrih #ifdef EXPENSIVE_CHECKS
967e5944d97SChandler Carruth   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
968e5944d97SChandler Carruth          "Target must be a descendant of the Source.");
9692e0fe3e6SChandler Carruth #endif
970e5944d97SChandler Carruth 
971e5944d97SChandler Carruth   // Edges between RefSCCs are the same regardless of call or ref, so we can
972e5944d97SChandler Carruth   // just flip the edge here.
973aaad9f84SChandler Carruth   SourceN->setEdgeKind(TargetN, Edge::Ref);
974e5944d97SChandler Carruth 
975468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
976e5944d97SChandler Carruth   verify();
977e5944d97SChandler Carruth #endif
978e5944d97SChandler Carruth }
979e5944d97SChandler Carruth 
insertInternalRefEdge(Node & SourceN,Node & TargetN)980e5944d97SChandler Carruth void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
981e5944d97SChandler Carruth                                                   Node &TargetN) {
982e5944d97SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
983e5944d97SChandler Carruth   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
984e5944d97SChandler Carruth 
985aaad9f84SChandler Carruth   SourceN->insertEdgeInternal(TargetN, Edge::Ref);
986e5944d97SChandler Carruth 
987468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
988e5944d97SChandler Carruth   verify();
989e5944d97SChandler Carruth #endif
990e5944d97SChandler Carruth }
991e5944d97SChandler Carruth 
insertOutgoingEdge(Node & SourceN,Node & TargetN,Edge::Kind EK)992e5944d97SChandler Carruth void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
993a4499e9fSChandler Carruth                                                Edge::Kind EK) {
9947cc4ed82SChandler Carruth   // First insert it into the caller.
995aaad9f84SChandler Carruth   SourceN->insertEdgeInternal(TargetN, EK);
9967cc4ed82SChandler Carruth 
997e5944d97SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
9987cc4ed82SChandler Carruth 
999691d0243SChandler Carruth   assert(G->lookupRefSCC(TargetN) != this &&
1000691d0243SChandler Carruth          "Target must not be in this RefSCC.");
1001262ad16aSFrancis Visoiu Mistrih #ifdef EXPENSIVE_CHECKS
1002691d0243SChandler Carruth   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
1003e5944d97SChandler Carruth          "Target must be a descendant of the Source.");
10042e0fe3e6SChandler Carruth #endif
10057cc4ed82SChandler Carruth 
1006468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
1007e5944d97SChandler Carruth   verify();
1008e5944d97SChandler Carruth #endif
10097cc4ed82SChandler Carruth }
10107cc4ed82SChandler Carruth 
1011e5944d97SChandler Carruth SmallVector<LazyCallGraph::RefSCC *, 1>
insertIncomingRefEdge(Node & SourceN,Node & TargetN)1012e5944d97SChandler Carruth LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
101349d728adSChandler Carruth   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
101449d728adSChandler Carruth   RefSCC &SourceC = *G->lookupRefSCC(SourceN);
101549d728adSChandler Carruth   assert(&SourceC != this && "Source must not be in this RefSCC.");
1016262ad16aSFrancis Visoiu Mistrih #ifdef EXPENSIVE_CHECKS
101749d728adSChandler Carruth   assert(SourceC.isDescendantOf(*this) &&
101849d728adSChandler Carruth          "Source must be a descendant of the Target.");
10192e0fe3e6SChandler Carruth #endif
102049d728adSChandler Carruth 
102149d728adSChandler Carruth   SmallVector<RefSCC *, 1> DeletedRefSCCs;
1022312dddfbSChandler Carruth 
1023468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
102411b3f60cSChandler Carruth   verify();
102511b3f60cSChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
102611b3f60cSChandler Carruth #endif
102711b3f60cSChandler Carruth 
102849d728adSChandler Carruth   int SourceIdx = G->RefSCCIndices[&SourceC];
102949d728adSChandler Carruth   int TargetIdx = G->RefSCCIndices[this];
103049d728adSChandler Carruth   assert(SourceIdx < TargetIdx &&
103149d728adSChandler Carruth          "Postorder list doesn't see edge as incoming!");
1032312dddfbSChandler Carruth 
103349d728adSChandler Carruth   // Compute the RefSCCs which (transitively) reach the source. We do this by
103449d728adSChandler Carruth   // working backwards from the source using the parent set in each RefSCC,
103549d728adSChandler Carruth   // skipping any RefSCCs that don't fall in the postorder range. This has the
103649d728adSChandler Carruth   // advantage of walking the sparser parent edge (in high fan-out graphs) but
103749d728adSChandler Carruth   // more importantly this removes examining all forward edges in all RefSCCs
103849d728adSChandler Carruth   // within the postorder range which aren't in fact connected. Only connected
103949d728adSChandler Carruth   // RefSCCs (and their edges) are visited here.
104049d728adSChandler Carruth   auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
104149d728adSChandler Carruth     Set.insert(&SourceC);
104213ffd110SChandler Carruth     auto IsConnected = [&](RefSCC &RC) {
104313ffd110SChandler Carruth       for (SCC &C : RC)
104413ffd110SChandler Carruth         for (Node &N : C)
104513ffd110SChandler Carruth           for (Edge &E : *N)
104613ffd110SChandler Carruth             if (Set.count(G->lookupRefSCC(E.getNode())))
104713ffd110SChandler Carruth               return true;
104813ffd110SChandler Carruth 
104913ffd110SChandler Carruth       return false;
105013ffd110SChandler Carruth     };
105113ffd110SChandler Carruth 
105213ffd110SChandler Carruth     for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
105313ffd110SChandler Carruth                                 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
105413ffd110SChandler Carruth       if (IsConnected(*C))
105513ffd110SChandler Carruth         Set.insert(C);
105649d728adSChandler Carruth   };
105749d728adSChandler Carruth 
105849d728adSChandler Carruth   // Use a normal worklist to find which SCCs the target connects to. We still
105949d728adSChandler Carruth   // bound the search based on the range in the postorder list we care about,
106049d728adSChandler Carruth   // but because this is forward connectivity we just "recurse" through the
106149d728adSChandler Carruth   // edges.
106249d728adSChandler Carruth   auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
106349d728adSChandler Carruth     Set.insert(this);
106449d728adSChandler Carruth     SmallVector<RefSCC *, 4> Worklist;
106549d728adSChandler Carruth     Worklist.push_back(this);
106649d728adSChandler Carruth     do {
106749d728adSChandler Carruth       RefSCC &RC = *Worklist.pop_back_val();
106849d728adSChandler Carruth       for (SCC &C : RC)
106949d728adSChandler Carruth         for (Node &N : C)
1070aaad9f84SChandler Carruth           for (Edge &E : *N) {
1071aaad9f84SChandler Carruth             RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
107249d728adSChandler Carruth             if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
107349d728adSChandler Carruth               // Not in the postorder sequence between source and target.
1074312dddfbSChandler Carruth               continue;
1075312dddfbSChandler Carruth 
107649d728adSChandler Carruth             if (Set.insert(&EdgeRC).second)
107749d728adSChandler Carruth               Worklist.push_back(&EdgeRC);
1078312dddfbSChandler Carruth           }
107949d728adSChandler Carruth     } while (!Worklist.empty());
108049d728adSChandler Carruth   };
1081312dddfbSChandler Carruth 
108249d728adSChandler Carruth   // Use a generic helper to update the postorder sequence of RefSCCs and return
108349d728adSChandler Carruth   // a range of any RefSCCs connected into a cycle by inserting this edge. This
108449d728adSChandler Carruth   // routine will also take care of updating the indices into the postorder
108549d728adSChandler Carruth   // sequence.
108649d728adSChandler Carruth   iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
108749d728adSChandler Carruth       updatePostorderSequenceForEdgeInsertion(
108849d728adSChandler Carruth           SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
108949d728adSChandler Carruth           ComputeSourceConnectedSet, ComputeTargetConnectedSet);
109049d728adSChandler Carruth 
10915205c350SChandler Carruth   // Build a set so we can do fast tests for whether a RefSCC will end up as
10925205c350SChandler Carruth   // part of the merged RefSCC.
109349d728adSChandler Carruth   SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
1094312dddfbSChandler Carruth 
10955205c350SChandler Carruth   // This RefSCC will always be part of that set, so just insert it here.
10965205c350SChandler Carruth   MergeSet.insert(this);
10975205c350SChandler Carruth 
1098312dddfbSChandler Carruth   // Now that we have identified all of the SCCs which need to be merged into
1099312dddfbSChandler Carruth   // a connected set with the inserted edge, merge all of them into this SCC.
1100e5944d97SChandler Carruth   SmallVector<SCC *, 16> MergedSCCs;
1101e5944d97SChandler Carruth   int SCCIndex = 0;
110249d728adSChandler Carruth   for (RefSCC *RC : MergeRange) {
110349d728adSChandler Carruth     assert(RC != this && "We're merging into the target RefSCC, so it "
110449d728adSChandler Carruth                          "shouldn't be in the range.");
1105312dddfbSChandler Carruth 
1106e5944d97SChandler Carruth     // Walk the inner SCCs to update their up-pointer and walk all the edges to
1107e5944d97SChandler Carruth     // update any parent sets.
1108e5944d97SChandler Carruth     // FIXME: We should try to find a way to avoid this (rather expensive) edge
1109e5944d97SChandler Carruth     // walk by updating the parent sets in some other manner.
111049d728adSChandler Carruth     for (SCC &InnerC : *RC) {
1111e5944d97SChandler Carruth       InnerC.OuterRefSCC = this;
1112e5944d97SChandler Carruth       SCCIndices[&InnerC] = SCCIndex++;
1113adbf14abSChandler Carruth       for (Node &N : InnerC)
1114e5944d97SChandler Carruth         G->SCCMap[&N] = &InnerC;
1115312dddfbSChandler Carruth     }
1116e5944d97SChandler Carruth 
1117e5944d97SChandler Carruth     // Now merge in the SCCs. We can actually move here so try to reuse storage
1118e5944d97SChandler Carruth     // the first time through.
1119e5944d97SChandler Carruth     if (MergedSCCs.empty())
112049d728adSChandler Carruth       MergedSCCs = std::move(RC->SCCs);
1121e5944d97SChandler Carruth     else
112249d728adSChandler Carruth       MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
112349d728adSChandler Carruth     RC->SCCs.clear();
112449d728adSChandler Carruth     DeletedRefSCCs.push_back(RC);
1125312dddfbSChandler Carruth   }
1126312dddfbSChandler Carruth 
112749d728adSChandler Carruth   // Append our original SCCs to the merged list and move it into place.
1128e5944d97SChandler Carruth   for (SCC &InnerC : *this)
1129e5944d97SChandler Carruth     SCCIndices[&InnerC] = SCCIndex++;
1130e5944d97SChandler Carruth   MergedSCCs.append(SCCs.begin(), SCCs.end());
1131e5944d97SChandler Carruth   SCCs = std::move(MergedSCCs);
1132e5944d97SChandler Carruth 
113349d728adSChandler Carruth   // Remove the merged away RefSCCs from the post order sequence.
113449d728adSChandler Carruth   for (RefSCC *RC : MergeRange)
113549d728adSChandler Carruth     G->RefSCCIndices.erase(RC);
113649d728adSChandler Carruth   int IndexOffset = MergeRange.end() - MergeRange.begin();
113749d728adSChandler Carruth   auto EraseEnd =
113849d728adSChandler Carruth       G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
113949d728adSChandler Carruth   for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
114049d728adSChandler Carruth     G->RefSCCIndices[RC] -= IndexOffset;
114149d728adSChandler Carruth 
1142e5944d97SChandler Carruth   // At this point we have a merged RefSCC with a post-order SCCs list, just
1143e5944d97SChandler Carruth   // connect the nodes to form the new edge.
1144aaad9f84SChandler Carruth   SourceN->insertEdgeInternal(TargetN, Edge::Ref);
1145e5944d97SChandler Carruth 
1146312dddfbSChandler Carruth   // We return the list of SCCs which were merged so that callers can
1147312dddfbSChandler Carruth   // invalidate any data they have associated with those SCCs. Note that these
1148312dddfbSChandler Carruth   // SCCs are no longer in an interesting state (they are totally empty) but
1149312dddfbSChandler Carruth   // the pointers will remain stable for the life of the graph itself.
115049d728adSChandler Carruth   return DeletedRefSCCs;
1151312dddfbSChandler Carruth }
1152312dddfbSChandler Carruth 
removeOutgoingEdge(Node & SourceN,Node & TargetN)1153e5944d97SChandler Carruth void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1154e5944d97SChandler Carruth   assert(G->lookupRefSCC(SourceN) == this &&
1155e5944d97SChandler Carruth          "The source must be a member of this RefSCC.");
1156ef42fd43SBenjamin Kramer   assert(G->lookupRefSCC(TargetN) != this &&
1157ef42fd43SBenjamin Kramer          "The target must not be a member of this RefSCC");
1158e5944d97SChandler Carruth 
1159468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
116011b3f60cSChandler Carruth   verify();
116111b3f60cSChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() { verify(); });
116211b3f60cSChandler Carruth #endif
116311b3f60cSChandler Carruth 
1164aa839b22SChandler Carruth   // First remove it from the node.
1165aaad9f84SChandler Carruth   bool Removed = SourceN->removeEdgeInternal(TargetN);
1166aaad9f84SChandler Carruth   (void)Removed;
1167aaad9f84SChandler Carruth   assert(Removed && "Target not in the edge set for this caller?");
11689302fbf0SChandler Carruth }
11699302fbf0SChandler Carruth 
1170e5944d97SChandler Carruth SmallVector<LazyCallGraph::RefSCC *, 1>
removeInternalRefEdge(Node & SourceN,ArrayRef<Node * > TargetNs)117123c2f44cSChandler Carruth LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN,
117223c2f44cSChandler Carruth                                              ArrayRef<Node *> TargetNs) {
1173e5944d97SChandler Carruth   // We return a list of the resulting *new* RefSCCs in post-order.
1174e5944d97SChandler Carruth   SmallVector<RefSCC *, 1> Result;
1175e5944d97SChandler Carruth 
1176468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
1177468fa037SArthur Eubanks   // Verify the RefSCC is valid to start with and that either we return an empty
1178468fa037SArthur Eubanks   // list of result RefSCCs and this RefSCC remains valid, or we return new
1179468fa037SArthur Eubanks   // RefSCCs and this RefSCC is dead.
118023c2f44cSChandler Carruth   verify();
118123c2f44cSChandler Carruth   auto VerifyOnExit = make_scope_exit([&]() {
11829c161e89SChandler Carruth     // If we didn't replace our RefSCC with new ones, check that this one
11839c161e89SChandler Carruth     // remains valid.
11849c161e89SChandler Carruth     if (G)
118523c2f44cSChandler Carruth       verify();
118623c2f44cSChandler Carruth   });
118723c2f44cSChandler Carruth #endif
118823c2f44cSChandler Carruth 
118923c2f44cSChandler Carruth   // First remove the actual edges.
119023c2f44cSChandler Carruth   for (Node *TargetN : TargetNs) {
119123c2f44cSChandler Carruth     assert(!(*SourceN)[*TargetN].isCall() &&
119223c2f44cSChandler Carruth            "Cannot remove a call edge, it must first be made a ref edge");
119323c2f44cSChandler Carruth 
119423c2f44cSChandler Carruth     bool Removed = SourceN->removeEdgeInternal(*TargetN);
119523c2f44cSChandler Carruth     (void)Removed;
119623c2f44cSChandler Carruth     assert(Removed && "Target not in the edge set for this caller?");
119723c2f44cSChandler Carruth   }
119823c2f44cSChandler Carruth 
119923c2f44cSChandler Carruth   // Direct self references don't impact the ref graph at all.
120023c2f44cSChandler Carruth   if (llvm::all_of(TargetNs,
120123c2f44cSChandler Carruth                    [&](Node *TargetN) { return &SourceN == TargetN; }))
1202e5944d97SChandler Carruth     return Result;
1203e5944d97SChandler Carruth 
120423c2f44cSChandler Carruth   // If all targets are in the same SCC as the source, because no call edges
120523c2f44cSChandler Carruth   // were removed there is no RefSCC structure change.
1206c6334579SChandler Carruth   SCC &SourceC = *G->lookupSCC(SourceN);
120723c2f44cSChandler Carruth   if (llvm::all_of(TargetNs, [&](Node *TargetN) {
120823c2f44cSChandler Carruth         return G->lookupSCC(*TargetN) == &SourceC;
120923c2f44cSChandler Carruth       }))
1210c6334579SChandler Carruth     return Result;
1211c6334579SChandler Carruth 
1212e5944d97SChandler Carruth   // We build somewhat synthetic new RefSCCs by providing a postorder mapping
12132cd28b2bSChandler Carruth   // for each inner SCC. We store these inside the low-link field of the nodes
12142cd28b2bSChandler Carruth   // rather than associated with SCCs because this saves a round-trip through
12152cd28b2bSChandler Carruth   // the node->SCC map and in the common case, SCCs are small. We will verify
12162cd28b2bSChandler Carruth   // that we always give the same number to every node in the SCC such that
12172cd28b2bSChandler Carruth   // these are equivalent.
121823c2f44cSChandler Carruth   int PostOrderNumber = 0;
1219e5944d97SChandler Carruth 
1220e5944d97SChandler Carruth   // Reset all the other nodes to prepare for a DFS over them, and add them to
1221e5944d97SChandler Carruth   // our worklist.
1222e5944d97SChandler Carruth   SmallVector<Node *, 8> Worklist;
1223e5944d97SChandler Carruth   for (SCC *C : SCCs) {
1224e5944d97SChandler Carruth     for (Node &N : *C)
1225e5944d97SChandler Carruth       N.DFSNumber = N.LowLink = 0;
1226e5944d97SChandler Carruth 
1227e5944d97SChandler Carruth     Worklist.append(C->Nodes.begin(), C->Nodes.end());
12289302fbf0SChandler Carruth   }
12299302fbf0SChandler Carruth 
12309c3deaa6SChandler Carruth   // Track the number of nodes in this RefSCC so that we can quickly recognize
12319c3deaa6SChandler Carruth   // an important special case of the edge removal not breaking the cycle of
12329c3deaa6SChandler Carruth   // this RefSCC.
12339c3deaa6SChandler Carruth   const int NumRefSCCNodes = Worklist.size();
12349c3deaa6SChandler Carruth 
1235aaad9f84SChandler Carruth   SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
1236e5944d97SChandler Carruth   SmallVector<Node *, 4> PendingRefSCCStack;
1237e5944d97SChandler Carruth   do {
1238e5944d97SChandler Carruth     assert(DFSStack.empty() &&
1239e5944d97SChandler Carruth            "Cannot begin a new root with a non-empty DFS stack!");
1240e5944d97SChandler Carruth     assert(PendingRefSCCStack.empty() &&
1241e5944d97SChandler Carruth            "Cannot begin a new root with pending nodes for an SCC!");
1242aca48d04SChandler Carruth 
1243e5944d97SChandler Carruth     Node *RootN = Worklist.pop_back_val();
1244e5944d97SChandler Carruth     // Skip any nodes we've already reached in the DFS.
1245e5944d97SChandler Carruth     if (RootN->DFSNumber != 0) {
1246e5944d97SChandler Carruth       assert(RootN->DFSNumber == -1 &&
1247e5944d97SChandler Carruth              "Shouldn't have any mid-DFS root nodes!");
1248aca48d04SChandler Carruth       continue;
1249aca48d04SChandler Carruth     }
1250aca48d04SChandler Carruth 
1251e5944d97SChandler Carruth     RootN->DFSNumber = RootN->LowLink = 1;
1252e5944d97SChandler Carruth     int NextDFSNumber = 2;
1253e5944d97SChandler Carruth 
1254aaad9f84SChandler Carruth     DFSStack.push_back({RootN, (*RootN)->begin()});
1255e5944d97SChandler Carruth     do {
1256e5944d97SChandler Carruth       Node *N;
1257aaad9f84SChandler Carruth       EdgeSequence::iterator I;
1258e5944d97SChandler Carruth       std::tie(N, I) = DFSStack.pop_back_val();
1259aaad9f84SChandler Carruth       auto E = (*N)->end();
1260e5944d97SChandler Carruth 
1261e5944d97SChandler Carruth       assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1262e5944d97SChandler Carruth                                   "before processing a node.");
1263e5944d97SChandler Carruth 
1264e5944d97SChandler Carruth       while (I != E) {
1265aaad9f84SChandler Carruth         Node &ChildN = I->getNode();
1266aca48d04SChandler Carruth         if (ChildN.DFSNumber == 0) {
1267aca48d04SChandler Carruth           // Mark that we should start at this child when next this node is the
1268aca48d04SChandler Carruth           // top of the stack. We don't start at the next child to ensure this
1269aca48d04SChandler Carruth           // child's lowlink is reflected.
1270e5944d97SChandler Carruth           DFSStack.push_back({N, I});
1271aca48d04SChandler Carruth 
1272aca48d04SChandler Carruth           // Continue, resetting to the child node.
1273aca48d04SChandler Carruth           ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1274aca48d04SChandler Carruth           N = &ChildN;
1275aaad9f84SChandler Carruth           I = ChildN->begin();
1276aaad9f84SChandler Carruth           E = ChildN->end();
1277aca48d04SChandler Carruth           continue;
1278aca48d04SChandler Carruth         }
1279e5944d97SChandler Carruth         if (ChildN.DFSNumber == -1) {
1280e5944d97SChandler Carruth           // If this child isn't currently in this RefSCC, no need to process
1281adbf14abSChandler Carruth           // it.
1282e5944d97SChandler Carruth           ++I;
1283e5944d97SChandler Carruth           continue;
1284e5944d97SChandler Carruth         }
1285aca48d04SChandler Carruth 
1286beaca19cSAlp Toker         // Track the lowest link of the children, if any are still in the stack.
1287aca48d04SChandler Carruth         // Any child not on the stack will have a LowLink of -1.
1288aca48d04SChandler Carruth         assert(ChildN.LowLink != 0 &&
1289aca48d04SChandler Carruth                "Low-link must not be zero with a non-zero DFS number.");
1290aca48d04SChandler Carruth         if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1291aca48d04SChandler Carruth           N->LowLink = ChildN.LowLink;
1292aca48d04SChandler Carruth         ++I;
1293aca48d04SChandler Carruth       }
1294aca48d04SChandler Carruth 
12951a8456daSVedant Kumar       // We've finished processing N and its descendants, put it on our pending
1296e5944d97SChandler Carruth       // stack to eventually get merged into a RefSCC.
1297e5944d97SChandler Carruth       PendingRefSCCStack.push_back(N);
1298aca48d04SChandler Carruth 
1299e5944d97SChandler Carruth       // If this node is linked to some lower entry, continue walking up the
1300e5944d97SChandler Carruth       // stack.
1301e5944d97SChandler Carruth       if (N->LowLink != N->DFSNumber) {
1302e5944d97SChandler Carruth         assert(!DFSStack.empty() &&
1303e5944d97SChandler Carruth                "We never found a viable root for a RefSCC to pop off!");
1304e5944d97SChandler Carruth         continue;
1305aca48d04SChandler Carruth       }
1306aca48d04SChandler Carruth 
1307e5944d97SChandler Carruth       // Otherwise, form a new RefSCC from the top of the pending node stack.
13082cd28b2bSChandler Carruth       int RefSCCNumber = PostOrderNumber++;
1309e5944d97SChandler Carruth       int RootDFSNumber = N->DFSNumber;
13102cd28b2bSChandler Carruth 
1311e5944d97SChandler Carruth       // Find the range of the node stack by walking down until we pass the
13122cd28b2bSChandler Carruth       // root DFS number. Update the DFS numbers and low link numbers in the
13132cd28b2bSChandler Carruth       // process to avoid re-walking this list where possible.
13142cd28b2bSChandler Carruth       auto StackRI = find_if(reverse(PendingRefSCCStack), [&](Node *N) {
13152cd28b2bSChandler Carruth         if (N->DFSNumber < RootDFSNumber)
13162cd28b2bSChandler Carruth           // We've found the bottom.
13172cd28b2bSChandler Carruth           return true;
13182cd28b2bSChandler Carruth 
13192cd28b2bSChandler Carruth         // Update this node and keep scanning.
13202cd28b2bSChandler Carruth         N->DFSNumber = -1;
13212cd28b2bSChandler Carruth         // Save the post-order number in the lowlink field so that we can use
13222cd28b2bSChandler Carruth         // it to map SCCs into new RefSCCs after we finish the DFS.
13232cd28b2bSChandler Carruth         N->LowLink = RefSCCNumber;
13242cd28b2bSChandler Carruth         return false;
13252cd28b2bSChandler Carruth       });
13262cd28b2bSChandler Carruth       auto RefSCCNodes = make_range(StackRI.base(), PendingRefSCCStack.end());
13279c3deaa6SChandler Carruth 
13289c3deaa6SChandler Carruth       // If we find a cycle containing all nodes originally in this RefSCC then
13299c3deaa6SChandler Carruth       // the removal hasn't changed the structure at all. This is an important
13309c3deaa6SChandler Carruth       // special case and we can directly exit the entire routine more
13319c3deaa6SChandler Carruth       // efficiently as soon as we discover it.
13325a0872c2SVedant Kumar       if (llvm::size(RefSCCNodes) == NumRefSCCNodes) {
13332cd28b2bSChandler Carruth         // Clear out the low link field as we won't need it.
13349c3deaa6SChandler Carruth         for (Node *N : RefSCCNodes)
13352cd28b2bSChandler Carruth           N->LowLink = -1;
13369c3deaa6SChandler Carruth         // Return the empty result immediately.
13379c3deaa6SChandler Carruth         return Result;
13389c3deaa6SChandler Carruth       }
1339aca48d04SChandler Carruth 
13402cd28b2bSChandler Carruth       // We've already marked the nodes internally with the RefSCC number so
13412cd28b2bSChandler Carruth       // just clear them off the stack and continue.
13429c3deaa6SChandler Carruth       PendingRefSCCStack.erase(RefSCCNodes.begin(), PendingRefSCCStack.end());
1343e5944d97SChandler Carruth     } while (!DFSStack.empty());
13449302fbf0SChandler Carruth 
1345aca48d04SChandler Carruth     assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
1346e5944d97SChandler Carruth     assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
1347aca48d04SChandler Carruth   } while (!Worklist.empty());
13489302fbf0SChandler Carruth 
13499c3deaa6SChandler Carruth   assert(PostOrderNumber > 1 &&
13509c3deaa6SChandler Carruth          "Should never finish the DFS when the existing RefSCC remains valid!");
135123c2f44cSChandler Carruth 
135223c2f44cSChandler Carruth   // Otherwise we create a collection of new RefSCC nodes and build
135323c2f44cSChandler Carruth   // a radix-sort style map from postorder number to these new RefSCCs. We then
135421e545d0SMalcolm Parsons   // append SCCs to each of these RefSCCs in the order they occurred in the
135523c2f44cSChandler Carruth   // original SCCs container.
135623c2f44cSChandler Carruth   for (int i = 0; i < PostOrderNumber; ++i)
1357e5944d97SChandler Carruth     Result.push_back(G->createRefSCC(*G));
1358e5944d97SChandler Carruth 
135949d728adSChandler Carruth   // Insert the resulting postorder sequence into the global graph postorder
136023c2f44cSChandler Carruth   // sequence before the current RefSCC in that sequence, and then remove the
136123c2f44cSChandler Carruth   // current one.
136249d728adSChandler Carruth   //
136349d728adSChandler Carruth   // FIXME: It'd be nice to change the APIs so that we returned an iterator
136449d728adSChandler Carruth   // range over the global postorder sequence and generally use that sequence
136549d728adSChandler Carruth   // rather than building a separate result vector here.
136649d728adSChandler Carruth   int Idx = G->getRefSCCIndex(*this);
136723c2f44cSChandler Carruth   G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
136823c2f44cSChandler Carruth   G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.begin(),
136923c2f44cSChandler Carruth                              Result.end());
137049d728adSChandler Carruth   for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
137149d728adSChandler Carruth     G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
137249d728adSChandler Carruth 
1373e5944d97SChandler Carruth   for (SCC *C : SCCs) {
13742cd28b2bSChandler Carruth     // We store the SCC number in the node's low-link field above.
13752cd28b2bSChandler Carruth     int SCCNumber = C->begin()->LowLink;
13762cd28b2bSChandler Carruth     // Clear out all of the SCC's node's low-link fields now that we're done
13772cd28b2bSChandler Carruth     // using them as side-storage.
13782cd28b2bSChandler Carruth     for (Node &N : *C) {
13792cd28b2bSChandler Carruth       assert(N.LowLink == SCCNumber &&
1380e5944d97SChandler Carruth              "Cannot have different numbers for nodes in the same SCC!");
13812cd28b2bSChandler Carruth       N.LowLink = -1;
13822cd28b2bSChandler Carruth     }
1383e5944d97SChandler Carruth 
138423c2f44cSChandler Carruth     RefSCC &RC = *Result[SCCNumber];
1385e5944d97SChandler Carruth     int SCCIndex = RC.SCCs.size();
1386e5944d97SChandler Carruth     RC.SCCs.push_back(C);
138723a6c3f7SChandler Carruth     RC.SCCIndices[C] = SCCIndex;
1388e5944d97SChandler Carruth     C->OuterRefSCC = &RC;
1389e5944d97SChandler Carruth   }
1390e5944d97SChandler Carruth 
139123c2f44cSChandler Carruth   // Now that we've moved things into the new RefSCCs, clear out our current
139223c2f44cSChandler Carruth   // one.
139323c2f44cSChandler Carruth   G = nullptr;
139423c2f44cSChandler Carruth   SCCs.clear();
139588823468SChandler Carruth   SCCIndices.clear();
139623a6c3f7SChandler Carruth 
1397468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
13989c161e89SChandler Carruth   // Verify the new RefSCCs we've built.
13999c161e89SChandler Carruth   for (RefSCC *RC : Result)
14009c161e89SChandler Carruth     RC->verify();
14019c161e89SChandler Carruth #endif
14029c161e89SChandler Carruth 
14039302fbf0SChandler Carruth   // Return the new list of SCCs.
1404e5944d97SChandler Carruth   return Result;
14059302fbf0SChandler Carruth }
14069302fbf0SChandler Carruth 
insertTrivialCallEdge(Node & SourceN,Node & TargetN)14075dbc164dSChandler Carruth void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
14085dbc164dSChandler Carruth                                                   Node &TargetN) {
1409468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
14105dbc164dSChandler Carruth   auto ExitVerifier = make_scope_exit([this] { verify(); });
1411bae595b7SChandler Carruth 
14122e0fe3e6SChandler Carruth   // Check that we aren't breaking some invariants of the SCC graph. Note that
14132e0fe3e6SChandler Carruth   // this is quadratic in the number of edges in the call graph!
1414bae595b7SChandler Carruth   SCC &SourceC = *G->lookupSCC(SourceN);
1415bae595b7SChandler Carruth   SCC &TargetC = *G->lookupSCC(TargetN);
1416bae595b7SChandler Carruth   if (&SourceC != &TargetC)
1417bae595b7SChandler Carruth     assert(SourceC.isAncestorOf(TargetC) &&
1418bae595b7SChandler Carruth            "Call edge is not trivial in the SCC graph!");
1419468fa037SArthur Eubanks #endif
14202e0fe3e6SChandler Carruth 
14215dbc164dSChandler Carruth   // First insert it into the source or find the existing edge.
1422aaad9f84SChandler Carruth   auto InsertResult =
1423aaad9f84SChandler Carruth       SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
14245dbc164dSChandler Carruth   if (!InsertResult.second) {
14255dbc164dSChandler Carruth     // Already an edge, just update it.
1426aaad9f84SChandler Carruth     Edge &E = SourceN->Edges[InsertResult.first->second];
14275dbc164dSChandler Carruth     if (E.isCall())
14285dbc164dSChandler Carruth       return; // Nothing to do!
14295dbc164dSChandler Carruth     E.setKind(Edge::Call);
14305dbc164dSChandler Carruth   } else {
14315dbc164dSChandler Carruth     // Create the new edge.
1432aaad9f84SChandler Carruth     SourceN->Edges.emplace_back(TargetN, Edge::Call);
14335dbc164dSChandler Carruth   }
14345dbc164dSChandler Carruth }
14355dbc164dSChandler Carruth 
insertTrivialRefEdge(Node & SourceN,Node & TargetN)14365dbc164dSChandler Carruth void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1437468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
14385dbc164dSChandler Carruth   auto ExitVerifier = make_scope_exit([this] { verify(); });
14399eb857cbSChandler Carruth 
14409eb857cbSChandler Carruth   // Check that we aren't breaking some invariants of the RefSCC graph.
14419eb857cbSChandler Carruth   RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
14429eb857cbSChandler Carruth   RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
14439eb857cbSChandler Carruth   if (&SourceRC != &TargetRC)
14449eb857cbSChandler Carruth     assert(SourceRC.isAncestorOf(TargetRC) &&
14459eb857cbSChandler Carruth            "Ref edge is not trivial in the RefSCC graph!");
1446468fa037SArthur Eubanks #endif
14472e0fe3e6SChandler Carruth 
14485dbc164dSChandler Carruth   // First insert it into the source or find the existing edge.
1449aaad9f84SChandler Carruth   auto InsertResult =
1450aaad9f84SChandler Carruth       SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
14515dbc164dSChandler Carruth   if (!InsertResult.second)
14525dbc164dSChandler Carruth     // Already an edge, we're done.
14535dbc164dSChandler Carruth     return;
14545dbc164dSChandler Carruth 
14555dbc164dSChandler Carruth   // Create the new edge.
1456aaad9f84SChandler Carruth   SourceN->Edges.emplace_back(TargetN, Edge::Ref);
14575dbc164dSChandler Carruth }
14585dbc164dSChandler Carruth 
replaceNodeFunction(Node & N,Function & NewF)1459aaad9f84SChandler Carruth void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1460aaad9f84SChandler Carruth   Function &OldF = N.getFunction();
1461c00a7ff4SChandler Carruth 
1462468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
1463aaad9f84SChandler Carruth   auto ExitVerifier = make_scope_exit([this] { verify(); });
1464aaad9f84SChandler Carruth 
1465aaad9f84SChandler Carruth   assert(G->lookupRefSCC(N) == this &&
1466aaad9f84SChandler Carruth          "Cannot replace the function of a node outside this RefSCC.");
1467aaad9f84SChandler Carruth 
1468aaad9f84SChandler Carruth   assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1469aaad9f84SChandler Carruth          "Must not have already walked the new function!'");
1470aaad9f84SChandler Carruth 
1471aaad9f84SChandler Carruth   // It is important that this replacement not introduce graph changes so we
1472aaad9f84SChandler Carruth   // insist that the caller has already removed every use of the original
1473aaad9f84SChandler Carruth   // function and that all uses of the new function correspond to existing
1474aaad9f84SChandler Carruth   // edges in the graph. The common and expected way to use this is when
1475aaad9f84SChandler Carruth   // replacing the function itself in the IR without changing the call graph
1476aaad9f84SChandler Carruth   // shape and just updating the analysis based on that.
1477aaad9f84SChandler Carruth   assert(&OldF != &NewF && "Cannot replace a function with itself!");
1478aaad9f84SChandler Carruth   assert(OldF.use_empty() &&
1479aaad9f84SChandler Carruth          "Must have moved all uses from the old function to the new!");
1480aaad9f84SChandler Carruth #endif
1481aaad9f84SChandler Carruth 
1482aaad9f84SChandler Carruth   N.replaceFunction(NewF);
1483aaad9f84SChandler Carruth 
1484aaad9f84SChandler Carruth   // Update various call graph maps.
1485aaad9f84SChandler Carruth   G->NodeMap.erase(&OldF);
1486aaad9f84SChandler Carruth   G->NodeMap[&NewF] = &N;
1487c00a7ff4SChandler Carruth }
1488c00a7ff4SChandler Carruth 
insertEdge(Node & SourceN,Node & TargetN,Edge::Kind EK)1489aaad9f84SChandler Carruth void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
14902e0fe3e6SChandler Carruth   assert(SCCMap.empty() &&
1491aa839b22SChandler Carruth          "This method cannot be called after SCCs have been formed!");
14929302fbf0SChandler Carruth 
1493aaad9f84SChandler Carruth   return SourceN->insertEdgeInternal(TargetN, EK);
1494aaad9f84SChandler Carruth }
1495aaad9f84SChandler Carruth 
removeEdge(Node & SourceN,Node & TargetN)1496aaad9f84SChandler Carruth void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1497aaad9f84SChandler Carruth   assert(SCCMap.empty() &&
1498aaad9f84SChandler Carruth          "This method cannot be called after SCCs have been formed!");
1499aaad9f84SChandler Carruth 
1500aaad9f84SChandler Carruth   bool Removed = SourceN->removeEdgeInternal(TargetN);
1501aaad9f84SChandler Carruth   (void)Removed;
1502aaad9f84SChandler Carruth   assert(Removed && "Target not in the edge set for this caller?");
15039302fbf0SChandler Carruth }
15049302fbf0SChandler Carruth 
removeDeadFunction(Function & F)15055dbc164dSChandler Carruth void LazyCallGraph::removeDeadFunction(Function &F) {
15065dbc164dSChandler Carruth   // FIXME: This is unnecessarily restrictive. We should be able to remove
15075dbc164dSChandler Carruth   // functions which recursively call themselves.
1508757e044dSArthur Eubanks   assert(F.hasZeroLiveUses() &&
15095dbc164dSChandler Carruth          "This routine should only be called on trivially dead functions!");
15105dbc164dSChandler Carruth 
151106a86301SChandler Carruth   // We shouldn't remove library functions as they are never really dead while
151206a86301SChandler Carruth   // the call graph is in use -- every function definition refers to them.
151306a86301SChandler Carruth   assert(!isLibFunction(F) &&
151406a86301SChandler Carruth          "Must not remove lib functions from the call graph!");
151506a86301SChandler Carruth 
15165dbc164dSChandler Carruth   auto NI = NodeMap.find(&F);
15175dbc164dSChandler Carruth   if (NI == NodeMap.end())
15185dbc164dSChandler Carruth     // Not in the graph at all!
15195dbc164dSChandler Carruth     return;
15205dbc164dSChandler Carruth 
15215dbc164dSChandler Carruth   Node &N = *NI->second;
15225dbc164dSChandler Carruth   NodeMap.erase(NI);
15235dbc164dSChandler Carruth 
1524aaad9f84SChandler Carruth   // Remove this from the entry edges if present.
1525aaad9f84SChandler Carruth   EntryEdges.removeEdgeInternal(N);
1526aaad9f84SChandler Carruth 
15275dbc164dSChandler Carruth   // Cannot remove a function which has yet to be visited in the DFS walk, so
15285dbc164dSChandler Carruth   // if we have a node at all then we must have an SCC and RefSCC.
15295dbc164dSChandler Carruth   auto CI = SCCMap.find(&N);
15305dbc164dSChandler Carruth   assert(CI != SCCMap.end() &&
15315dbc164dSChandler Carruth          "Tried to remove a node without an SCC after DFS walk started!");
15325dbc164dSChandler Carruth   SCC &C = *CI->second;
15335dbc164dSChandler Carruth   SCCMap.erase(CI);
15345dbc164dSChandler Carruth   RefSCC &RC = C.getOuterRefSCC();
15355dbc164dSChandler Carruth 
15365dbc164dSChandler Carruth   // This node must be the only member of its SCC as it has no callers, and
15375dbc164dSChandler Carruth   // that SCC must be the only member of a RefSCC as it has no references.
15385dbc164dSChandler Carruth   // Validate these properties first.
15395dbc164dSChandler Carruth   assert(C.size() == 1 && "Dead functions must be in a singular SCC");
15405dbc164dSChandler Carruth   assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
15411f8fcfeaSChandler Carruth 
15425dbc164dSChandler Carruth   // Finally clear out all the data structures from the node down through the
1543d51e3474SArthur Eubanks   // components. postorder_ref_scc_iterator will skip empty RefSCCs, so no need
1544d51e3474SArthur Eubanks   // to adjust LazyCallGraph data structures.
15455dbc164dSChandler Carruth   N.clear();
1546403d3c4bSChandler Carruth   N.G = nullptr;
1547c718b8e7SChandler Carruth   N.F = nullptr;
15485dbc164dSChandler Carruth   C.clear();
15495dbc164dSChandler Carruth   RC.clear();
1550403d3c4bSChandler Carruth   RC.G = nullptr;
15515dbc164dSChandler Carruth 
15525dbc164dSChandler Carruth   // Nothing to delete as all the objects are allocated in stable bump pointer
15535dbc164dSChandler Carruth   // allocators.
15545dbc164dSChandler Carruth }
15555dbc164dSChandler Carruth 
15567fea561eSArthur Eubanks // Gets the Edge::Kind from one function to another by looking at the function's
15577fea561eSArthur Eubanks // instructions. Asserts if there is no edge.
15587fea561eSArthur Eubanks // Useful for determining what type of edge should exist between functions when
15597fea561eSArthur Eubanks // the edge hasn't been created yet.
getEdgeKind(Function & OriginalFunction,Function & NewFunction)15607fea561eSArthur Eubanks static LazyCallGraph::Edge::Kind getEdgeKind(Function &OriginalFunction,
15617fea561eSArthur Eubanks                                              Function &NewFunction) {
15627fea561eSArthur Eubanks   // In release builds, assume that if there are no direct calls to the new
15637fea561eSArthur Eubanks   // function, then there is a ref edge. In debug builds, keep track of
15647fea561eSArthur Eubanks   // references to assert that there is actually a ref edge if there is no call
15657fea561eSArthur Eubanks   // edge.
15667fea561eSArthur Eubanks #ifndef NDEBUG
15677fea561eSArthur Eubanks   SmallVector<Constant *, 16> Worklist;
15687fea561eSArthur Eubanks   SmallPtrSet<Constant *, 16> Visited;
15697fea561eSArthur Eubanks #endif
15707fea561eSArthur Eubanks 
15717fea561eSArthur Eubanks   for (Instruction &I : instructions(OriginalFunction)) {
15727fea561eSArthur Eubanks     if (auto *CB = dyn_cast<CallBase>(&I)) {
15737fea561eSArthur Eubanks       if (Function *Callee = CB->getCalledFunction()) {
15747fea561eSArthur Eubanks         if (Callee == &NewFunction)
15757fea561eSArthur Eubanks           return LazyCallGraph::Edge::Kind::Call;
15767fea561eSArthur Eubanks       }
15777fea561eSArthur Eubanks     }
15787fea561eSArthur Eubanks #ifndef NDEBUG
15797fea561eSArthur Eubanks     for (Value *Op : I.operand_values()) {
15807fea561eSArthur Eubanks       if (Constant *C = dyn_cast<Constant>(Op)) {
15817fea561eSArthur Eubanks         if (Visited.insert(C).second)
15827fea561eSArthur Eubanks           Worklist.push_back(C);
15837fea561eSArthur Eubanks       }
15847fea561eSArthur Eubanks     }
15857fea561eSArthur Eubanks #endif
15867fea561eSArthur Eubanks   }
15877fea561eSArthur Eubanks 
15887fea561eSArthur Eubanks #ifndef NDEBUG
15897fea561eSArthur Eubanks   bool FoundNewFunction = false;
15907fea561eSArthur Eubanks   LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &F) {
15917fea561eSArthur Eubanks     if (&F == &NewFunction)
15927fea561eSArthur Eubanks       FoundNewFunction = true;
15937fea561eSArthur Eubanks   });
15947fea561eSArthur Eubanks   assert(FoundNewFunction && "No edge from original function to new function");
15957fea561eSArthur Eubanks #endif
15967fea561eSArthur Eubanks 
15977fea561eSArthur Eubanks   return LazyCallGraph::Edge::Kind::Ref;
15987fea561eSArthur Eubanks }
15997fea561eSArthur Eubanks 
addSplitFunction(Function & OriginalFunction,Function & NewFunction)16007fea561eSArthur Eubanks void LazyCallGraph::addSplitFunction(Function &OriginalFunction,
16017fea561eSArthur Eubanks                                      Function &NewFunction) {
16027fea561eSArthur Eubanks   assert(lookup(OriginalFunction) &&
16037fea561eSArthur Eubanks          "Original function's node should already exist");
16047fea561eSArthur Eubanks   Node &OriginalN = get(OriginalFunction);
16057fea561eSArthur Eubanks   SCC *OriginalC = lookupSCC(OriginalN);
16067fea561eSArthur Eubanks   RefSCC *OriginalRC = lookupRefSCC(OriginalN);
16077fea561eSArthur Eubanks 
1608468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
16097fea561eSArthur Eubanks   OriginalRC->verify();
16107fea561eSArthur Eubanks   auto VerifyOnExit = make_scope_exit([&]() { OriginalRC->verify(); });
16117fea561eSArthur Eubanks #endif
16127fea561eSArthur Eubanks 
16137fea561eSArthur Eubanks   assert(!lookup(NewFunction) &&
16147fea561eSArthur Eubanks          "New function's node should not already exist");
16157fea561eSArthur Eubanks   Node &NewN = initNode(NewFunction);
16167fea561eSArthur Eubanks 
16177fea561eSArthur Eubanks   Edge::Kind EK = getEdgeKind(OriginalFunction, NewFunction);
16187fea561eSArthur Eubanks 
16197fea561eSArthur Eubanks   SCC *NewC = nullptr;
16207fea561eSArthur Eubanks   for (Edge &E : *NewN) {
16217fea561eSArthur Eubanks     Node &EN = E.getNode();
16227fea561eSArthur Eubanks     if (EK == Edge::Kind::Call && E.isCall() && lookupSCC(EN) == OriginalC) {
16237fea561eSArthur Eubanks       // If the edge to the new function is a call edge and there is a call edge
16247fea561eSArthur Eubanks       // from the new function to any function in the original function's SCC,
16257fea561eSArthur Eubanks       // it is in the same SCC (and RefSCC) as the original function.
16267fea561eSArthur Eubanks       NewC = OriginalC;
16277fea561eSArthur Eubanks       NewC->Nodes.push_back(&NewN);
16287fea561eSArthur Eubanks       break;
16297fea561eSArthur Eubanks     }
16307fea561eSArthur Eubanks   }
16317fea561eSArthur Eubanks 
16327fea561eSArthur Eubanks   if (!NewC) {
16337fea561eSArthur Eubanks     for (Edge &E : *NewN) {
16347fea561eSArthur Eubanks       Node &EN = E.getNode();
16357fea561eSArthur Eubanks       if (lookupRefSCC(EN) == OriginalRC) {
16367fea561eSArthur Eubanks         // If there is any edge from the new function to any function in the
16377fea561eSArthur Eubanks         // original function's RefSCC, it is in the same RefSCC as the original
16387fea561eSArthur Eubanks         // function but a new SCC.
16397fea561eSArthur Eubanks         RefSCC *NewRC = OriginalRC;
16407fea561eSArthur Eubanks         NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
16417fea561eSArthur Eubanks 
16427fea561eSArthur Eubanks         // The new function's SCC is not the same as the original function's
16437fea561eSArthur Eubanks         // SCC, since that case was handled earlier. If the edge from the
16447fea561eSArthur Eubanks         // original function to the new function was a call edge, then we need
16457fea561eSArthur Eubanks         // to insert the newly created function's SCC before the original
16467fea561eSArthur Eubanks         // function's SCC. Otherwise either the new SCC comes after the original
16477fea561eSArthur Eubanks         // function's SCC, or it doesn't matter, and in both cases we can add it
16487fea561eSArthur Eubanks         // to the very end.
16497fea561eSArthur Eubanks         int InsertIndex = EK == Edge::Kind::Call ? NewRC->SCCIndices[OriginalC]
16507fea561eSArthur Eubanks                                                  : NewRC->SCCIndices.size();
16517fea561eSArthur Eubanks         NewRC->SCCs.insert(NewRC->SCCs.begin() + InsertIndex, NewC);
16527fea561eSArthur Eubanks         for (int I = InsertIndex, Size = NewRC->SCCs.size(); I < Size; ++I)
16537fea561eSArthur Eubanks           NewRC->SCCIndices[NewRC->SCCs[I]] = I;
16547fea561eSArthur Eubanks 
16557fea561eSArthur Eubanks         break;
16567fea561eSArthur Eubanks       }
16577fea561eSArthur Eubanks     }
16587fea561eSArthur Eubanks   }
16597fea561eSArthur Eubanks 
16607fea561eSArthur Eubanks   if (!NewC) {
16617fea561eSArthur Eubanks     // We didn't find any edges back to the original function's RefSCC, so the
16627fea561eSArthur Eubanks     // new function belongs in a new RefSCC. The new RefSCC goes before the
16637fea561eSArthur Eubanks     // original function's RefSCC.
16647fea561eSArthur Eubanks     RefSCC *NewRC = createRefSCC(*this);
16657fea561eSArthur Eubanks     NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
16667fea561eSArthur Eubanks     NewRC->SCCIndices[NewC] = 0;
16677fea561eSArthur Eubanks     NewRC->SCCs.push_back(NewC);
16687fea561eSArthur Eubanks     auto OriginalRCIndex = RefSCCIndices.find(OriginalRC)->second;
16697fea561eSArthur Eubanks     PostOrderRefSCCs.insert(PostOrderRefSCCs.begin() + OriginalRCIndex, NewRC);
16707fea561eSArthur Eubanks     for (int I = OriginalRCIndex, Size = PostOrderRefSCCs.size(); I < Size; ++I)
16717fea561eSArthur Eubanks       RefSCCIndices[PostOrderRefSCCs[I]] = I;
16727fea561eSArthur Eubanks   }
16737fea561eSArthur Eubanks 
16747fea561eSArthur Eubanks   SCCMap[&NewN] = NewC;
16757fea561eSArthur Eubanks 
16767fea561eSArthur Eubanks   OriginalN->insertEdgeInternal(NewN, EK);
16777fea561eSArthur Eubanks }
16787fea561eSArthur Eubanks 
addSplitRefRecursiveFunctions(Function & OriginalFunction,ArrayRef<Function * > NewFunctions)16797fea561eSArthur Eubanks void LazyCallGraph::addSplitRefRecursiveFunctions(
16807fea561eSArthur Eubanks     Function &OriginalFunction, ArrayRef<Function *> NewFunctions) {
16817fea561eSArthur Eubanks   assert(!NewFunctions.empty() && "Can't add zero functions");
16827fea561eSArthur Eubanks   assert(lookup(OriginalFunction) &&
16837fea561eSArthur Eubanks          "Original function's node should already exist");
16847fea561eSArthur Eubanks   Node &OriginalN = get(OriginalFunction);
16857fea561eSArthur Eubanks   RefSCC *OriginalRC = lookupRefSCC(OriginalN);
16867fea561eSArthur Eubanks 
1687468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
16887fea561eSArthur Eubanks   OriginalRC->verify();
16897fea561eSArthur Eubanks   auto VerifyOnExit = make_scope_exit([&]() {
16907fea561eSArthur Eubanks     OriginalRC->verify();
16917fea561eSArthur Eubanks     for (Function *NewFunction : NewFunctions)
16927fea561eSArthur Eubanks       lookupRefSCC(get(*NewFunction))->verify();
16937fea561eSArthur Eubanks   });
16947fea561eSArthur Eubanks #endif
16957fea561eSArthur Eubanks 
16967fea561eSArthur Eubanks   bool ExistsRefToOriginalRefSCC = false;
16977fea561eSArthur Eubanks 
16987fea561eSArthur Eubanks   for (Function *NewFunction : NewFunctions) {
16997fea561eSArthur Eubanks     Node &NewN = initNode(*NewFunction);
17007fea561eSArthur Eubanks 
17017fea561eSArthur Eubanks     OriginalN->insertEdgeInternal(NewN, Edge::Kind::Ref);
17027fea561eSArthur Eubanks 
17037fea561eSArthur Eubanks     // Check if there is any edge from any new function back to any function in
17047fea561eSArthur Eubanks     // the original function's RefSCC.
17057fea561eSArthur Eubanks     for (Edge &E : *NewN) {
17067fea561eSArthur Eubanks       if (lookupRefSCC(E.getNode()) == OriginalRC) {
17077fea561eSArthur Eubanks         ExistsRefToOriginalRefSCC = true;
17087fea561eSArthur Eubanks         break;
17097fea561eSArthur Eubanks       }
17107fea561eSArthur Eubanks     }
17117fea561eSArthur Eubanks   }
17127fea561eSArthur Eubanks 
17137fea561eSArthur Eubanks   RefSCC *NewRC;
17147fea561eSArthur Eubanks   if (ExistsRefToOriginalRefSCC) {
17157fea561eSArthur Eubanks     // If there is any edge from any new function to any function in the
17167fea561eSArthur Eubanks     // original function's RefSCC, all new functions will be in the same RefSCC
17177fea561eSArthur Eubanks     // as the original function.
17187fea561eSArthur Eubanks     NewRC = OriginalRC;
17197fea561eSArthur Eubanks   } else {
17207fea561eSArthur Eubanks     // Otherwise the new functions are in their own RefSCC.
17217fea561eSArthur Eubanks     NewRC = createRefSCC(*this);
17227fea561eSArthur Eubanks     // The new RefSCC goes before the original function's RefSCC in postorder
17237fea561eSArthur Eubanks     // since there are only edges from the original function's RefSCC to the new
17247fea561eSArthur Eubanks     // RefSCC.
17257fea561eSArthur Eubanks     auto OriginalRCIndex = RefSCCIndices.find(OriginalRC)->second;
17267fea561eSArthur Eubanks     PostOrderRefSCCs.insert(PostOrderRefSCCs.begin() + OriginalRCIndex, NewRC);
17277fea561eSArthur Eubanks     for (int I = OriginalRCIndex, Size = PostOrderRefSCCs.size(); I < Size; ++I)
17287fea561eSArthur Eubanks       RefSCCIndices[PostOrderRefSCCs[I]] = I;
17297fea561eSArthur Eubanks   }
17307fea561eSArthur Eubanks 
17317fea561eSArthur Eubanks   for (Function *NewFunction : NewFunctions) {
17327fea561eSArthur Eubanks     Node &NewN = get(*NewFunction);
17337fea561eSArthur Eubanks     // Each new function is in its own new SCC. The original function can only
17347fea561eSArthur Eubanks     // have a ref edge to new functions, and no other existing functions can
17357fea561eSArthur Eubanks     // have references to new functions. Each new function only has a ref edge
17367fea561eSArthur Eubanks     // to the other new functions.
17377fea561eSArthur Eubanks     SCC *NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
17387fea561eSArthur Eubanks     // The new SCCs are either sibling SCCs or parent SCCs to all other existing
17397fea561eSArthur Eubanks     // SCCs in the RefSCC. Either way, they can go at the back of the postorder
17407fea561eSArthur Eubanks     // SCC list.
17417fea561eSArthur Eubanks     auto Index = NewRC->SCCIndices.size();
17427fea561eSArthur Eubanks     NewRC->SCCIndices[NewC] = Index;
17437fea561eSArthur Eubanks     NewRC->SCCs.push_back(NewC);
17447fea561eSArthur Eubanks     SCCMap[&NewN] = NewC;
17457fea561eSArthur Eubanks   }
17467fea561eSArthur Eubanks 
17477fea561eSArthur Eubanks #ifndef NDEBUG
17487fea561eSArthur Eubanks   for (Function *F1 : NewFunctions) {
17497fea561eSArthur Eubanks     assert(getEdgeKind(OriginalFunction, *F1) == Edge::Kind::Ref &&
17507fea561eSArthur Eubanks            "Expected ref edges from original function to every new function");
17517fea561eSArthur Eubanks     Node &N1 = get(*F1);
17527fea561eSArthur Eubanks     for (Function *F2 : NewFunctions) {
17537fea561eSArthur Eubanks       if (F1 == F2)
17547fea561eSArthur Eubanks         continue;
17557fea561eSArthur Eubanks       Node &N2 = get(*F2);
17567fea561eSArthur Eubanks       assert(!N1->lookup(N2)->isCall() &&
17577fea561eSArthur Eubanks              "Edges between new functions must be ref edges");
17587fea561eSArthur Eubanks     }
17597fea561eSArthur Eubanks   }
176054c01057SArthur Eubanks #endif
17617fea561eSArthur Eubanks }
17627fea561eSArthur Eubanks 
insertInto(Function & F,Node * & MappedN)17632a898e0dSChandler Carruth LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
17642a898e0dSChandler Carruth   return *new (MappedN = BPA.Allocate()) Node(*this, F);
1765d8d865e2SChandler Carruth }
1766d8d865e2SChandler Carruth 
updateGraphPtrs()1767d8d865e2SChandler Carruth void LazyCallGraph::updateGraphPtrs() {
17687cb23e70SChandler Carruth   // Walk the node map to update their graph pointers. While this iterates in
17697cb23e70SChandler Carruth   // an unstable order, the order has no effect so it remains correct.
17707cb23e70SChandler Carruth   for (auto &FunctionNodePair : NodeMap)
17717cb23e70SChandler Carruth     FunctionNodePair.second->G = this;
1772bf71a34eSChandler Carruth 
17732c58e1a4SChandler Carruth   for (auto *RC : PostOrderRefSCCs)
17742c58e1a4SChandler Carruth     RC->G = this;
1775aa839b22SChandler Carruth }
1776aa839b22SChandler Carruth 
initNode(Function & F)17777fea561eSArthur Eubanks LazyCallGraph::Node &LazyCallGraph::initNode(Function &F) {
17787fea561eSArthur Eubanks   Node &N = get(F);
17790deef2e1SBrian Gesiak   N.DFSNumber = N.LowLink = -1;
17800deef2e1SBrian Gesiak   N.populate();
17817fea561eSArthur Eubanks   NodeMap[&F] = &N;
17826b1ce83aSArthur Eubanks   return N;
17830deef2e1SBrian Gesiak }
17840deef2e1SBrian Gesiak 
17852e0fe3e6SChandler Carruth template <typename RootsT, typename GetBeginT, typename GetEndT,
17862e0fe3e6SChandler Carruth           typename GetNodeT, typename FormSCCCallbackT>
buildGenericSCCs(RootsT && Roots,GetBeginT && GetBegin,GetEndT && GetEnd,GetNodeT && GetNode,FormSCCCallbackT && FormSCC)17872e0fe3e6SChandler Carruth void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
17882e0fe3e6SChandler Carruth                                      GetEndT &&GetEnd, GetNodeT &&GetNode,
17892e0fe3e6SChandler Carruth                                      FormSCCCallbackT &&FormSCC) {
1790530851c2SEugene Zelenko   using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
17913f9869a8SChandler Carruth 
17922e0fe3e6SChandler Carruth   SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
1793e5944d97SChandler Carruth   SmallVector<Node *, 16> PendingSCCStack;
1794e5944d97SChandler Carruth 
1795e5944d97SChandler Carruth   // Scan down the stack and DFS across the call edges.
17962e0fe3e6SChandler Carruth   for (Node *RootN : Roots) {
1797e5944d97SChandler Carruth     assert(DFSStack.empty() &&
1798e5944d97SChandler Carruth            "Cannot begin a new root with a non-empty DFS stack!");
1799e5944d97SChandler Carruth     assert(PendingSCCStack.empty() &&
1800e5944d97SChandler Carruth            "Cannot begin a new root with pending nodes for an SCC!");
1801e5944d97SChandler Carruth 
1802e5944d97SChandler Carruth     // Skip any nodes we've already reached in the DFS.
1803e5944d97SChandler Carruth     if (RootN->DFSNumber != 0) {
1804e5944d97SChandler Carruth       assert(RootN->DFSNumber == -1 &&
1805e5944d97SChandler Carruth              "Shouldn't have any mid-DFS root nodes!");
1806034d0d68SChandler Carruth       continue;
1807e5944d97SChandler Carruth     }
1808e5944d97SChandler Carruth 
1809e5944d97SChandler Carruth     RootN->DFSNumber = RootN->LowLink = 1;
1810e5944d97SChandler Carruth     int NextDFSNumber = 2;
1811e5944d97SChandler Carruth 
18122e0fe3e6SChandler Carruth     DFSStack.push_back({RootN, GetBegin(*RootN)});
1813e5944d97SChandler Carruth     do {
1814e5944d97SChandler Carruth       Node *N;
18152e0fe3e6SChandler Carruth       EdgeItT I;
1816e5944d97SChandler Carruth       std::tie(N, I) = DFSStack.pop_back_val();
18172e0fe3e6SChandler Carruth       auto E = GetEnd(*N);
1818e5944d97SChandler Carruth       while (I != E) {
18192e0fe3e6SChandler Carruth         Node &ChildN = GetNode(I);
1820e5944d97SChandler Carruth         if (ChildN.DFSNumber == 0) {
1821e5944d97SChandler Carruth           // We haven't yet visited this child, so descend, pushing the current
1822e5944d97SChandler Carruth           // node onto the stack.
1823e5944d97SChandler Carruth           DFSStack.push_back({N, I});
1824e5944d97SChandler Carruth 
1825e5944d97SChandler Carruth           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1826e5944d97SChandler Carruth           N = &ChildN;
18272e0fe3e6SChandler Carruth           I = GetBegin(*N);
18282e0fe3e6SChandler Carruth           E = GetEnd(*N);
1829e5944d97SChandler Carruth           continue;
1830e5944d97SChandler Carruth         }
1831e5944d97SChandler Carruth 
1832e5944d97SChandler Carruth         // If the child has already been added to some child component, it
1833e5944d97SChandler Carruth         // couldn't impact the low-link of this parent because it isn't
1834e5944d97SChandler Carruth         // connected, and thus its low-link isn't relevant so skip it.
1835e5944d97SChandler Carruth         if (ChildN.DFSNumber == -1) {
1836e5944d97SChandler Carruth           ++I;
1837e5944d97SChandler Carruth           continue;
1838e5944d97SChandler Carruth         }
1839e5944d97SChandler Carruth 
1840e5944d97SChandler Carruth         // Track the lowest linked child as the lowest link for this node.
1841e5944d97SChandler Carruth         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1842e5944d97SChandler Carruth         if (ChildN.LowLink < N->LowLink)
1843e5944d97SChandler Carruth           N->LowLink = ChildN.LowLink;
1844e5944d97SChandler Carruth 
1845e5944d97SChandler Carruth         // Move to the next edge.
1846e5944d97SChandler Carruth         ++I;
1847e5944d97SChandler Carruth       }
1848e5944d97SChandler Carruth 
18491a8456daSVedant Kumar       // We've finished processing N and its descendants, put it on our pending
1850e5944d97SChandler Carruth       // SCC stack to eventually get merged into an SCC of nodes.
1851e5944d97SChandler Carruth       PendingSCCStack.push_back(N);
1852e5944d97SChandler Carruth 
1853e5944d97SChandler Carruth       // If this node is linked to some lower entry, continue walking up the
1854e5944d97SChandler Carruth       // stack.
1855e5944d97SChandler Carruth       if (N->LowLink != N->DFSNumber)
1856e5944d97SChandler Carruth         continue;
1857e5944d97SChandler Carruth 
1858e5944d97SChandler Carruth       // Otherwise, we've completed an SCC. Append it to our post order list of
1859e5944d97SChandler Carruth       // SCCs.
1860e5944d97SChandler Carruth       int RootDFSNumber = N->DFSNumber;
1861e5944d97SChandler Carruth       // Find the range of the node stack by walking down until we pass the
1862e5944d97SChandler Carruth       // root DFS number.
1863e5944d97SChandler Carruth       auto SCCNodes = make_range(
1864e5944d97SChandler Carruth           PendingSCCStack.rbegin(),
186542531260SDavid Majnemer           find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1866e5944d97SChandler Carruth             return N->DFSNumber < RootDFSNumber;
1867e5944d97SChandler Carruth           }));
1868e5944d97SChandler Carruth       // Form a new SCC out of these nodes and then clear them off our pending
1869e5944d97SChandler Carruth       // stack.
18702e0fe3e6SChandler Carruth       FormSCC(SCCNodes);
18712e0fe3e6SChandler Carruth       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
18722e0fe3e6SChandler Carruth     } while (!DFSStack.empty());
18732e0fe3e6SChandler Carruth   }
18742e0fe3e6SChandler Carruth }
18752e0fe3e6SChandler Carruth 
18762e0fe3e6SChandler Carruth /// Build the internal SCCs for a RefSCC from a sequence of nodes.
18772e0fe3e6SChandler Carruth ///
18782e0fe3e6SChandler Carruth /// Appends the SCCs to the provided vector and updates the map with their
18792e0fe3e6SChandler Carruth /// indices. Both the vector and map must be empty when passed into this
18802e0fe3e6SChandler Carruth /// routine.
buildSCCs(RefSCC & RC,node_stack_range Nodes)18812e0fe3e6SChandler Carruth void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
18822e0fe3e6SChandler Carruth   assert(RC.SCCs.empty() && "Already built SCCs!");
18832e0fe3e6SChandler Carruth   assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
18842e0fe3e6SChandler Carruth 
18852e0fe3e6SChandler Carruth   for (Node *N : Nodes) {
18862e0fe3e6SChandler Carruth     assert(N->LowLink >= (*Nodes.begin())->LowLink &&
18872e0fe3e6SChandler Carruth            "We cannot have a low link in an SCC lower than its root on the "
18882e0fe3e6SChandler Carruth            "stack!");
18892e0fe3e6SChandler Carruth 
18902e0fe3e6SChandler Carruth     // This node will go into the next RefSCC, clear out its DFS and low link
18912e0fe3e6SChandler Carruth     // as we scan.
18922e0fe3e6SChandler Carruth     N->DFSNumber = N->LowLink = 0;
18932e0fe3e6SChandler Carruth   }
18942e0fe3e6SChandler Carruth 
18952e0fe3e6SChandler Carruth   // Each RefSCC contains a DAG of the call SCCs. To build these, we do
18962e0fe3e6SChandler Carruth   // a direct walk of the call edges using Tarjan's algorithm. We reuse the
18972e0fe3e6SChandler Carruth   // internal storage as we won't need it for the outer graph's DFS any longer.
1898aaad9f84SChandler Carruth   buildGenericSCCs(
1899aaad9f84SChandler Carruth       Nodes, [](Node &N) { return N->call_begin(); },
1900aaad9f84SChandler Carruth       [](Node &N) { return N->call_end(); },
1901aaad9f84SChandler Carruth       [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
19022e0fe3e6SChandler Carruth       [this, &RC](node_stack_range Nodes) {
19032e0fe3e6SChandler Carruth         RC.SCCs.push_back(createSCC(RC, Nodes));
1904e5944d97SChandler Carruth         for (Node &N : *RC.SCCs.back()) {
1905e5944d97SChandler Carruth           N.DFSNumber = N.LowLink = -1;
1906e5944d97SChandler Carruth           SCCMap[&N] = RC.SCCs.back();
1907e5944d97SChandler Carruth         }
19082e0fe3e6SChandler Carruth       });
1909e5944d97SChandler Carruth 
1910e5944d97SChandler Carruth   // Wire up the SCC indices.
1911e5944d97SChandler Carruth   for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1912e5944d97SChandler Carruth     RC.SCCIndices[RC.SCCs[i]] = i;
1913e5944d97SChandler Carruth }
1914e5944d97SChandler Carruth 
buildRefSCCs()19152e0fe3e6SChandler Carruth void LazyCallGraph::buildRefSCCs() {
19162e0fe3e6SChandler Carruth   if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
19172e0fe3e6SChandler Carruth     // RefSCCs are either non-existent or already built!
19182e0fe3e6SChandler Carruth     return;
19192e0fe3e6SChandler Carruth 
19202e0fe3e6SChandler Carruth   assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
19212e0fe3e6SChandler Carruth 
19222e0fe3e6SChandler Carruth   SmallVector<Node *, 16> Roots;
19232e0fe3e6SChandler Carruth   for (Edge &E : *this)
1924aaad9f84SChandler Carruth     Roots.push_back(&E.getNode());
19252e0fe3e6SChandler Carruth 
1926491dd271SFangrui Song   // The roots will be iterated in order.
19272e0fe3e6SChandler Carruth   buildGenericSCCs(
1928aaad9f84SChandler Carruth       Roots,
1929aaad9f84SChandler Carruth       [](Node &N) {
1930aaad9f84SChandler Carruth         // We need to populate each node as we begin to walk its edges.
1931aaad9f84SChandler Carruth         N.populate();
1932aaad9f84SChandler Carruth         return N->begin();
19332e0fe3e6SChandler Carruth       },
1934aaad9f84SChandler Carruth       [](Node &N) { return N->end(); },
1935aaad9f84SChandler Carruth       [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
19362e0fe3e6SChandler Carruth       [this](node_stack_range Nodes) {
19372e0fe3e6SChandler Carruth         RefSCC *NewRC = createRefSCC(*this);
19382e0fe3e6SChandler Carruth         buildSCCs(*NewRC, Nodes);
19392e0fe3e6SChandler Carruth 
19402e0fe3e6SChandler Carruth         // Push the new node into the postorder list and remember its position
19412e0fe3e6SChandler Carruth         // in the index map.
19422e0fe3e6SChandler Carruth         bool Inserted =
19432e0fe3e6SChandler Carruth             RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
19442e0fe3e6SChandler Carruth         (void)Inserted;
19452e0fe3e6SChandler Carruth         assert(Inserted && "Cannot already have this RefSCC in the index map!");
19462e0fe3e6SChandler Carruth         PostOrderRefSCCs.push_back(NewRC);
1947468fa037SArthur Eubanks #ifdef EXPENSIVE_CHECKS
19482e0fe3e6SChandler Carruth         NewRC->verify();
1949a80cfb30SChandler Carruth #endif
19502e0fe3e6SChandler Carruth       });
19512e0fe3e6SChandler Carruth }
19522e0fe3e6SChandler Carruth 
visitReferences(SmallVectorImpl<Constant * > & Worklist,SmallPtrSetImpl<Constant * > & Visited,function_ref<void (Function &)> Callback)195300500d5bSArthur Eubanks void LazyCallGraph::visitReferences(SmallVectorImpl<Constant *> &Worklist,
195400500d5bSArthur Eubanks                                     SmallPtrSetImpl<Constant *> &Visited,
195500500d5bSArthur Eubanks                                     function_ref<void(Function &)> Callback) {
195600500d5bSArthur Eubanks   while (!Worklist.empty()) {
195700500d5bSArthur Eubanks     Constant *C = Worklist.pop_back_val();
195800500d5bSArthur Eubanks 
195900500d5bSArthur Eubanks     if (Function *F = dyn_cast<Function>(C)) {
196000500d5bSArthur Eubanks       if (!F->isDeclaration())
196100500d5bSArthur Eubanks         Callback(*F);
196200500d5bSArthur Eubanks       continue;
196300500d5bSArthur Eubanks     }
196400500d5bSArthur Eubanks 
1965029f1a53SArthur Eubanks     // blockaddresses are weird and don't participate in the call graph anyway,
1966029f1a53SArthur Eubanks     // skip them.
1967029f1a53SArthur Eubanks     if (isa<BlockAddress>(C))
196800500d5bSArthur Eubanks       continue;
196900500d5bSArthur Eubanks 
197000500d5bSArthur Eubanks     for (Value *Op : C->operand_values())
197100500d5bSArthur Eubanks       if (Visited.insert(cast<Constant>(Op)).second)
197200500d5bSArthur Eubanks         Worklist.push_back(cast<Constant>(Op));
197300500d5bSArthur Eubanks   }
197400500d5bSArthur Eubanks }
197500500d5bSArthur Eubanks 
1976dab4eae2SChandler Carruth AnalysisKey LazyCallGraphAnalysis::Key;
1977df0cd726SNAKAMURA Takumi 
LazyCallGraphPrinterPass(raw_ostream & OS)1978bf71a34eSChandler Carruth LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1979bf71a34eSChandler Carruth 
printNode(raw_ostream & OS,LazyCallGraph::Node & N)1980e5944d97SChandler Carruth static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
1981a4499e9fSChandler Carruth   OS << "  Edges in function: " << N.getFunction().getName() << "\n";
1982aaad9f84SChandler Carruth   for (LazyCallGraph::Edge &E : N.populate())
1983a4499e9fSChandler Carruth     OS << "    " << (E.isCall() ? "call" : "ref ") << " -> "
1984a4499e9fSChandler Carruth        << E.getFunction().getName() << "\n";
198511f50323SChandler Carruth 
198611f50323SChandler Carruth   OS << "\n";
198711f50323SChandler Carruth }
198811f50323SChandler Carruth 
printSCC(raw_ostream & OS,LazyCallGraph::SCC & C)1989e5944d97SChandler Carruth static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1990cb4327d7SFangrui Song   OS << "    SCC with " << C.size() << " functions:\n";
199111f50323SChandler Carruth 
1992e5944d97SChandler Carruth   for (LazyCallGraph::Node &N : C)
1993e5944d97SChandler Carruth     OS << "      " << N.getFunction().getName() << "\n";
1994e5944d97SChandler Carruth }
1995e5944d97SChandler Carruth 
printRefSCC(raw_ostream & OS,LazyCallGraph::RefSCC & C)1996e5944d97SChandler Carruth static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1997cb4327d7SFangrui Song   OS << "  RefSCC with " << C.size() << " call SCCs:\n";
1998e5944d97SChandler Carruth 
1999e5944d97SChandler Carruth   for (LazyCallGraph::SCC &InnerC : C)
2000e5944d97SChandler Carruth     printSCC(OS, InnerC);
200111f50323SChandler Carruth 
200211f50323SChandler Carruth   OS << "\n";
200311f50323SChandler Carruth }
200411f50323SChandler Carruth 
run(Module & M,ModuleAnalysisManager & AM)2005d174ce4aSChandler Carruth PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
2006b47f8010SChandler Carruth                                                 ModuleAnalysisManager &AM) {
2007b47f8010SChandler Carruth   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
200811f50323SChandler Carruth 
200911f50323SChandler Carruth   OS << "Printing the call graph for module: " << M.getModuleIdentifier()
201011f50323SChandler Carruth      << "\n\n";
201111f50323SChandler Carruth 
2012e5944d97SChandler Carruth   for (Function &F : M)
2013e5944d97SChandler Carruth     printNode(OS, G.get(F));
201411f50323SChandler Carruth 
20152e0fe3e6SChandler Carruth   G.buildRefSCCs();
2016e5944d97SChandler Carruth   for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
2017e5944d97SChandler Carruth     printRefSCC(OS, C);
201818eadd92SChandler Carruth 
2019bf71a34eSChandler Carruth   return PreservedAnalyses::all();
2020bf71a34eSChandler Carruth }
20217cb30664SSean Silva 
LazyCallGraphDOTPrinterPass(raw_ostream & OS)20227cb30664SSean Silva LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
20237cb30664SSean Silva     : OS(OS) {}
20247cb30664SSean Silva 
printNodeDOT(raw_ostream & OS,LazyCallGraph::Node & N)20257cb30664SSean Silva static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
2026adcd0268SBenjamin Kramer   std::string Name =
2027adcd0268SBenjamin Kramer       "\"" + DOT::EscapeString(std::string(N.getFunction().getName())) + "\"";
20287cb30664SSean Silva 
2029aaad9f84SChandler Carruth   for (LazyCallGraph::Edge &E : N.populate()) {
20307cb30664SSean Silva     OS << "  " << Name << " -> \""
2031adcd0268SBenjamin Kramer        << DOT::EscapeString(std::string(E.getFunction().getName())) << "\"";
20327cb30664SSean Silva     if (!E.isCall()) // It is a ref edge.
20337cb30664SSean Silva       OS << " [style=dashed,label=\"ref\"]";
20347cb30664SSean Silva     OS << ";\n";
20357cb30664SSean Silva   }
20367cb30664SSean Silva 
20377cb30664SSean Silva   OS << "\n";
20387cb30664SSean Silva }
20397cb30664SSean Silva 
run(Module & M,ModuleAnalysisManager & AM)20407cb30664SSean Silva PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
20417cb30664SSean Silva                                                    ModuleAnalysisManager &AM) {
20427cb30664SSean Silva   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
20437cb30664SSean Silva 
20447cb30664SSean Silva   OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
20457cb30664SSean Silva 
20467cb30664SSean Silva   for (Function &F : M)
20477cb30664SSean Silva     printNodeDOT(OS, G.get(F));
20487cb30664SSean Silva 
20497cb30664SSean Silva   OS << "}\n";
20507cb30664SSean Silva 
20517cb30664SSean Silva   return PreservedAnalyses::all();
20527cb30664SSean Silva }
2053