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