1 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/Analysis/LazyCallGraph.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/IR/CallSite.h"
13 #include "llvm/IR/InstVisitor.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/PassManager.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/GraphWriter.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 using namespace llvm;
21 
22 #define DEBUG_TYPE "lcg"
23 
24 static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
25                     DenseMap<Function *, int> &EdgeIndexMap, Function &F,
26                     LazyCallGraph::Edge::Kind EK) {
27   // Note that we consider *any* function with a definition to be a viable
28   // edge. Even if the function's definition is subject to replacement by
29   // some other module (say, a weak definition) there may still be
30   // optimizations which essentially speculate based on the definition and
31   // a way to check that the specific definition is in fact the one being
32   // used. For example, this could be done by moving the weak definition to
33   // a strong (internal) definition and making the weak definition be an
34   // alias. Then a test of the address of the weak function against the new
35   // strong definition's address would be an effective way to determine the
36   // safety of optimizing a direct call edge.
37   if (!F.isDeclaration() &&
38       EdgeIndexMap.insert({&F, Edges.size()}).second) {
39     DEBUG(dbgs() << "    Added callable function: " << F.getName() << "\n");
40     Edges.emplace_back(LazyCallGraph::Edge(F, EK));
41   }
42 }
43 
44 static void findReferences(SmallVectorImpl<Constant *> &Worklist,
45                            SmallPtrSetImpl<Constant *> &Visited,
46                            SmallVectorImpl<LazyCallGraph::Edge> &Edges,
47                            DenseMap<Function *, int> &EdgeIndexMap) {
48   while (!Worklist.empty()) {
49     Constant *C = Worklist.pop_back_val();
50 
51     if (Function *F = dyn_cast<Function>(C)) {
52       addEdge(Edges, EdgeIndexMap, *F, LazyCallGraph::Edge::Ref);
53       continue;
54     }
55 
56     for (Value *Op : C->operand_values())
57       if (Visited.insert(cast<Constant>(Op)).second)
58         Worklist.push_back(cast<Constant>(Op));
59   }
60 }
61 
62 LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
63     : G(&G), F(F), DFSNumber(0), LowLink(0) {
64   DEBUG(dbgs() << "  Adding functions called by '" << F.getName()
65                << "' to the graph.\n");
66 
67   SmallVector<Constant *, 16> Worklist;
68   SmallPtrSet<Function *, 4> Callees;
69   SmallPtrSet<Constant *, 16> Visited;
70 
71   // Find all the potential call graph edges in this function. We track both
72   // actual call edges and indirect references to functions. The direct calls
73   // are trivially added, but to accumulate the latter we walk the instructions
74   // and add every operand which is a constant to the worklist to process
75   // afterward.
76   for (BasicBlock &BB : F)
77     for (Instruction &I : BB) {
78       if (auto CS = CallSite(&I))
79         if (Function *Callee = CS.getCalledFunction())
80           if (Callees.insert(Callee).second) {
81             Visited.insert(Callee);
82             addEdge(Edges, EdgeIndexMap, *Callee, LazyCallGraph::Edge::Call);
83           }
84 
85       for (Value *Op : I.operand_values())
86         if (Constant *C = dyn_cast<Constant>(Op))
87           if (Visited.insert(C).second)
88             Worklist.push_back(C);
89     }
90 
91   // We've collected all the constant (and thus potentially function or
92   // function containing) operands to all of the instructions in the function.
93   // Process them (recursively) collecting every function found.
94   findReferences(Worklist, Visited, Edges, EdgeIndexMap);
95 }
96 
97 void LazyCallGraph::Node::insertEdgeInternal(Function &Target, Edge::Kind EK) {
98   if (Node *N = G->lookup(Target))
99     return insertEdgeInternal(*N, EK);
100 
101   EdgeIndexMap.insert({&Target, Edges.size()});
102   Edges.emplace_back(Target, EK);
103 }
104 
105 void LazyCallGraph::Node::insertEdgeInternal(Node &TargetN, Edge::Kind EK) {
106   EdgeIndexMap.insert({&TargetN.getFunction(), Edges.size()});
107   Edges.emplace_back(TargetN, EK);
108 }
109 
110 void LazyCallGraph::Node::setEdgeKind(Function &TargetF, Edge::Kind EK) {
111   Edges[EdgeIndexMap.find(&TargetF)->second].setKind(EK);
112 }
113 
114 void LazyCallGraph::Node::removeEdgeInternal(Function &Target) {
115   auto IndexMapI = EdgeIndexMap.find(&Target);
116   assert(IndexMapI != EdgeIndexMap.end() &&
117          "Target not in the edge set for this caller?");
118 
119   Edges[IndexMapI->second] = Edge();
120   EdgeIndexMap.erase(IndexMapI);
121 }
122 
123 LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
124   DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
125                << "\n");
126   for (Function &F : M)
127     if (!F.isDeclaration() && !F.hasLocalLinkage())
128       if (EntryIndexMap.insert({&F, EntryEdges.size()}).second) {
129         DEBUG(dbgs() << "  Adding '" << F.getName()
130                      << "' to entry set of the graph.\n");
131         EntryEdges.emplace_back(F, Edge::Ref);
132       }
133 
134   // Now add entry nodes for functions reachable via initializers to globals.
135   SmallVector<Constant *, 16> Worklist;
136   SmallPtrSet<Constant *, 16> Visited;
137   for (GlobalVariable &GV : M.globals())
138     if (GV.hasInitializer())
139       if (Visited.insert(GV.getInitializer()).second)
140         Worklist.push_back(GV.getInitializer());
141 
142   DEBUG(dbgs() << "  Adding functions referenced by global initializers to the "
143                   "entry set.\n");
144   findReferences(Worklist, Visited, EntryEdges, EntryIndexMap);
145 
146   for (const Edge &E : EntryEdges)
147     RefSCCEntryNodes.push_back(&E.getFunction());
148 }
149 
150 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
151     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
152       EntryEdges(std::move(G.EntryEdges)),
153       EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
154       SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)),
155       DFSStack(std::move(G.DFSStack)),
156       RefSCCEntryNodes(std::move(G.RefSCCEntryNodes)),
157       NextDFSNumber(G.NextDFSNumber) {
158   updateGraphPtrs();
159 }
160 
161 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
162   BPA = std::move(G.BPA);
163   NodeMap = std::move(G.NodeMap);
164   EntryEdges = std::move(G.EntryEdges);
165   EntryIndexMap = std::move(G.EntryIndexMap);
166   SCCBPA = std::move(G.SCCBPA);
167   SCCMap = std::move(G.SCCMap);
168   LeafRefSCCs = std::move(G.LeafRefSCCs);
169   DFSStack = std::move(G.DFSStack);
170   RefSCCEntryNodes = std::move(G.RefSCCEntryNodes);
171   NextDFSNumber = G.NextDFSNumber;
172   updateGraphPtrs();
173   return *this;
174 }
175 
176 #ifndef NDEBUG
177 void LazyCallGraph::SCC::verify() {
178   assert(OuterRefSCC && "Can't have a null RefSCC!");
179   assert(!Nodes.empty() && "Can't have an empty SCC!");
180 
181   for (Node *N : Nodes) {
182     assert(N && "Can't have a null node!");
183     assert(OuterRefSCC->G->lookupSCC(*N) == this &&
184            "Node does not map to this SCC!");
185     assert(N->DFSNumber == -1 &&
186            "Must set DFS numbers to -1 when adding a node to an SCC!");
187     assert(N->LowLink == -1 &&
188            "Must set low link to -1 when adding a node to an SCC!");
189     for (Edge &E : *N)
190       assert(E.getNode() && "Can't have an edge to a raw function!");
191   }
192 }
193 #endif
194 
195 LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
196 
197 #ifndef NDEBUG
198 void LazyCallGraph::RefSCC::verify() {
199   assert(G && "Can't have a null graph!");
200   assert(!SCCs.empty() && "Can't have an empty SCC!");
201 
202   // Verify basic properties of the SCCs.
203   for (SCC *C : SCCs) {
204     assert(C && "Can't have a null SCC!");
205     C->verify();
206     assert(&C->getOuterRefSCC() == this &&
207            "SCC doesn't think it is inside this RefSCC!");
208   }
209 
210   // Check that our indices map correctly.
211   for (auto &SCCIndexPair : SCCIndices) {
212     SCC *C = SCCIndexPair.first;
213     int i = SCCIndexPair.second;
214     assert(C && "Can't have a null SCC in the indices!");
215     assert(SCCs[i] == C && "Index doesn't point to SCC!");
216   }
217 
218   // Check that the SCCs are in fact in post-order.
219   for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
220     SCC &SourceSCC = *SCCs[i];
221     for (Node &N : SourceSCC)
222       for (Edge &E : N) {
223         if (!E.isCall())
224           continue;
225         SCC &TargetSCC = *G->lookupSCC(*E.getNode());
226         if (&TargetSCC.getOuterRefSCC() == this) {
227           assert(SCCIndices.find(&TargetSCC)->second <= i &&
228                  "Edge between SCCs violates post-order relationship.");
229           continue;
230         }
231         assert(TargetSCC.getOuterRefSCC().Parents.count(this) &&
232                "Edge to a RefSCC missing us in its parent set.");
233       }
234   }
235 }
236 #endif
237 
238 bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const {
239   // Walk up the parents of this SCC and verify that we eventually find C.
240   SmallVector<const RefSCC *, 4> AncestorWorklist;
241   AncestorWorklist.push_back(this);
242   do {
243     const RefSCC *AncestorC = AncestorWorklist.pop_back_val();
244     if (AncestorC->isChildOf(C))
245       return true;
246     for (const RefSCC *ParentC : AncestorC->Parents)
247       AncestorWorklist.push_back(ParentC);
248   } while (!AncestorWorklist.empty());
249 
250   return false;
251 }
252 
253 SmallVector<LazyCallGraph::SCC *, 1>
254 LazyCallGraph::RefSCC::switchInternalEdgeToCall(Node &SourceN, Node &TargetN) {
255   assert(!SourceN[TargetN].isCall() && "Must start with a ref edge!");
256 
257   SmallVector<SCC *, 1> DeletedSCCs;
258 
259   SCC &SourceSCC = *G->lookupSCC(SourceN);
260   SCC &TargetSCC = *G->lookupSCC(TargetN);
261 
262   // If the two nodes are already part of the same SCC, we're also done as
263   // we've just added more connectivity.
264   if (&SourceSCC == &TargetSCC) {
265     SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
266 #ifndef NDEBUG
267     // Check that the RefSCC is still valid.
268     verify();
269 #endif
270     return DeletedSCCs;
271   }
272 
273   // At this point we leverage the postorder list of SCCs to detect when the
274   // insertion of an edge changes the SCC structure in any way.
275   //
276   // First and foremost, we can eliminate the need for any changes when the
277   // edge is toward the beginning of the postorder sequence because all edges
278   // flow in that direction already. Thus adding a new one cannot form a cycle.
279   int SourceIdx = SCCIndices[&SourceSCC];
280   int TargetIdx = SCCIndices[&TargetSCC];
281   if (TargetIdx < SourceIdx) {
282     SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
283 #ifndef NDEBUG
284     // Check that the RefSCC is still valid.
285     verify();
286 #endif
287     return DeletedSCCs;
288   }
289 
290   // When we do have an edge from an earlier SCC to a later SCC in the
291   // postorder sequence, all of the SCCs which may be impacted are in the
292   // closed range of those two within the postorder sequence. The algorithm to
293   // restore the state is as follows:
294   //
295   // 1) Starting from the source SCC, construct a set of SCCs which reach the
296   //    source SCC consisting of just the source SCC. Then scan toward the
297   //    target SCC in postorder and for each SCC, if it has an edge to an SCC
298   //    in the set, add it to the set. Otherwise, the source SCC is not
299   //    a successor, move it in the postorder sequence to immediately before
300   //    the source SCC, shifting the source SCC and all SCCs in the set one
301   //    position toward the target SCC. Stop scanning after processing the
302   //    target SCC.
303   // 2) If the source SCC is now past the target SCC in the postorder sequence,
304   //    and thus the new edge will flow toward the start, we are done.
305   // 3) Otherwise, starting from the target SCC, walk all edges which reach an
306   //    SCC between the source and the target, and add them to the set of
307   //    connected SCCs, then recurse through them. Once a complete set of the
308   //    SCCs the target connects to is known, hoist the remaining SCCs between
309   //    the source and the target to be above the target. Note that there is no
310   //    need to process the source SCC, it is already known to connect.
311   // 4) At this point, all of the SCCs in the closed range between the source
312   //    SCC and the target SCC in the postorder sequence are connected,
313   //    including the target SCC and the source SCC. Inserting the edge from
314   //    the source SCC to the target SCC will form a cycle out of precisely
315   //    these SCCs. Thus we can merge all of the SCCs in this closed range into
316   //    a single SCC.
317   //
318   // This process has various important properties:
319   // - Only mutates the SCCs when adding the edge actually changes the SCC
320   //   structure.
321   // - Never mutates SCCs which are unaffected by the change.
322   // - Updates the postorder sequence to correctly satisfy the postorder
323   //   constraint after the edge is inserted.
324   // - Only reorders SCCs in the closed postorder sequence from the source to
325   //   the target, so easy to bound how much has changed even in the ordering.
326   // - Big-O is the number of edges in the closed postorder range of SCCs from
327   //   source to target.
328 
329   assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
330   SmallPtrSet<SCC *, 4> ConnectedSet;
331 
332   // Compute the SCCs which (transitively) reach the source.
333   ConnectedSet.insert(&SourceSCC);
334   auto IsConnected = [&](SCC &C) {
335     for (Node &N : C)
336       for (Edge &E : N.calls()) {
337         assert(E.getNode() && "Must have formed a node within an SCC!");
338         if (ConnectedSet.count(G->lookupSCC(*E.getNode())))
339           return true;
340       }
341 
342     return false;
343   };
344 
345   for (SCC *C :
346        make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
347     if (IsConnected(*C))
348       ConnectedSet.insert(C);
349 
350   // Partition the SCCs in this part of the port-order sequence so only SCCs
351   // connecting to the source remain between it and the target. This is
352   // a benign partition as it preserves postorder.
353   auto SourceI = std::stable_partition(
354       SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
355       [&ConnectedSet](SCC *C) { return !ConnectedSet.count(C); });
356   for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
357     SCCIndices.find(SCCs[i])->second = i;
358 
359   // If the target doesn't connect to the source, then we've corrected the
360   // post-order and there are no cycles formed.
361   if (!ConnectedSet.count(&TargetSCC)) {
362     assert(SourceI > (SCCs.begin() + SourceIdx) &&
363            "Must have moved the source to fix the post-order.");
364     assert(*std::prev(SourceI) == &TargetSCC &&
365            "Last SCC to move should have bene the target.");
366     SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
367 #ifndef NDEBUG
368     verify();
369 #endif
370     return DeletedSCCs;
371   }
372 
373   assert(SCCs[TargetIdx] == &TargetSCC &&
374          "Should not have moved target if connected!");
375   SourceIdx = SourceI - SCCs.begin();
376 
377 #ifndef NDEBUG
378   // Check that the RefSCC is still valid.
379   verify();
380 #endif
381 
382   // See whether there are any remaining intervening SCCs between the source
383   // and target. If so we need to make sure they all are reachable form the
384   // target.
385   if (SourceIdx + 1 < TargetIdx) {
386     // Use a normal worklist to find which SCCs the target connects to. We still
387     // bound the search based on the range in the postorder list we care about,
388     // but because this is forward connectivity we just "recurse" through the
389     // edges.
390     ConnectedSet.clear();
391     ConnectedSet.insert(&TargetSCC);
392     SmallVector<SCC *, 4> Worklist;
393     Worklist.push_back(&TargetSCC);
394     do {
395       SCC &C = *Worklist.pop_back_val();
396       for (Node &N : C)
397         for (Edge &E : N) {
398           assert(E.getNode() && "Must have formed a node within an SCC!");
399           if (!E.isCall())
400             continue;
401           SCC &EdgeC = *G->lookupSCC(*E.getNode());
402           if (&EdgeC.getOuterRefSCC() != this)
403             // Not in this RefSCC...
404             continue;
405           if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
406             // Not in the postorder sequence between source and target.
407             continue;
408 
409           if (ConnectedSet.insert(&EdgeC).second)
410             Worklist.push_back(&EdgeC);
411         }
412     } while (!Worklist.empty());
413 
414     // Partition SCCs so that only SCCs reached from the target remain between
415     // the source and the target. This preserves postorder.
416     auto TargetI = std::stable_partition(
417         SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
418         [&ConnectedSet](SCC *C) { return ConnectedSet.count(C); });
419     for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
420       SCCIndices.find(SCCs[i])->second = i;
421     TargetIdx = std::prev(TargetI) - SCCs.begin();
422     assert(SCCs[TargetIdx] == &TargetSCC &&
423            "Should always end with the target!");
424 
425 #ifndef NDEBUG
426     // Check that the RefSCC is still valid.
427     verify();
428 #endif
429   }
430 
431   // At this point, we know that connecting source to target forms a cycle
432   // because target connects back to source, and we know that all of the SCCs
433   // between the source and target in the postorder sequence participate in that
434   // cycle. This means that we need to merge all of these SCCs into a single
435   // result SCC.
436   //
437   // NB: We merge into the target because all of these functions were already
438   // reachable from the target, meaning any SCC-wide properties deduced about it
439   // other than the set of functions within it will not have changed.
440   auto MergeRange =
441       make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
442   for (SCC *C : MergeRange) {
443     assert(C != &TargetSCC &&
444            "We merge *into* the target and shouldn't process it here!");
445     SCCIndices.erase(C);
446     TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
447     for (Node *N : C->Nodes)
448       G->SCCMap[N] = &TargetSCC;
449     C->clear();
450     DeletedSCCs.push_back(C);
451   }
452 
453   // Erase the merged SCCs from the list and update the indices of the
454   // remaining SCCs.
455   int IndexOffset = MergeRange.end() - MergeRange.begin();
456   auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
457   for (SCC *C : make_range(EraseEnd, SCCs.end()))
458     SCCIndices[C] -= IndexOffset;
459 
460   // Now that the SCC structure is finalized, flip the kind to call.
461   SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
462 
463 #ifndef NDEBUG
464   // And we're done! Verify in debug builds that the RefSCC is coherent.
465   verify();
466 #endif
467   return DeletedSCCs;
468 }
469 
470 void LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN,
471                                                     Node &TargetN) {
472   assert(SourceN[TargetN].isCall() && "Must start with a call edge!");
473 
474   SCC &SourceSCC = *G->lookupSCC(SourceN);
475   SCC &TargetSCC = *G->lookupSCC(TargetN);
476 
477   assert(&SourceSCC.getOuterRefSCC() == this &&
478          "Source must be in this RefSCC.");
479   assert(&TargetSCC.getOuterRefSCC() == this &&
480          "Target must be in this RefSCC.");
481 
482   // Set the edge kind.
483   SourceN.setEdgeKind(TargetN.getFunction(), Edge::Ref);
484 
485   // If this call edge is just connecting two separate SCCs within this RefSCC,
486   // there is nothing to do.
487   if (&SourceSCC != &TargetSCC) {
488 #ifndef NDEBUG
489     // Check that the RefSCC is still valid.
490     verify();
491 #endif
492     return;
493   }
494 
495   // Otherwise we are removing a call edge from a single SCC. This may break
496   // the cycle. In order to compute the new set of SCCs, we need to do a small
497   // DFS over the nodes within the SCC to form any sub-cycles that remain as
498   // distinct SCCs and compute a postorder over the resulting SCCs.
499   //
500   // However, we specially handle the target node. The target node is known to
501   // reach all other nodes in the original SCC by definition. This means that
502   // we want the old SCC to be replaced with an SCC contaning that node as it
503   // will be the root of whatever SCC DAG results from the DFS. Assumptions
504   // about an SCC such as the set of functions called will continue to hold,
505   // etc.
506 
507   SCC &OldSCC = TargetSCC;
508   SmallVector<std::pair<Node *, call_edge_iterator>, 16> DFSStack;
509   SmallVector<Node *, 16> PendingSCCStack;
510   SmallVector<SCC *, 4> NewSCCs;
511 
512   // Prepare the nodes for a fresh DFS.
513   SmallVector<Node *, 16> Worklist;
514   Worklist.swap(OldSCC.Nodes);
515   for (Node *N : Worklist) {
516     N->DFSNumber = N->LowLink = 0;
517     G->SCCMap.erase(N);
518   }
519 
520   // Force the target node to be in the old SCC. This also enables us to take
521   // a very significant short-cut in the standard Tarjan walk to re-form SCCs
522   // below: whenever we build an edge that reaches the target node, we know
523   // that the target node eventually connects back to all other nodes in our
524   // walk. As a consequence, we can detect and handle participants in that
525   // cycle without walking all the edges that form this connection, and instead
526   // by relying on the fundamental guarantee coming into this operation (all
527   // nodes are reachable from the target due to previously forming an SCC).
528   TargetN.DFSNumber = TargetN.LowLink = -1;
529   OldSCC.Nodes.push_back(&TargetN);
530   G->SCCMap[&TargetN] = &OldSCC;
531 
532   // Scan down the stack and DFS across the call edges.
533   for (Node *RootN : Worklist) {
534     assert(DFSStack.empty() &&
535            "Cannot begin a new root with a non-empty DFS stack!");
536     assert(PendingSCCStack.empty() &&
537            "Cannot begin a new root with pending nodes for an SCC!");
538 
539     // Skip any nodes we've already reached in the DFS.
540     if (RootN->DFSNumber != 0) {
541       assert(RootN->DFSNumber == -1 &&
542              "Shouldn't have any mid-DFS root nodes!");
543       continue;
544     }
545 
546     RootN->DFSNumber = RootN->LowLink = 1;
547     int NextDFSNumber = 2;
548 
549     DFSStack.push_back({RootN, RootN->call_begin()});
550     do {
551       Node *N;
552       call_edge_iterator I;
553       std::tie(N, I) = DFSStack.pop_back_val();
554       auto E = N->call_end();
555       while (I != E) {
556         Node &ChildN = *I->getNode();
557         if (ChildN.DFSNumber == 0) {
558           // We haven't yet visited this child, so descend, pushing the current
559           // node onto the stack.
560           DFSStack.push_back({N, I});
561 
562           assert(!G->SCCMap.count(&ChildN) &&
563                  "Found a node with 0 DFS number but already in an SCC!");
564           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
565           N = &ChildN;
566           I = N->call_begin();
567           E = N->call_end();
568           continue;
569         }
570 
571         // Check for the child already being part of some component.
572         if (ChildN.DFSNumber == -1) {
573           if (G->lookupSCC(ChildN) == &OldSCC) {
574             // If the child is part of the old SCC, we know that it can reach
575             // every other node, so we have formed a cycle. Pull the entire DFS
576             // and pending stacks into it. See the comment above about setting
577             // up the old SCC for why we do this.
578             int OldSize = OldSCC.size();
579             OldSCC.Nodes.push_back(N);
580             OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
581             PendingSCCStack.clear();
582             while (!DFSStack.empty())
583               OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
584             for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
585               N.DFSNumber = N.LowLink = -1;
586               G->SCCMap[&N] = &OldSCC;
587             }
588             N = nullptr;
589             break;
590           }
591 
592           // If the child has already been added to some child component, it
593           // couldn't impact the low-link of this parent because it isn't
594           // connected, and thus its low-link isn't relevant so skip it.
595           ++I;
596           continue;
597         }
598 
599         // Track the lowest linked child as the lowest link for this node.
600         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
601         if (ChildN.LowLink < N->LowLink)
602           N->LowLink = ChildN.LowLink;
603 
604         // Move to the next edge.
605         ++I;
606       }
607       if (!N)
608         // Cleared the DFS early, start another round.
609         break;
610 
611       // We've finished processing N and its descendents, put it on our pending
612       // SCC stack to eventually get merged into an SCC of nodes.
613       PendingSCCStack.push_back(N);
614 
615       // If this node is linked to some lower entry, continue walking up the
616       // stack.
617       if (N->LowLink != N->DFSNumber)
618         continue;
619 
620       // Otherwise, we've completed an SCC. Append it to our post order list of
621       // SCCs.
622       int RootDFSNumber = N->DFSNumber;
623       // Find the range of the node stack by walking down until we pass the
624       // root DFS number.
625       auto SCCNodes = make_range(
626           PendingSCCStack.rbegin(),
627           std::find_if(PendingSCCStack.rbegin(), PendingSCCStack.rend(),
628                        [RootDFSNumber](Node *N) {
629                          return N->DFSNumber < RootDFSNumber;
630                        }));
631 
632       // Form a new SCC out of these nodes and then clear them off our pending
633       // stack.
634       NewSCCs.push_back(G->createSCC(*this, SCCNodes));
635       for (Node &N : *NewSCCs.back()) {
636         N.DFSNumber = N.LowLink = -1;
637         G->SCCMap[&N] = NewSCCs.back();
638       }
639       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
640     } while (!DFSStack.empty());
641   }
642 
643   // Insert the remaining SCCs before the old one. The old SCC can reach all
644   // other SCCs we form because it contains the target node of the removed edge
645   // of the old SCC. This means that we will have edges into all of the new
646   // SCCs, which means the old one must come last for postorder.
647   int OldIdx = SCCIndices[&OldSCC];
648   SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
649 
650   // Update the mapping from SCC* to index to use the new SCC*s, and remove the
651   // old SCC from the mapping.
652   for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
653     SCCIndices[SCCs[Idx]] = Idx;
654 
655 #ifndef NDEBUG
656   // We're done. Check the validity on our way out.
657   verify();
658 #endif
659 }
660 
661 void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
662                                                      Node &TargetN) {
663   assert(!SourceN[TargetN].isCall() && "Must start with a ref edge!");
664 
665   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
666   assert(G->lookupRefSCC(TargetN) != this &&
667          "Target must not be in this RefSCC.");
668   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
669          "Target must be a descendant of the Source.");
670 
671   // Edges between RefSCCs are the same regardless of call or ref, so we can
672   // just flip the edge here.
673   SourceN.setEdgeKind(TargetN.getFunction(), Edge::Call);
674 
675 #ifndef NDEBUG
676   // Check that the RefSCC is still valid.
677   verify();
678 #endif
679 }
680 
681 void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
682                                                     Node &TargetN) {
683   assert(SourceN[TargetN].isCall() && "Must start with a call edge!");
684 
685   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
686   assert(G->lookupRefSCC(TargetN) != this &&
687          "Target must not be in this RefSCC.");
688   assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
689          "Target must be a descendant of the Source.");
690 
691   // Edges between RefSCCs are the same regardless of call or ref, so we can
692   // just flip the edge here.
693   SourceN.setEdgeKind(TargetN.getFunction(), Edge::Ref);
694 
695 #ifndef NDEBUG
696   // Check that the RefSCC is still valid.
697   verify();
698 #endif
699 }
700 
701 void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
702                                                   Node &TargetN) {
703   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
704   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
705 
706   SourceN.insertEdgeInternal(TargetN, Edge::Ref);
707 
708 #ifndef NDEBUG
709   // Check that the RefSCC is still valid.
710   verify();
711 #endif
712 }
713 
714 void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
715                                                Edge::Kind EK) {
716   // First insert it into the caller.
717   SourceN.insertEdgeInternal(TargetN, EK);
718 
719   assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
720 
721   RefSCC &TargetC = *G->lookupRefSCC(TargetN);
722   assert(&TargetC != this && "Target must not be in this RefSCC.");
723   assert(TargetC.isDescendantOf(*this) &&
724          "Target must be a descendant of the Source.");
725 
726   // The only change required is to add this SCC to the parent set of the
727   // callee.
728   TargetC.Parents.insert(this);
729 
730 #ifndef NDEBUG
731   // Check that the RefSCC is still valid.
732   verify();
733 #endif
734 }
735 
736 SmallVector<LazyCallGraph::RefSCC *, 1>
737 LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
738   assert(G->lookupRefSCC(TargetN) == this && "Target must be in this SCC.");
739 
740   // We store the RefSCCs found to be connected in postorder so that we can use
741   // that when merging. We also return this to the caller to allow them to
742   // invalidate information pertaining to these RefSCCs.
743   SmallVector<RefSCC *, 1> Connected;
744 
745   RefSCC &SourceC = *G->lookupRefSCC(SourceN);
746   assert(&SourceC != this && "Source must not be in this SCC.");
747   assert(SourceC.isDescendantOf(*this) &&
748          "Source must be a descendant of the Target.");
749 
750   // The algorithm we use for merging SCCs based on the cycle introduced here
751   // is to walk the RefSCC inverted DAG formed by the parent sets. The inverse
752   // graph has the same cycle properties as the actual DAG of the RefSCCs, and
753   // when forming RefSCCs lazily by a DFS, the bottom of the graph won't exist
754   // in many cases which should prune the search space.
755   //
756   // FIXME: We can get this pruning behavior even after the incremental RefSCC
757   // formation by leaving behind (conservative) DFS numberings in the nodes,
758   // and pruning the search with them. These would need to be cleverly updated
759   // during the removal of intra-SCC edges, but could be preserved
760   // conservatively.
761   //
762   // FIXME: This operation currently creates ordering stability problems
763   // because we don't use stably ordered containers for the parent SCCs.
764 
765   // The set of RefSCCs that are connected to the parent, and thus will
766   // participate in the merged connected component.
767   SmallPtrSet<RefSCC *, 8> ConnectedSet;
768   ConnectedSet.insert(this);
769 
770   // We build up a DFS stack of the parents chains.
771   SmallVector<std::pair<RefSCC *, parent_iterator>, 8> DFSStack;
772   SmallPtrSet<RefSCC *, 8> Visited;
773   int ConnectedDepth = -1;
774   DFSStack.push_back({&SourceC, SourceC.parent_begin()});
775   do {
776     auto DFSPair = DFSStack.pop_back_val();
777     RefSCC *C = DFSPair.first;
778     parent_iterator I = DFSPair.second;
779     auto E = C->parent_end();
780 
781     while (I != E) {
782       RefSCC &Parent = *I++;
783 
784       // If we have already processed this parent SCC, skip it, and remember
785       // whether it was connected so we don't have to check the rest of the
786       // stack. This also handles when we reach a child of the 'this' SCC (the
787       // callee) which terminates the search.
788       if (ConnectedSet.count(&Parent)) {
789         assert(ConnectedDepth < (int)DFSStack.size() &&
790                "Cannot have a connected depth greater than the DFS depth!");
791         ConnectedDepth = DFSStack.size();
792         continue;
793       }
794       if (Visited.count(&Parent))
795         continue;
796 
797       // We fully explore the depth-first space, adding nodes to the connected
798       // set only as we pop them off, so "recurse" by rotating to the parent.
799       DFSStack.push_back({C, I});
800       C = &Parent;
801       I = C->parent_begin();
802       E = C->parent_end();
803     }
804 
805     // If we've found a connection anywhere below this point on the stack (and
806     // thus up the parent graph from the caller), the current node needs to be
807     // added to the connected set now that we've processed all of its parents.
808     if ((int)DFSStack.size() == ConnectedDepth) {
809       --ConnectedDepth; // We're finished with this connection.
810       bool Inserted = ConnectedSet.insert(C).second;
811       (void)Inserted;
812       assert(Inserted && "Cannot insert a refSCC multiple times!");
813       Connected.push_back(C);
814     } else {
815       // Otherwise remember that its parents don't ever connect.
816       assert(ConnectedDepth < (int)DFSStack.size() &&
817              "Cannot have a connected depth greater than the DFS depth!");
818       Visited.insert(C);
819     }
820   } while (!DFSStack.empty());
821 
822   // Now that we have identified all of the SCCs which need to be merged into
823   // a connected set with the inserted edge, merge all of them into this SCC.
824   // We walk the newly connected RefSCCs in the reverse postorder of the parent
825   // DAG walk above and merge in each of their SCC postorder lists. This
826   // ensures a merged postorder SCC list.
827   SmallVector<SCC *, 16> MergedSCCs;
828   int SCCIndex = 0;
829   for (RefSCC *C : reverse(Connected)) {
830     assert(C != this &&
831            "This RefSCC should terminate the DFS without being reached.");
832 
833     // Merge the parents which aren't part of the merge into the our parents.
834     for (RefSCC *ParentC : C->Parents)
835       if (!ConnectedSet.count(ParentC))
836         Parents.insert(ParentC);
837     C->Parents.clear();
838 
839     // Walk the inner SCCs to update their up-pointer and walk all the edges to
840     // update any parent sets.
841     // FIXME: We should try to find a way to avoid this (rather expensive) edge
842     // walk by updating the parent sets in some other manner.
843     for (SCC &InnerC : *C) {
844       InnerC.OuterRefSCC = this;
845       SCCIndices[&InnerC] = SCCIndex++;
846       for (Node &N : InnerC) {
847         G->SCCMap[&N] = &InnerC;
848         for (Edge &E : N) {
849           assert(E.getNode() &&
850                  "Cannot have a null node within a visited SCC!");
851           RefSCC &ChildRC = *G->lookupRefSCC(*E.getNode());
852           if (ConnectedSet.count(&ChildRC))
853             continue;
854           ChildRC.Parents.erase(C);
855           ChildRC.Parents.insert(this);
856         }
857       }
858     }
859 
860     // Now merge in the SCCs. We can actually move here so try to reuse storage
861     // the first time through.
862     if (MergedSCCs.empty())
863       MergedSCCs = std::move(C->SCCs);
864     else
865       MergedSCCs.append(C->SCCs.begin(), C->SCCs.end());
866     C->SCCs.clear();
867   }
868 
869   // Finally append our original SCCs to the merged list and move it into
870   // place.
871   for (SCC &InnerC : *this)
872     SCCIndices[&InnerC] = SCCIndex++;
873   MergedSCCs.append(SCCs.begin(), SCCs.end());
874   SCCs = std::move(MergedSCCs);
875 
876   // At this point we have a merged RefSCC with a post-order SCCs list, just
877   // connect the nodes to form the new edge.
878   SourceN.insertEdgeInternal(TargetN, Edge::Ref);
879 
880 #ifndef NDEBUG
881   // Check that the RefSCC is still valid.
882   verify();
883 #endif
884 
885   // We return the list of SCCs which were merged so that callers can
886   // invalidate any data they have associated with those SCCs. Note that these
887   // SCCs are no longer in an interesting state (they are totally empty) but
888   // the pointers will remain stable for the life of the graph itself.
889   return Connected;
890 }
891 
892 void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
893   assert(G->lookupRefSCC(SourceN) == this &&
894          "The source must be a member of this RefSCC.");
895 
896   RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
897   assert(&TargetRC != this && "The target must not be a member of this RefSCC");
898 
899   assert(std::find(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this) ==
900              G->LeafRefSCCs.end() &&
901          "Cannot have a leaf RefSCC source.");
902 
903   // First remove it from the node.
904   SourceN.removeEdgeInternal(TargetN.getFunction());
905 
906   bool HasOtherEdgeToChildRC = false;
907   bool HasOtherChildRC = false;
908   for (SCC *InnerC : SCCs) {
909     for (Node &N : *InnerC) {
910       for (Edge &E : N) {
911         assert(E.getNode() && "Cannot have a missing node in a visited SCC!");
912         RefSCC &OtherChildRC = *G->lookupRefSCC(*E.getNode());
913         if (&OtherChildRC == &TargetRC) {
914           HasOtherEdgeToChildRC = true;
915           break;
916         }
917         if (&OtherChildRC != this)
918           HasOtherChildRC = true;
919       }
920       if (HasOtherEdgeToChildRC)
921         break;
922     }
923     if (HasOtherEdgeToChildRC)
924       break;
925   }
926   // Because the SCCs form a DAG, deleting such an edge cannot change the set
927   // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
928   // the source SCC no longer connected to the target SCC. If so, we need to
929   // update the target SCC's map of its parents.
930   if (!HasOtherEdgeToChildRC) {
931     bool Removed = TargetRC.Parents.erase(this);
932     (void)Removed;
933     assert(Removed &&
934            "Did not find the source SCC in the target SCC's parent list!");
935 
936     // It may orphan an SCC if it is the last edge reaching it, but that does
937     // not violate any invariants of the graph.
938     if (TargetRC.Parents.empty())
939       DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName()
940                    << " -> " << TargetN.getFunction().getName()
941                    << " edge orphaned the callee's SCC!\n");
942 
943     // It may make the Source SCC a leaf SCC.
944     if (!HasOtherChildRC)
945       G->LeafRefSCCs.push_back(this);
946   }
947 }
948 
949 SmallVector<LazyCallGraph::RefSCC *, 1>
950 LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
951   assert(!SourceN[TargetN].isCall() &&
952          "Cannot remove a call edge, it must first be made a ref edge");
953 
954   // First remove the actual edge.
955   SourceN.removeEdgeInternal(TargetN.getFunction());
956 
957   // We return a list of the resulting *new* RefSCCs in post-order.
958   SmallVector<RefSCC *, 1> Result;
959 
960   // Direct recursion doesn't impact the SCC graph at all.
961   if (&SourceN == &TargetN)
962     return Result;
963 
964   // We build somewhat synthetic new RefSCCs by providing a postorder mapping
965   // for each inner SCC. We also store these associated with *nodes* rather
966   // than SCCs because this saves a round-trip through the node->SCC map and in
967   // the common case, SCCs are small. We will verify that we always give the
968   // same number to every node in the SCC such that these are equivalent.
969   const int RootPostOrderNumber = 0;
970   int PostOrderNumber = RootPostOrderNumber + 1;
971   SmallDenseMap<Node *, int> PostOrderMapping;
972 
973   // Every node in the target SCC can already reach every node in this RefSCC
974   // (by definition). It is the only node we know will stay inside this RefSCC.
975   // Everything which transitively reaches Target will also remain in the
976   // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
977   // back to the root post order number.
978   //
979   // This also enables us to take a very significant short-cut in the standard
980   // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
981   // references the target node, we know that the target node eventually
982   // references all other nodes in our walk. As a consequence, we can detect
983   // and handle participants in that cycle without walking all the edges that
984   // form the connections, and instead by relying on the fundamental guarantee
985   // coming into this operation.
986   SCC &TargetC = *G->lookupSCC(TargetN);
987   for (Node &N : TargetC)
988     PostOrderMapping[&N] = RootPostOrderNumber;
989 
990   // Reset all the other nodes to prepare for a DFS over them, and add them to
991   // our worklist.
992   SmallVector<Node *, 8> Worklist;
993   for (SCC *C : SCCs) {
994     if (C == &TargetC)
995       continue;
996 
997     for (Node &N : *C)
998       N.DFSNumber = N.LowLink = 0;
999 
1000     Worklist.append(C->Nodes.begin(), C->Nodes.end());
1001   }
1002 
1003   auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1004     N.DFSNumber = N.LowLink = -1;
1005     PostOrderMapping[&N] = Number;
1006   };
1007 
1008   SmallVector<std::pair<Node *, edge_iterator>, 4> DFSStack;
1009   SmallVector<Node *, 4> PendingRefSCCStack;
1010   do {
1011     assert(DFSStack.empty() &&
1012            "Cannot begin a new root with a non-empty DFS stack!");
1013     assert(PendingRefSCCStack.empty() &&
1014            "Cannot begin a new root with pending nodes for an SCC!");
1015 
1016     Node *RootN = Worklist.pop_back_val();
1017     // Skip any nodes we've already reached in the DFS.
1018     if (RootN->DFSNumber != 0) {
1019       assert(RootN->DFSNumber == -1 &&
1020              "Shouldn't have any mid-DFS root nodes!");
1021       continue;
1022     }
1023 
1024     RootN->DFSNumber = RootN->LowLink = 1;
1025     int NextDFSNumber = 2;
1026 
1027     DFSStack.push_back({RootN, RootN->begin()});
1028     do {
1029       Node *N;
1030       edge_iterator I;
1031       std::tie(N, I) = DFSStack.pop_back_val();
1032       auto E = N->end();
1033 
1034       assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1035                                   "before processing a node.");
1036 
1037       while (I != E) {
1038         Node &ChildN = I->getNode(*G);
1039         if (ChildN.DFSNumber == 0) {
1040           // Mark that we should start at this child when next this node is the
1041           // top of the stack. We don't start at the next child to ensure this
1042           // child's lowlink is reflected.
1043           DFSStack.push_back({N, I});
1044 
1045           // Continue, resetting to the child node.
1046           ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1047           N = &ChildN;
1048           I = ChildN.begin();
1049           E = ChildN.end();
1050           continue;
1051         }
1052         if (ChildN.DFSNumber == -1) {
1053           // Check if this edge's target node connects to the deleted edge's
1054           // target node. If so, we know that every node connected will end up
1055           // in this RefSCC, so collapse the entire current stack into the root
1056           // slot in our SCC numbering. See above for the motivation of
1057           // optimizing the target connected nodes in this way.
1058           auto PostOrderI = PostOrderMapping.find(&ChildN);
1059           if (PostOrderI != PostOrderMapping.end() &&
1060               PostOrderI->second == RootPostOrderNumber) {
1061             MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1062             while (!PendingRefSCCStack.empty())
1063               MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1064                                    RootPostOrderNumber);
1065             while (!DFSStack.empty())
1066               MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1067                                    RootPostOrderNumber);
1068             // Ensure we break all the way out of the enclosing loop.
1069             N = nullptr;
1070             break;
1071           }
1072 
1073           // If this child isn't currently in this RefSCC, no need to process
1074           // it.
1075           // However, we do need to remove this RefSCC from its RefSCC's parent
1076           // set.
1077           RefSCC &ChildRC = *G->lookupRefSCC(ChildN);
1078           ChildRC.Parents.erase(this);
1079           ++I;
1080           continue;
1081         }
1082 
1083         // Track the lowest link of the children, if any are still in the stack.
1084         // Any child not on the stack will have a LowLink of -1.
1085         assert(ChildN.LowLink != 0 &&
1086                "Low-link must not be zero with a non-zero DFS number.");
1087         if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1088           N->LowLink = ChildN.LowLink;
1089         ++I;
1090       }
1091       if (!N)
1092         // We short-circuited this node.
1093         break;
1094 
1095       // We've finished processing N and its descendents, put it on our pending
1096       // stack to eventually get merged into a RefSCC.
1097       PendingRefSCCStack.push_back(N);
1098 
1099       // If this node is linked to some lower entry, continue walking up the
1100       // stack.
1101       if (N->LowLink != N->DFSNumber) {
1102         assert(!DFSStack.empty() &&
1103                "We never found a viable root for a RefSCC to pop off!");
1104         continue;
1105       }
1106 
1107       // Otherwise, form a new RefSCC from the top of the pending node stack.
1108       int RootDFSNumber = N->DFSNumber;
1109       // Find the range of the node stack by walking down until we pass the
1110       // root DFS number.
1111       auto RefSCCNodes = make_range(
1112           PendingRefSCCStack.rbegin(),
1113           std::find_if(PendingRefSCCStack.rbegin(), PendingRefSCCStack.rend(),
1114                        [RootDFSNumber](Node *N) {
1115                          return N->DFSNumber < RootDFSNumber;
1116                        }));
1117 
1118       // Mark the postorder number for these nodes and clear them off the
1119       // stack. We'll use the postorder number to pull them into RefSCCs at the
1120       // end. FIXME: Fuse with the loop above.
1121       int RefSCCNumber = PostOrderNumber++;
1122       for (Node *N : RefSCCNodes)
1123         MarkNodeForSCCNumber(*N, RefSCCNumber);
1124 
1125       PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1126                                PendingRefSCCStack.end());
1127     } while (!DFSStack.empty());
1128 
1129     assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
1130     assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
1131   } while (!Worklist.empty());
1132 
1133   // We now have a post-order numbering for RefSCCs and a mapping from each
1134   // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1135   // (re-using this RefSCC node for the root) and build a radix-sort style map
1136   // from postorder number to the RefSCC. We then append SCCs to each of these
1137   // RefSCCs in the order they occured in the original SCCs container.
1138   for (int i = 1; i < PostOrderNumber; ++i)
1139     Result.push_back(G->createRefSCC(*G));
1140 
1141   for (SCC *C : SCCs) {
1142     auto PostOrderI = PostOrderMapping.find(&*C->begin());
1143     assert(PostOrderI != PostOrderMapping.end() &&
1144            "Cannot have missing mappings for nodes!");
1145     int SCCNumber = PostOrderI->second;
1146 #ifndef NDEBUG
1147     for (Node &N : *C)
1148       assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1149              "Cannot have different numbers for nodes in the same SCC!");
1150 #endif
1151     if (SCCNumber == 0)
1152       // The root node is handled separately by removing the SCCs.
1153       continue;
1154 
1155     RefSCC &RC = *Result[SCCNumber - 1];
1156     int SCCIndex = RC.SCCs.size();
1157     RC.SCCs.push_back(C);
1158     SCCIndices[C] = SCCIndex;
1159     C->OuterRefSCC = &RC;
1160   }
1161 
1162   // FIXME: We re-walk the edges in each RefSCC to establish whether it is
1163   // a leaf and connect it to the rest of the graph's parents lists. This is
1164   // really wasteful. We should instead do this during the DFS to avoid yet
1165   // another edge walk.
1166   for (RefSCC *RC : Result)
1167     G->connectRefSCC(*RC);
1168 
1169   // Now erase all but the root's SCCs.
1170   SCCs.erase(std::remove_if(SCCs.begin(), SCCs.end(),
1171                             [&](SCC *C) {
1172                               return PostOrderMapping.lookup(&*C->begin()) !=
1173                                      RootPostOrderNumber;
1174                             }),
1175              SCCs.end());
1176 
1177 #ifndef NDEBUG
1178   // Now we need to reconnect the current (root) SCC to the graph. We do this
1179   // manually because we can special case our leaf handling and detect errors.
1180   bool IsLeaf = true;
1181 #endif
1182   for (SCC *C : SCCs)
1183     for (Node &N : *C) {
1184       for (Edge &E : N) {
1185         assert(E.getNode() && "Cannot have a missing node in a visited SCC!");
1186         RefSCC &ChildRC = *G->lookupRefSCC(*E.getNode());
1187         if (&ChildRC == this)
1188           continue;
1189         ChildRC.Parents.insert(this);
1190 #ifndef NDEBUG
1191         IsLeaf = false;
1192 #endif
1193       }
1194     }
1195 #ifndef NDEBUG
1196   if (!Result.empty())
1197     assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new "
1198                       "SCCs by removing this edge.");
1199   if (!std::any_of(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(),
1200                    [&](RefSCC *C) { return C == this; }))
1201     assert(!IsLeaf && "This SCC cannot be a leaf as it already had child "
1202                       "SCCs before we removed this edge.");
1203 #endif
1204   // If this SCC stopped being a leaf through this edge removal, remove it from
1205   // the leaf SCC list. Note that this DTRT in the case where this was never
1206   // a leaf.
1207   // FIXME: As LeafRefSCCs could be very large, we might want to not walk the
1208   // entire list if this RefSCC wasn't a leaf before the edge removal.
1209   if (!Result.empty())
1210     G->LeafRefSCCs.erase(
1211         std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this),
1212         G->LeafRefSCCs.end());
1213 
1214   // Return the new list of SCCs.
1215   return Result;
1216 }
1217 
1218 void LazyCallGraph::insertEdge(Node &SourceN, Function &Target, Edge::Kind EK) {
1219   assert(SCCMap.empty() && DFSStack.empty() &&
1220          "This method cannot be called after SCCs have been formed!");
1221 
1222   return SourceN.insertEdgeInternal(Target, EK);
1223 }
1224 
1225 void LazyCallGraph::removeEdge(Node &SourceN, Function &Target) {
1226   assert(SCCMap.empty() && DFSStack.empty() &&
1227          "This method cannot be called after SCCs have been formed!");
1228 
1229   return SourceN.removeEdgeInternal(Target);
1230 }
1231 
1232 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1233   return *new (MappedN = BPA.Allocate()) Node(*this, F);
1234 }
1235 
1236 void LazyCallGraph::updateGraphPtrs() {
1237   // Process all nodes updating the graph pointers.
1238   {
1239     SmallVector<Node *, 16> Worklist;
1240     for (Edge &E : EntryEdges)
1241       if (Node *EntryN = E.getNode())
1242         Worklist.push_back(EntryN);
1243 
1244     while (!Worklist.empty()) {
1245       Node *N = Worklist.pop_back_val();
1246       N->G = this;
1247       for (Edge &E : N->Edges)
1248         if (Node *TargetN = E.getNode())
1249           Worklist.push_back(TargetN);
1250     }
1251   }
1252 
1253   // Process all SCCs updating the graph pointers.
1254   {
1255     SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end());
1256 
1257     while (!Worklist.empty()) {
1258       RefSCC &C = *Worklist.pop_back_val();
1259       C.G = this;
1260       for (RefSCC &ParentC : C.parents())
1261         Worklist.push_back(&ParentC);
1262     }
1263   }
1264 }
1265 
1266 /// Build the internal SCCs for a RefSCC from a sequence of nodes.
1267 ///
1268 /// Appends the SCCs to the provided vector and updates the map with their
1269 /// indices. Both the vector and map must be empty when passed into this
1270 /// routine.
1271 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1272   assert(RC.SCCs.empty() && "Already built SCCs!");
1273   assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1274 
1275   for (Node *N : Nodes) {
1276     assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1277            "We cannot have a low link in an SCC lower than its root on the "
1278            "stack!");
1279 
1280     // This node will go into the next RefSCC, clear out its DFS and low link
1281     // as we scan.
1282     N->DFSNumber = N->LowLink = 0;
1283   }
1284 
1285   // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1286   // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1287   // internal storage as we won't need it for the outer graph's DFS any longer.
1288 
1289   SmallVector<std::pair<Node *, call_edge_iterator>, 16> DFSStack;
1290   SmallVector<Node *, 16> PendingSCCStack;
1291 
1292   // Scan down the stack and DFS across the call edges.
1293   for (Node *RootN : Nodes) {
1294     assert(DFSStack.empty() &&
1295            "Cannot begin a new root with a non-empty DFS stack!");
1296     assert(PendingSCCStack.empty() &&
1297            "Cannot begin a new root with pending nodes for an SCC!");
1298 
1299     // Skip any nodes we've already reached in the DFS.
1300     if (RootN->DFSNumber != 0) {
1301       assert(RootN->DFSNumber == -1 &&
1302              "Shouldn't have any mid-DFS root nodes!");
1303       continue;
1304     }
1305 
1306     RootN->DFSNumber = RootN->LowLink = 1;
1307     int NextDFSNumber = 2;
1308 
1309     DFSStack.push_back({RootN, RootN->call_begin()});
1310     do {
1311       Node *N;
1312       call_edge_iterator I;
1313       std::tie(N, I) = DFSStack.pop_back_val();
1314       auto E = N->call_end();
1315       while (I != E) {
1316         Node &ChildN = *I->getNode();
1317         if (ChildN.DFSNumber == 0) {
1318           // We haven't yet visited this child, so descend, pushing the current
1319           // node onto the stack.
1320           DFSStack.push_back({N, I});
1321 
1322           assert(!lookupSCC(ChildN) &&
1323                  "Found a node with 0 DFS number but already in an SCC!");
1324           ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1325           N = &ChildN;
1326           I = N->call_begin();
1327           E = N->call_end();
1328           continue;
1329         }
1330 
1331         // If the child has already been added to some child component, it
1332         // couldn't impact the low-link of this parent because it isn't
1333         // connected, and thus its low-link isn't relevant so skip it.
1334         if (ChildN.DFSNumber == -1) {
1335           ++I;
1336           continue;
1337         }
1338 
1339         // Track the lowest linked child as the lowest link for this node.
1340         assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1341         if (ChildN.LowLink < N->LowLink)
1342           N->LowLink = ChildN.LowLink;
1343 
1344         // Move to the next edge.
1345         ++I;
1346       }
1347 
1348       // We've finished processing N and its descendents, put it on our pending
1349       // SCC stack to eventually get merged into an SCC of nodes.
1350       PendingSCCStack.push_back(N);
1351 
1352       // If this node is linked to some lower entry, continue walking up the
1353       // stack.
1354       if (N->LowLink != N->DFSNumber)
1355         continue;
1356 
1357       // Otherwise, we've completed an SCC. Append it to our post order list of
1358       // SCCs.
1359       int RootDFSNumber = N->DFSNumber;
1360       // Find the range of the node stack by walking down until we pass the
1361       // root DFS number.
1362       auto SCCNodes = make_range(
1363           PendingSCCStack.rbegin(),
1364           std::find_if(PendingSCCStack.rbegin(), PendingSCCStack.rend(),
1365                        [RootDFSNumber](Node *N) {
1366                          return N->DFSNumber < RootDFSNumber;
1367                        }));
1368       // Form a new SCC out of these nodes and then clear them off our pending
1369       // stack.
1370       RC.SCCs.push_back(createSCC(RC, SCCNodes));
1371       for (Node &N : *RC.SCCs.back()) {
1372         N.DFSNumber = N.LowLink = -1;
1373         SCCMap[&N] = RC.SCCs.back();
1374       }
1375       PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1376     } while (!DFSStack.empty());
1377   }
1378 
1379   // Wire up the SCC indices.
1380   for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1381     RC.SCCIndices[RC.SCCs[i]] = i;
1382 }
1383 
1384 // FIXME: We should move callers of this to embed the parent linking and leaf
1385 // tracking into their DFS in order to remove a full walk of all edges.
1386 void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1387   // Walk all edges in the RefSCC (this remains linear as we only do this once
1388   // when we build the RefSCC) to connect it to the parent sets of its
1389   // children.
1390   bool IsLeaf = true;
1391   for (SCC &C : RC)
1392     for (Node &N : C)
1393       for (Edge &E : N) {
1394         assert(E.getNode() &&
1395                "Cannot have a missing node in a visited part of the graph!");
1396         RefSCC &ChildRC = *lookupRefSCC(*E.getNode());
1397         if (&ChildRC == &RC)
1398           continue;
1399         ChildRC.Parents.insert(&RC);
1400         IsLeaf = false;
1401       }
1402 
1403   // For the SCCs where we fine no child SCCs, add them to the leaf list.
1404   if (IsLeaf)
1405     LeafRefSCCs.push_back(&RC);
1406 }
1407 
1408 LazyCallGraph::RefSCC *LazyCallGraph::getNextRefSCCInPostOrder() {
1409   if (DFSStack.empty()) {
1410     Node *N;
1411     do {
1412       // If we've handled all candidate entry nodes to the SCC forest, we're
1413       // done.
1414       if (RefSCCEntryNodes.empty())
1415         return nullptr;
1416 
1417       N = &get(*RefSCCEntryNodes.pop_back_val());
1418     } while (N->DFSNumber != 0);
1419 
1420     // Found a new root, begin the DFS here.
1421     N->LowLink = N->DFSNumber = 1;
1422     NextDFSNumber = 2;
1423     DFSStack.push_back({N, N->begin()});
1424   }
1425 
1426   for (;;) {
1427     Node *N;
1428     edge_iterator I;
1429     std::tie(N, I) = DFSStack.pop_back_val();
1430 
1431     assert(N->DFSNumber > 0 && "We should always assign a DFS number "
1432                                "before placing a node onto the stack.");
1433 
1434     auto E = N->end();
1435     while (I != E) {
1436       Node &ChildN = I->getNode(*this);
1437       if (ChildN.DFSNumber == 0) {
1438         // We haven't yet visited this child, so descend, pushing the current
1439         // node onto the stack.
1440         DFSStack.push_back({N, N->begin()});
1441 
1442         assert(!SCCMap.count(&ChildN) &&
1443                "Found a node with 0 DFS number but already in an SCC!");
1444         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1445         N = &ChildN;
1446         I = N->begin();
1447         E = N->end();
1448         continue;
1449       }
1450 
1451       // If the child has already been added to some child component, it
1452       // couldn't impact the low-link of this parent because it isn't
1453       // connected, and thus its low-link isn't relevant so skip it.
1454       if (ChildN.DFSNumber == -1) {
1455         ++I;
1456         continue;
1457       }
1458 
1459       // Track the lowest linked child as the lowest link for this node.
1460       assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1461       if (ChildN.LowLink < N->LowLink)
1462         N->LowLink = ChildN.LowLink;
1463 
1464       // Move to the next edge.
1465       ++I;
1466     }
1467 
1468     // We've finished processing N and its descendents, put it on our pending
1469     // SCC stack to eventually get merged into an SCC of nodes.
1470     PendingRefSCCStack.push_back(N);
1471 
1472     // If this node is linked to some lower entry, continue walking up the
1473     // stack.
1474     if (N->LowLink != N->DFSNumber) {
1475       assert(!DFSStack.empty() &&
1476              "We never found a viable root for an SCC to pop off!");
1477       continue;
1478     }
1479 
1480     // Otherwise, form a new RefSCC from the top of the pending node stack.
1481     int RootDFSNumber = N->DFSNumber;
1482     // Find the range of the node stack by walking down until we pass the
1483     // root DFS number.
1484     auto RefSCCNodes = node_stack_range(
1485         PendingRefSCCStack.rbegin(),
1486         std::find_if(
1487             PendingRefSCCStack.rbegin(), PendingRefSCCStack.rend(),
1488             [RootDFSNumber](Node *N) { return N->DFSNumber < RootDFSNumber; }));
1489     // Form a new RefSCC out of these nodes and then clear them off our pending
1490     // stack.
1491     RefSCC *NewRC = createRefSCC(*this);
1492     buildSCCs(*NewRC, RefSCCNodes);
1493     connectRefSCC(*NewRC);
1494     PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1495                              PendingRefSCCStack.end());
1496 
1497     // We return the new node here. This essentially suspends the DFS walk
1498     // until another RefSCC is requested.
1499     return NewRC;
1500   }
1501 }
1502 
1503 char LazyCallGraphAnalysis::PassID;
1504 
1505 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1506 
1507 static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
1508   OS << "  Edges in function: " << N.getFunction().getName() << "\n";
1509   for (const LazyCallGraph::Edge &E : N)
1510     OS << "    " << (E.isCall() ? "call" : "ref ") << " -> "
1511        << E.getFunction().getName() << "\n";
1512 
1513   OS << "\n";
1514 }
1515 
1516 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1517   ptrdiff_t Size = std::distance(C.begin(), C.end());
1518   OS << "    SCC with " << Size << " functions:\n";
1519 
1520   for (LazyCallGraph::Node &N : C)
1521     OS << "      " << N.getFunction().getName() << "\n";
1522 }
1523 
1524 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1525   ptrdiff_t Size = std::distance(C.begin(), C.end());
1526   OS << "  RefSCC with " << Size << " call SCCs:\n";
1527 
1528   for (LazyCallGraph::SCC &InnerC : C)
1529     printSCC(OS, InnerC);
1530 
1531   OS << "\n";
1532 }
1533 
1534 PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
1535                                                 ModuleAnalysisManager &AM) {
1536   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1537 
1538   OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1539      << "\n\n";
1540 
1541   for (Function &F : M)
1542     printNode(OS, G.get(F));
1543 
1544   for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1545     printRefSCC(OS, C);
1546 
1547   return PreservedAnalyses::all();
1548 }
1549 
1550 LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1551     : OS(OS) {}
1552 
1553 static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1554   std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1555 
1556   for (const LazyCallGraph::Edge &E : N) {
1557     OS << "  " << Name << " -> \""
1558        << DOT::EscapeString(E.getFunction().getName()) << "\"";
1559     if (!E.isCall()) // It is a ref edge.
1560       OS << " [style=dashed,label=\"ref\"]";
1561     OS << ";\n";
1562   }
1563 
1564   OS << "\n";
1565 }
1566 
1567 PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1568                                                    ModuleAnalysisManager &AM) {
1569   LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1570 
1571   OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1572 
1573   for (Function &F : M)
1574     printNodeDOT(OS, G.get(F));
1575 
1576   OS << "}\n";
1577 
1578   return PreservedAnalyses::all();
1579 }
1580