1 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Analysis/LazyCallGraph.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/ScopeExit.h"
13 #include "llvm/ADT/Sequence.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"
24 #define DEBUG_TYPE "lcg"
26 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
28 EdgeIndexMap.insert({&TargetN, Edges.size()});
29 Edges.emplace_back(TargetN, EK);
32 void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
33 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
36 bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
37 auto IndexMapI = EdgeIndexMap.find(&TargetN);
38 if (IndexMapI == EdgeIndexMap.end())
41 Edges[IndexMapI->second] = Edge();
42 EdgeIndexMap.erase(IndexMapI);
46 static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
47 DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
48 LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
49 if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
52 DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n");
53 Edges.emplace_back(LazyCallGraph::Edge(N, EK));
56 LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
57 assert(!Edges && "Must not have already populated the edges for this node!");
59 DEBUG(dbgs() << " Adding functions called by '" << getName()
60 << "' to the graph.\n");
62 Edges = EdgeSequence();
64 SmallVector<Constant *, 16> Worklist;
65 SmallPtrSet<Function *, 4> Callees;
66 SmallPtrSet<Constant *, 16> Visited;
68 // Find all the potential call graph edges in this function. We track both
69 // actual call edges and indirect references to functions. The direct calls
70 // are trivially added, but to accumulate the latter we walk the instructions
71 // and add every operand which is a constant to the worklist to process
74 // Note that we consider *any* function with a definition to be a viable
75 // edge. Even if the function's definition is subject to replacement by
76 // some other module (say, a weak definition) there may still be
77 // optimizations which essentially speculate based on the definition and
78 // a way to check that the specific definition is in fact the one being
79 // used. For example, this could be done by moving the weak definition to
80 // a strong (internal) definition and making the weak definition be an
81 // alias. Then a test of the address of the weak function against the new
82 // strong definition's address would be an effective way to determine the
83 // safety of optimizing a direct call edge.
84 for (BasicBlock &BB : *F)
85 for (Instruction &I : BB) {
86 if (auto CS = CallSite(&I))
87 if (Function *Callee = CS.getCalledFunction())
88 if (!Callee->isDeclaration())
89 if (Callees.insert(Callee).second) {
90 Visited.insert(Callee);
91 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
92 LazyCallGraph::Edge::Call);
95 for (Value *Op : I.operand_values())
96 if (Constant *C = dyn_cast<Constant>(Op))
97 if (Visited.insert(C).second)
98 Worklist.push_back(C);
101 // We've collected all the constant (and thus potentially function or
102 // function containing) operands to all of the instructions in the function.
103 // Process them (recursively) collecting every function found.
104 visitReferences(Worklist, Visited, [&](Function &F) {
105 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
106 LazyCallGraph::Edge::Ref);
112 void LazyCallGraph::Node::replaceFunction(Function &NewF) {
113 assert(F != &NewF && "Must not replace a function with itself!");
117 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
118 LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
119 dbgs() << *this << '\n';
123 LazyCallGraph::LazyCallGraph(Module &M) {
124 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
126 for (Function &F : M)
127 if (!F.isDeclaration() && !F.hasLocalLinkage()) {
128 DEBUG(dbgs() << " Adding '" << F.getName()
129 << "' to entry set of the graph.\n");
130 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
133 // Now add entry nodes for functions reachable via initializers to globals.
134 SmallVector<Constant *, 16> Worklist;
135 SmallPtrSet<Constant *, 16> Visited;
136 for (GlobalVariable &GV : M.globals())
137 if (GV.hasInitializer())
138 if (Visited.insert(GV.getInitializer()).second)
139 Worklist.push_back(GV.getInitializer());
141 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
143 visitReferences(Worklist, Visited, [&](Function &F) {
144 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
145 LazyCallGraph::Edge::Ref);
149 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
150 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
151 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
152 SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)) {
156 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
157 BPA = std::move(G.BPA);
158 NodeMap = std::move(G.NodeMap);
159 EntryEdges = std::move(G.EntryEdges);
160 SCCBPA = std::move(G.SCCBPA);
161 SCCMap = std::move(G.SCCMap);
162 LeafRefSCCs = std::move(G.LeafRefSCCs);
167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
168 LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
169 dbgs() << *this << '\n';
174 void LazyCallGraph::SCC::verify() {
175 assert(OuterRefSCC && "Can't have a null RefSCC!");
176 assert(!Nodes.empty() && "Can't have an empty SCC!");
178 for (Node *N : Nodes) {
179 assert(N && "Can't have a null node!");
180 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
181 "Node does not map to this SCC!");
182 assert(N->DFSNumber == -1 &&
183 "Must set DFS numbers to -1 when adding a node to an SCC!");
184 assert(N->LowLink == -1 &&
185 "Must set low link to -1 when adding a node to an SCC!");
187 assert(E.getNode() && "Can't have an unpopulated node!");
192 bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
196 for (Node &N : *this)
197 for (Edge &E : N->calls())
198 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
205 bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
206 if (this == &TargetC)
209 LazyCallGraph &G = *OuterRefSCC->G;
211 // Start with this SCC.
212 SmallPtrSet<const SCC *, 16> Visited = {this};
213 SmallVector<const SCC *, 16> Worklist = {this};
215 // Walk down the graph until we run out of edges or find a path to TargetC.
217 const SCC &C = *Worklist.pop_back_val();
219 for (Edge &E : N->calls()) {
220 SCC *CalleeC = G.lookupSCC(E.getNode());
224 // If the callee's SCC is the TargetC, we're done.
225 if (CalleeC == &TargetC)
228 // If this is the first time we've reached this SCC, put it on the
229 // worklist to recurse through.
230 if (Visited.insert(CalleeC).second)
231 Worklist.push_back(CalleeC);
233 } while (!Worklist.empty());
239 LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
241 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
242 LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
243 dbgs() << *this << '\n';
248 void LazyCallGraph::RefSCC::verify() {
249 assert(G && "Can't have a null graph!");
250 assert(!SCCs.empty() && "Can't have an empty SCC!");
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!");
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 auto IndexIt = SCCIndices.find(C);
262 assert(IndexIt != SCCIndices.end() &&
263 "Found an SCC that doesn't have an index!");
266 // Check that our indices map correctly.
267 for (auto &SCCIndexPair : SCCIndices) {
268 SCC *C = SCCIndexPair.first;
269 int i = SCCIndexPair.second;
270 assert(C && "Can't have a null SCC in the indices!");
271 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
272 assert(SCCs[i] == C && "Index doesn't point to SCC!");
275 // Check that the SCCs are in fact in post-order.
276 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
277 SCC &SourceSCC = *SCCs[i];
278 for (Node &N : SourceSCC)
282 SCC &TargetSCC = *G->lookupSCC(E.getNode());
283 if (&TargetSCC.getOuterRefSCC() == this) {
284 assert(SCCIndices.find(&TargetSCC)->second <= i &&
285 "Edge between SCCs violates post-order relationship.");
288 assert(TargetSCC.getOuterRefSCC().Parents.count(this) &&
289 "Edge to a RefSCC missing us in its parent set.");
293 // Check that our parents are actually parents.
294 for (RefSCC *ParentRC : Parents) {
295 assert(ParentRC != this && "Cannot be our own parent!");
296 auto HasConnectingEdge = [&] {
297 for (SCC &C : *ParentRC)
300 if (G->lookupRefSCC(E.getNode()) == this)
304 assert(HasConnectingEdge() && "No edge connects the parent to us!");
309 bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const {
310 // Walk up the parents of this SCC and verify that we eventually find C.
311 SmallVector<const RefSCC *, 4> AncestorWorklist;
312 AncestorWorklist.push_back(this);
314 const RefSCC *AncestorC = AncestorWorklist.pop_back_val();
315 if (AncestorC->isChildOf(C))
317 for (const RefSCC *ParentC : AncestorC->Parents)
318 AncestorWorklist.push_back(ParentC);
319 } while (!AncestorWorklist.empty());
324 /// Generic helper that updates a postorder sequence of SCCs for a potentially
325 /// cycle-introducing edge insertion.
327 /// A postorder sequence of SCCs of a directed graph has one fundamental
328 /// property: all deges in the DAG of SCCs point "up" the sequence. That is,
329 /// all edges in the SCC DAG point to prior SCCs in the sequence.
331 /// This routine both updates a postorder sequence and uses that sequence to
332 /// compute the set of SCCs connected into a cycle. It should only be called to
333 /// insert a "downward" edge which will require changing the sequence to
334 /// restore it to a postorder.
336 /// When inserting an edge from an earlier SCC to a later SCC in some postorder
337 /// sequence, all of the SCCs which may be impacted are in the closed range of
338 /// those two within the postorder sequence. The algorithm used here to restore
339 /// the state is as follows:
341 /// 1) Starting from the source SCC, construct a set of SCCs which reach the
342 /// source SCC consisting of just the source SCC. Then scan toward the
343 /// target SCC in postorder and for each SCC, if it has an edge to an SCC
344 /// in the set, add it to the set. Otherwise, the source SCC is not
345 /// a successor, move it in the postorder sequence to immediately before
346 /// the source SCC, shifting the source SCC and all SCCs in the set one
347 /// position toward the target SCC. Stop scanning after processing the
349 /// 2) If the source SCC is now past the target SCC in the postorder sequence,
350 /// and thus the new edge will flow toward the start, we are done.
351 /// 3) Otherwise, starting from the target SCC, walk all edges which reach an
352 /// SCC between the source and the target, and add them to the set of
353 /// connected SCCs, then recurse through them. Once a complete set of the
354 /// SCCs the target connects to is known, hoist the remaining SCCs between
355 /// the source and the target to be above the target. Note that there is no
356 /// need to process the source SCC, it is already known to connect.
357 /// 4) At this point, all of the SCCs in the closed range between the source
358 /// SCC and the target SCC in the postorder sequence are connected,
359 /// including the target SCC and the source SCC. Inserting the edge from
360 /// the source SCC to the target SCC will form a cycle out of precisely
361 /// these SCCs. Thus we can merge all of the SCCs in this closed range into
364 /// This process has various important properties:
365 /// - Only mutates the SCCs when adding the edge actually changes the SCC
367 /// - Never mutates SCCs which are unaffected by the change.
368 /// - Updates the postorder sequence to correctly satisfy the postorder
369 /// constraint after the edge is inserted.
370 /// - Only reorders SCCs in the closed postorder sequence from the source to
371 /// the target, so easy to bound how much has changed even in the ordering.
372 /// - Big-O is the number of edges in the closed postorder range of SCCs from
373 /// source to target.
375 /// This helper routine, in addition to updating the postorder sequence itself
376 /// will also update a map from SCCs to indices within that sequecne.
378 /// The sequence and the map must operate on pointers to the SCC type.
380 /// Two callbacks must be provided. The first computes the subset of SCCs in
381 /// the postorder closed range from the source to the target which connect to
382 /// the source SCC via some (transitive) set of edges. The second computes the
383 /// subset of the same range which the target SCC connects to via some
384 /// (transitive) set of edges. Both callbacks should populate the set argument
386 template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
387 typename ComputeSourceConnectedSetCallableT,
388 typename ComputeTargetConnectedSetCallableT>
389 static iterator_range<typename PostorderSequenceT::iterator>
390 updatePostorderSequenceForEdgeInsertion(
391 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
392 SCCIndexMapT &SCCIndices,
393 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
394 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
395 int SourceIdx = SCCIndices[&SourceSCC];
396 int TargetIdx = SCCIndices[&TargetSCC];
397 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
399 SmallPtrSet<SCCT *, 4> ConnectedSet;
401 // Compute the SCCs which (transitively) reach the source.
402 ComputeSourceConnectedSet(ConnectedSet);
404 // Partition the SCCs in this part of the port-order sequence so only SCCs
405 // connecting to the source remain between it and the target. This is
406 // a benign partition as it preserves postorder.
407 auto SourceI = std::stable_partition(
408 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
409 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
410 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
411 SCCIndices.find(SCCs[i])->second = i;
413 // If the target doesn't connect to the source, then we've corrected the
414 // post-order and there are no cycles formed.
415 if (!ConnectedSet.count(&TargetSCC)) {
416 assert(SourceI > (SCCs.begin() + SourceIdx) &&
417 "Must have moved the source to fix the post-order.");
418 assert(*std::prev(SourceI) == &TargetSCC &&
419 "Last SCC to move should have bene the target.");
421 // Return an empty range at the target SCC indicating there is nothing to
423 return make_range(std::prev(SourceI), std::prev(SourceI));
426 assert(SCCs[TargetIdx] == &TargetSCC &&
427 "Should not have moved target if connected!");
428 SourceIdx = SourceI - SCCs.begin();
429 assert(SCCs[SourceIdx] == &SourceSCC &&
430 "Bad updated index computation for the source SCC!");
433 // See whether there are any remaining intervening SCCs between the source
434 // and target. If so we need to make sure they all are reachable form the
436 if (SourceIdx + 1 < TargetIdx) {
437 ConnectedSet.clear();
438 ComputeTargetConnectedSet(ConnectedSet);
440 // Partition SCCs so that only SCCs reached from the target remain between
441 // the source and the target. This preserves postorder.
442 auto TargetI = std::stable_partition(
443 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
444 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
445 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
446 SCCIndices.find(SCCs[i])->second = i;
447 TargetIdx = std::prev(TargetI) - SCCs.begin();
448 assert(SCCs[TargetIdx] == &TargetSCC &&
449 "Should always end with the target!");
452 // At this point, we know that connecting source to target forms a cycle
453 // because target connects back to source, and we know that all of the SCCs
454 // between the source and target in the postorder sequence participate in that
456 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
460 LazyCallGraph::RefSCC::switchInternalEdgeToCall(
461 Node &SourceN, Node &TargetN,
462 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
463 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
464 SmallVector<SCC *, 1> DeletedSCCs;
467 // In a debug build, verify the RefSCC is valid to start with and when this
470 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
473 SCC &SourceSCC = *G->lookupSCC(SourceN);
474 SCC &TargetSCC = *G->lookupSCC(TargetN);
476 // If the two nodes are already part of the same SCC, we're also done as
477 // we've just added more connectivity.
478 if (&SourceSCC == &TargetSCC) {
479 SourceN->setEdgeKind(TargetN, Edge::Call);
480 return false; // No new cycle.
483 // At this point we leverage the postorder list of SCCs to detect when the
484 // insertion of an edge changes the SCC structure in any way.
486 // First and foremost, we can eliminate the need for any changes when the
487 // edge is toward the beginning of the postorder sequence because all edges
488 // flow in that direction already. Thus adding a new one cannot form a cycle.
489 int SourceIdx = SCCIndices[&SourceSCC];
490 int TargetIdx = SCCIndices[&TargetSCC];
491 if (TargetIdx < SourceIdx) {
492 SourceN->setEdgeKind(TargetN, Edge::Call);
493 return false; // No new cycle.
496 // Compute the SCCs which (transitively) reach the source.
497 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
499 // Check that the RefSCC is still valid before computing this as the
500 // results will be nonsensical of we've broken its invariants.
503 ConnectedSet.insert(&SourceSCC);
504 auto IsConnected = [&](SCC &C) {
506 for (Edge &E : N->calls())
507 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
514 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
516 ConnectedSet.insert(C);
519 // Use a normal worklist to find which SCCs the target connects to. We still
520 // bound the search based on the range in the postorder list we care about,
521 // but because this is forward connectivity we just "recurse" through the
523 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
525 // Check that the RefSCC is still valid before computing this as the
526 // results will be nonsensical of we've broken its invariants.
529 ConnectedSet.insert(&TargetSCC);
530 SmallVector<SCC *, 4> Worklist;
531 Worklist.push_back(&TargetSCC);
533 SCC &C = *Worklist.pop_back_val();
538 SCC &EdgeC = *G->lookupSCC(E.getNode());
539 if (&EdgeC.getOuterRefSCC() != this)
540 // Not in this RefSCC...
542 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
543 // Not in the postorder sequence between source and target.
546 if (ConnectedSet.insert(&EdgeC).second)
547 Worklist.push_back(&EdgeC);
549 } while (!Worklist.empty());
552 // Use a generic helper to update the postorder sequence of SCCs and return
553 // a range of any SCCs connected into a cycle by inserting this edge. This
554 // routine will also take care of updating the indices into the postorder
556 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
557 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
558 ComputeTargetConnectedSet);
560 // Run the user's callback on the merged SCCs before we actually merge them.
562 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
564 // If the merge range is empty, then adding the edge didn't actually form any
565 // new cycles. We're done.
566 if (MergeRange.begin() == MergeRange.end()) {
567 // Now that the SCC structure is finalized, flip the kind to call.
568 SourceN->setEdgeKind(TargetN, Edge::Call);
569 return false; // No new cycle.
573 // Before merging, check that the RefSCC remains valid after all the
574 // postorder updates.
578 // Otherwise we need to merge all of the SCCs in the cycle into a single
581 // NB: We merge into the target because all of these functions were already
582 // reachable from the target, meaning any SCC-wide properties deduced about it
583 // other than the set of functions within it will not have changed.
584 for (SCC *C : MergeRange) {
585 assert(C != &TargetSCC &&
586 "We merge *into* the target and shouldn't process it here!");
588 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
589 for (Node *N : C->Nodes)
590 G->SCCMap[N] = &TargetSCC;
592 DeletedSCCs.push_back(C);
595 // Erase the merged SCCs from the list and update the indices of the
597 int IndexOffset = MergeRange.end() - MergeRange.begin();
598 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
599 for (SCC *C : make_range(EraseEnd, SCCs.end()))
600 SCCIndices[C] -= IndexOffset;
602 // Now that the SCC structure is finalized, flip the kind to call.
603 SourceN->setEdgeKind(TargetN, Edge::Call);
605 // And we're done, but we did form a new cycle.
609 void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
611 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
614 // In a debug build, verify the RefSCC is valid to start with and when this
617 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
620 assert(G->lookupRefSCC(SourceN) == this &&
621 "Source must be in this RefSCC.");
622 assert(G->lookupRefSCC(TargetN) == this &&
623 "Target must be in this RefSCC.");
624 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
625 "Source and Target must be in separate SCCs for this to be trivial!");
627 // Set the edge kind.
628 SourceN->setEdgeKind(TargetN, Edge::Ref);
631 iterator_range<LazyCallGraph::RefSCC::iterator>
632 LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
633 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
636 // In a debug build, verify the RefSCC is valid to start with and when this
639 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
642 assert(G->lookupRefSCC(SourceN) == this &&
643 "Source must be in this RefSCC.");
644 assert(G->lookupRefSCC(TargetN) == this &&
645 "Target must be in this RefSCC.");
647 SCC &TargetSCC = *G->lookupSCC(TargetN);
648 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
649 "the same SCC to require the "
652 // Set the edge kind.
653 SourceN->setEdgeKind(TargetN, Edge::Ref);
655 // Otherwise we are removing a call edge from a single SCC. This may break
656 // the cycle. In order to compute the new set of SCCs, we need to do a small
657 // DFS over the nodes within the SCC to form any sub-cycles that remain as
658 // distinct SCCs and compute a postorder over the resulting SCCs.
660 // However, we specially handle the target node. The target node is known to
661 // reach all other nodes in the original SCC by definition. This means that
662 // we want the old SCC to be replaced with an SCC contaning that node as it
663 // will be the root of whatever SCC DAG results from the DFS. Assumptions
664 // about an SCC such as the set of functions called will continue to hold,
667 SCC &OldSCC = TargetSCC;
668 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
669 SmallVector<Node *, 16> PendingSCCStack;
670 SmallVector<SCC *, 4> NewSCCs;
672 // Prepare the nodes for a fresh DFS.
673 SmallVector<Node *, 16> Worklist;
674 Worklist.swap(OldSCC.Nodes);
675 for (Node *N : Worklist) {
676 N->DFSNumber = N->LowLink = 0;
680 // Force the target node to be in the old SCC. This also enables us to take
681 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
682 // below: whenever we build an edge that reaches the target node, we know
683 // that the target node eventually connects back to all other nodes in our
684 // walk. As a consequence, we can detect and handle participants in that
685 // cycle without walking all the edges that form this connection, and instead
686 // by relying on the fundamental guarantee coming into this operation (all
687 // nodes are reachable from the target due to previously forming an SCC).
688 TargetN.DFSNumber = TargetN.LowLink = -1;
689 OldSCC.Nodes.push_back(&TargetN);
690 G->SCCMap[&TargetN] = &OldSCC;
692 // Scan down the stack and DFS across the call edges.
693 for (Node *RootN : Worklist) {
694 assert(DFSStack.empty() &&
695 "Cannot begin a new root with a non-empty DFS stack!");
696 assert(PendingSCCStack.empty() &&
697 "Cannot begin a new root with pending nodes for an SCC!");
699 // Skip any nodes we've already reached in the DFS.
700 if (RootN->DFSNumber != 0) {
701 assert(RootN->DFSNumber == -1 &&
702 "Shouldn't have any mid-DFS root nodes!");
706 RootN->DFSNumber = RootN->LowLink = 1;
707 int NextDFSNumber = 2;
709 DFSStack.push_back({RootN, (*RootN)->call_begin()});
712 EdgeSequence::call_iterator I;
713 std::tie(N, I) = DFSStack.pop_back_val();
714 auto E = (*N)->call_end();
716 Node &ChildN = I->getNode();
717 if (ChildN.DFSNumber == 0) {
718 // We haven't yet visited this child, so descend, pushing the current
719 // node onto the stack.
720 DFSStack.push_back({N, I});
722 assert(!G->SCCMap.count(&ChildN) &&
723 "Found a node with 0 DFS number but already in an SCC!");
724 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
726 I = (*N)->call_begin();
727 E = (*N)->call_end();
731 // Check for the child already being part of some component.
732 if (ChildN.DFSNumber == -1) {
733 if (G->lookupSCC(ChildN) == &OldSCC) {
734 // If the child is part of the old SCC, we know that it can reach
735 // every other node, so we have formed a cycle. Pull the entire DFS
736 // and pending stacks into it. See the comment above about setting
737 // up the old SCC for why we do this.
738 int OldSize = OldSCC.size();
739 OldSCC.Nodes.push_back(N);
740 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
741 PendingSCCStack.clear();
742 while (!DFSStack.empty())
743 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
744 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
745 N.DFSNumber = N.LowLink = -1;
746 G->SCCMap[&N] = &OldSCC;
752 // If the child has already been added to some child component, it
753 // couldn't impact the low-link of this parent because it isn't
754 // connected, and thus its low-link isn't relevant so skip it.
759 // Track the lowest linked child as the lowest link for this node.
760 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
761 if (ChildN.LowLink < N->LowLink)
762 N->LowLink = ChildN.LowLink;
764 // Move to the next edge.
768 // Cleared the DFS early, start another round.
771 // We've finished processing N and its descendents, put it on our pending
772 // SCC stack to eventually get merged into an SCC of nodes.
773 PendingSCCStack.push_back(N);
775 // If this node is linked to some lower entry, continue walking up the
777 if (N->LowLink != N->DFSNumber)
780 // Otherwise, we've completed an SCC. Append it to our post order list of
782 int RootDFSNumber = N->DFSNumber;
783 // Find the range of the node stack by walking down until we pass the
785 auto SCCNodes = make_range(
786 PendingSCCStack.rbegin(),
787 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
788 return N->DFSNumber < RootDFSNumber;
791 // Form a new SCC out of these nodes and then clear them off our pending
793 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
794 for (Node &N : *NewSCCs.back()) {
795 N.DFSNumber = N.LowLink = -1;
796 G->SCCMap[&N] = NewSCCs.back();
798 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
799 } while (!DFSStack.empty());
802 // Insert the remaining SCCs before the old one. The old SCC can reach all
803 // other SCCs we form because it contains the target node of the removed edge
804 // of the old SCC. This means that we will have edges into all of the new
805 // SCCs, which means the old one must come last for postorder.
806 int OldIdx = SCCIndices[&OldSCC];
807 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
809 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
810 // old SCC from the mapping.
811 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
812 SCCIndices[SCCs[Idx]] = Idx;
814 return make_range(SCCs.begin() + OldIdx,
815 SCCs.begin() + OldIdx + NewSCCs.size());
818 void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
820 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
822 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
823 assert(G->lookupRefSCC(TargetN) != this &&
824 "Target must not be in this RefSCC.");
825 #ifdef EXPENSIVE_CHECKS
826 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
827 "Target must be a descendant of the Source.");
830 // Edges between RefSCCs are the same regardless of call or ref, so we can
831 // just flip the edge here.
832 SourceN->setEdgeKind(TargetN, Edge::Call);
835 // Check that the RefSCC is still valid.
840 void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
842 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
844 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
845 assert(G->lookupRefSCC(TargetN) != this &&
846 "Target must not be in this RefSCC.");
847 #ifdef EXPENSIVE_CHECKS
848 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
849 "Target must be a descendant of the Source.");
852 // Edges between RefSCCs are the same regardless of call or ref, so we can
853 // just flip the edge here.
854 SourceN->setEdgeKind(TargetN, Edge::Ref);
857 // Check that the RefSCC is still valid.
862 void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
864 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
865 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
867 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
870 // Check that the RefSCC is still valid.
875 void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
877 // First insert it into the caller.
878 SourceN->insertEdgeInternal(TargetN, EK);
880 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
882 RefSCC &TargetC = *G->lookupRefSCC(TargetN);
883 assert(&TargetC != this && "Target must not be in this RefSCC.");
884 #ifdef EXPENSIVE_CHECKS
885 assert(TargetC.isDescendantOf(*this) &&
886 "Target must be a descendant of the Source.");
889 // The only change required is to add this SCC to the parent set of the
891 TargetC.Parents.insert(this);
894 // Check that the RefSCC is still valid.
899 SmallVector<LazyCallGraph::RefSCC *, 1>
900 LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
901 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
902 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
903 assert(&SourceC != this && "Source must not be in this RefSCC.");
904 #ifdef EXPENSIVE_CHECKS
905 assert(SourceC.isDescendantOf(*this) &&
906 "Source must be a descendant of the Target.");
909 SmallVector<RefSCC *, 1> DeletedRefSCCs;
912 // In a debug build, verify the RefSCC is valid to start with and when this
915 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
918 int SourceIdx = G->RefSCCIndices[&SourceC];
919 int TargetIdx = G->RefSCCIndices[this];
920 assert(SourceIdx < TargetIdx &&
921 "Postorder list doesn't see edge as incoming!");
923 // Compute the RefSCCs which (transitively) reach the source. We do this by
924 // working backwards from the source using the parent set in each RefSCC,
925 // skipping any RefSCCs that don't fall in the postorder range. This has the
926 // advantage of walking the sparser parent edge (in high fan-out graphs) but
927 // more importantly this removes examining all forward edges in all RefSCCs
928 // within the postorder range which aren't in fact connected. Only connected
929 // RefSCCs (and their edges) are visited here.
930 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
931 Set.insert(&SourceC);
932 SmallVector<RefSCC *, 4> Worklist;
933 Worklist.push_back(&SourceC);
935 RefSCC &RC = *Worklist.pop_back_val();
936 for (RefSCC &ParentRC : RC.parents()) {
937 // Skip any RefSCCs outside the range of source to target in the
938 // postorder sequence.
939 int ParentIdx = G->getRefSCCIndex(ParentRC);
940 assert(ParentIdx > SourceIdx && "Parent cannot precede source in postorder!");
941 if (ParentIdx > TargetIdx)
943 if (Set.insert(&ParentRC).second)
944 // First edge connecting to this parent, add it to our worklist.
945 Worklist.push_back(&ParentRC);
947 } while (!Worklist.empty());
950 // Use a normal worklist to find which SCCs the target connects to. We still
951 // bound the search based on the range in the postorder list we care about,
952 // but because this is forward connectivity we just "recurse" through the
954 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
956 SmallVector<RefSCC *, 4> Worklist;
957 Worklist.push_back(this);
959 RefSCC &RC = *Worklist.pop_back_val();
963 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
964 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
965 // Not in the postorder sequence between source and target.
968 if (Set.insert(&EdgeRC).second)
969 Worklist.push_back(&EdgeRC);
971 } while (!Worklist.empty());
974 // Use a generic helper to update the postorder sequence of RefSCCs and return
975 // a range of any RefSCCs connected into a cycle by inserting this edge. This
976 // routine will also take care of updating the indices into the postorder
978 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
979 updatePostorderSequenceForEdgeInsertion(
980 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
981 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
983 // Build a set so we can do fast tests for whether a RefSCC will end up as
984 // part of the merged RefSCC.
985 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
987 // This RefSCC will always be part of that set, so just insert it here.
988 MergeSet.insert(this);
990 // Now that we have identified all of the SCCs which need to be merged into
991 // a connected set with the inserted edge, merge all of them into this SCC.
992 SmallVector<SCC *, 16> MergedSCCs;
994 for (RefSCC *RC : MergeRange) {
995 assert(RC != this && "We're merging into the target RefSCC, so it "
996 "shouldn't be in the range.");
998 // Merge the parents which aren't part of the merge into the our parents.
999 for (RefSCC *ParentRC : RC->Parents)
1000 if (!MergeSet.count(ParentRC))
1001 Parents.insert(ParentRC);
1002 RC->Parents.clear();
1004 // Walk the inner SCCs to update their up-pointer and walk all the edges to
1005 // update any parent sets.
1006 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1007 // walk by updating the parent sets in some other manner.
1008 for (SCC &InnerC : *RC) {
1009 InnerC.OuterRefSCC = this;
1010 SCCIndices[&InnerC] = SCCIndex++;
1011 for (Node &N : InnerC) {
1012 G->SCCMap[&N] = &InnerC;
1013 for (Edge &E : *N) {
1014 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
1015 if (MergeSet.count(&ChildRC))
1017 ChildRC.Parents.erase(RC);
1018 ChildRC.Parents.insert(this);
1023 // Now merge in the SCCs. We can actually move here so try to reuse storage
1024 // the first time through.
1025 if (MergedSCCs.empty())
1026 MergedSCCs = std::move(RC->SCCs);
1028 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1030 DeletedRefSCCs.push_back(RC);
1033 // Append our original SCCs to the merged list and move it into place.
1034 for (SCC &InnerC : *this)
1035 SCCIndices[&InnerC] = SCCIndex++;
1036 MergedSCCs.append(SCCs.begin(), SCCs.end());
1037 SCCs = std::move(MergedSCCs);
1039 // Remove the merged away RefSCCs from the post order sequence.
1040 for (RefSCC *RC : MergeRange)
1041 G->RefSCCIndices.erase(RC);
1042 int IndexOffset = MergeRange.end() - MergeRange.begin();
1044 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1045 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1046 G->RefSCCIndices[RC] -= IndexOffset;
1048 // At this point we have a merged RefSCC with a post-order SCCs list, just
1049 // connect the nodes to form the new edge.
1050 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
1052 // We return the list of SCCs which were merged so that callers can
1053 // invalidate any data they have associated with those SCCs. Note that these
1054 // SCCs are no longer in an interesting state (they are totally empty) but
1055 // the pointers will remain stable for the life of the graph itself.
1056 return DeletedRefSCCs;
1059 void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1060 assert(G->lookupRefSCC(SourceN) == this &&
1061 "The source must be a member of this RefSCC.");
1063 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1064 assert(&TargetRC != this && "The target must not be a member of this RefSCC");
1066 assert(!is_contained(G->LeafRefSCCs, this) &&
1067 "Cannot have a leaf RefSCC source.");
1070 // In a debug build, verify the RefSCC is valid to start with and when this
1071 // routine finishes.
1073 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1076 // First remove it from the node.
1077 bool Removed = SourceN->removeEdgeInternal(TargetN);
1079 assert(Removed && "Target not in the edge set for this caller?");
1081 bool HasOtherEdgeToChildRC = false;
1082 bool HasOtherChildRC = false;
1083 for (SCC *InnerC : SCCs) {
1084 for (Node &N : *InnerC) {
1085 for (Edge &E : *N) {
1086 RefSCC &OtherChildRC = *G->lookupRefSCC(E.getNode());
1087 if (&OtherChildRC == &TargetRC) {
1088 HasOtherEdgeToChildRC = true;
1091 if (&OtherChildRC != this)
1092 HasOtherChildRC = true;
1094 if (HasOtherEdgeToChildRC)
1097 if (HasOtherEdgeToChildRC)
1100 // Because the SCCs form a DAG, deleting such an edge cannot change the set
1101 // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
1102 // the source SCC no longer connected to the target SCC. If so, we need to
1103 // update the target SCC's map of its parents.
1104 if (!HasOtherEdgeToChildRC) {
1105 bool Removed = TargetRC.Parents.erase(this);
1108 "Did not find the source SCC in the target SCC's parent list!");
1110 // It may orphan an SCC if it is the last edge reaching it, but that does
1111 // not violate any invariants of the graph.
1112 if (TargetRC.Parents.empty())
1113 DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName()
1114 << " -> " << TargetN.getFunction().getName()
1115 << " edge orphaned the callee's SCC!\n");
1117 // It may make the Source SCC a leaf SCC.
1118 if (!HasOtherChildRC)
1119 G->LeafRefSCCs.push_back(this);
1123 SmallVector<LazyCallGraph::RefSCC *, 1>
1124 LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
1125 assert(!(*SourceN)[TargetN].isCall() &&
1126 "Cannot remove a call edge, it must first be made a ref edge");
1129 // In a debug build, verify the RefSCC is valid to start with and when this
1130 // routine finishes.
1132 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1135 // First remove the actual edge.
1136 bool Removed = SourceN->removeEdgeInternal(TargetN);
1138 assert(Removed && "Target not in the edge set for this caller?");
1140 // We return a list of the resulting *new* RefSCCs in post-order.
1141 SmallVector<RefSCC *, 1> Result;
1143 // Direct recursion doesn't impact the SCC graph at all.
1144 if (&SourceN == &TargetN)
1147 // If this ref edge is within an SCC then there are sufficient other edges to
1148 // form a cycle without this edge so removing it is a no-op.
1149 SCC &SourceC = *G->lookupSCC(SourceN);
1150 SCC &TargetC = *G->lookupSCC(TargetN);
1151 if (&SourceC == &TargetC)
1154 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
1155 // for each inner SCC. We also store these associated with *nodes* rather
1156 // than SCCs because this saves a round-trip through the node->SCC map and in
1157 // the common case, SCCs are small. We will verify that we always give the
1158 // same number to every node in the SCC such that these are equivalent.
1159 const int RootPostOrderNumber = 0;
1160 int PostOrderNumber = RootPostOrderNumber + 1;
1161 SmallDenseMap<Node *, int> PostOrderMapping;
1163 // Every node in the target SCC can already reach every node in this RefSCC
1164 // (by definition). It is the only node we know will stay inside this RefSCC.
1165 // Everything which transitively reaches Target will also remain in the
1166 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
1167 // back to the root post order number.
1169 // This also enables us to take a very significant short-cut in the standard
1170 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
1171 // references the target node, we know that the target node eventually
1172 // references all other nodes in our walk. As a consequence, we can detect
1173 // and handle participants in that cycle without walking all the edges that
1174 // form the connections, and instead by relying on the fundamental guarantee
1175 // coming into this operation.
1176 for (Node &N : TargetC)
1177 PostOrderMapping[&N] = RootPostOrderNumber;
1179 // Reset all the other nodes to prepare for a DFS over them, and add them to
1181 SmallVector<Node *, 8> Worklist;
1182 for (SCC *C : SCCs) {
1187 N.DFSNumber = N.LowLink = 0;
1189 Worklist.append(C->Nodes.begin(), C->Nodes.end());
1192 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1193 N.DFSNumber = N.LowLink = -1;
1194 PostOrderMapping[&N] = Number;
1197 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
1198 SmallVector<Node *, 4> PendingRefSCCStack;
1200 assert(DFSStack.empty() &&
1201 "Cannot begin a new root with a non-empty DFS stack!");
1202 assert(PendingRefSCCStack.empty() &&
1203 "Cannot begin a new root with pending nodes for an SCC!");
1205 Node *RootN = Worklist.pop_back_val();
1206 // Skip any nodes we've already reached in the DFS.
1207 if (RootN->DFSNumber != 0) {
1208 assert(RootN->DFSNumber == -1 &&
1209 "Shouldn't have any mid-DFS root nodes!");
1213 RootN->DFSNumber = RootN->LowLink = 1;
1214 int NextDFSNumber = 2;
1216 DFSStack.push_back({RootN, (*RootN)->begin()});
1219 EdgeSequence::iterator I;
1220 std::tie(N, I) = DFSStack.pop_back_val();
1221 auto E = (*N)->end();
1223 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1224 "before processing a node.");
1227 Node &ChildN = I->getNode();
1228 if (ChildN.DFSNumber == 0) {
1229 // Mark that we should start at this child when next this node is the
1230 // top of the stack. We don't start at the next child to ensure this
1231 // child's lowlink is reflected.
1232 DFSStack.push_back({N, I});
1234 // Continue, resetting to the child node.
1235 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1237 I = ChildN->begin();
1241 if (ChildN.DFSNumber == -1) {
1242 // Check if this edge's target node connects to the deleted edge's
1243 // target node. If so, we know that every node connected will end up
1244 // in this RefSCC, so collapse the entire current stack into the root
1245 // slot in our SCC numbering. See above for the motivation of
1246 // optimizing the target connected nodes in this way.
1247 auto PostOrderI = PostOrderMapping.find(&ChildN);
1248 if (PostOrderI != PostOrderMapping.end() &&
1249 PostOrderI->second == RootPostOrderNumber) {
1250 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1251 while (!PendingRefSCCStack.empty())
1252 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1253 RootPostOrderNumber);
1254 while (!DFSStack.empty())
1255 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1256 RootPostOrderNumber);
1257 // Ensure we break all the way out of the enclosing loop.
1262 // If this child isn't currently in this RefSCC, no need to process
1263 // it. However, we do need to remove this RefSCC from its RefSCC's
1265 RefSCC &ChildRC = *G->lookupRefSCC(ChildN);
1266 ChildRC.Parents.erase(this);
1271 // Track the lowest link of the children, if any are still in the stack.
1272 // Any child not on the stack will have a LowLink of -1.
1273 assert(ChildN.LowLink != 0 &&
1274 "Low-link must not be zero with a non-zero DFS number.");
1275 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1276 N->LowLink = ChildN.LowLink;
1280 // We short-circuited this node.
1283 // We've finished processing N and its descendents, put it on our pending
1284 // stack to eventually get merged into a RefSCC.
1285 PendingRefSCCStack.push_back(N);
1287 // If this node is linked to some lower entry, continue walking up the
1289 if (N->LowLink != N->DFSNumber) {
1290 assert(!DFSStack.empty() &&
1291 "We never found a viable root for a RefSCC to pop off!");
1295 // Otherwise, form a new RefSCC from the top of the pending node stack.
1296 int RootDFSNumber = N->DFSNumber;
1297 // Find the range of the node stack by walking down until we pass the
1299 auto RefSCCNodes = make_range(
1300 PendingRefSCCStack.rbegin(),
1301 find_if(reverse(PendingRefSCCStack), [RootDFSNumber](const Node *N) {
1302 return N->DFSNumber < RootDFSNumber;
1305 // Mark the postorder number for these nodes and clear them off the
1306 // stack. We'll use the postorder number to pull them into RefSCCs at the
1307 // end. FIXME: Fuse with the loop above.
1308 int RefSCCNumber = PostOrderNumber++;
1309 for (Node *N : RefSCCNodes)
1310 MarkNodeForSCCNumber(*N, RefSCCNumber);
1312 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1313 PendingRefSCCStack.end());
1314 } while (!DFSStack.empty());
1316 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
1317 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
1318 } while (!Worklist.empty());
1320 // We now have a post-order numbering for RefSCCs and a mapping from each
1321 // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1322 // (re-using this RefSCC node for the root) and build a radix-sort style map
1323 // from postorder number to the RefSCC. We then append SCCs to each of these
1324 // RefSCCs in the order they occured in the original SCCs container.
1325 for (int i = 1; i < PostOrderNumber; ++i)
1326 Result.push_back(G->createRefSCC(*G));
1328 // Insert the resulting postorder sequence into the global graph postorder
1329 // sequence before the current RefSCC in that sequence. The idea being that
1330 // this RefSCC is the target of the reference edge removed, and thus has
1331 // a direct or indirect edge to every other RefSCC formed and so must be at
1332 // the end of any postorder traversal.
1334 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1335 // range over the global postorder sequence and generally use that sequence
1336 // rather than building a separate result vector here.
1337 if (!Result.empty()) {
1338 int Idx = G->getRefSCCIndex(*this);
1339 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx,
1340 Result.begin(), Result.end());
1341 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1342 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1343 assert(G->PostOrderRefSCCs[G->getRefSCCIndex(*this)] == this &&
1344 "Failed to update this RefSCC's index after insertion!");
1347 for (SCC *C : SCCs) {
1348 auto PostOrderI = PostOrderMapping.find(&*C->begin());
1349 assert(PostOrderI != PostOrderMapping.end() &&
1350 "Cannot have missing mappings for nodes!");
1351 int SCCNumber = PostOrderI->second;
1354 assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1355 "Cannot have different numbers for nodes in the same SCC!");
1358 // The root node is handled separately by removing the SCCs.
1361 RefSCC &RC = *Result[SCCNumber - 1];
1362 int SCCIndex = RC.SCCs.size();
1363 RC.SCCs.push_back(C);
1364 RC.SCCIndices[C] = SCCIndex;
1365 C->OuterRefSCC = &RC;
1368 // FIXME: We re-walk the edges in each RefSCC to establish whether it is
1369 // a leaf and connect it to the rest of the graph's parents lists. This is
1370 // really wasteful. We should instead do this during the DFS to avoid yet
1371 // another edge walk.
1372 for (RefSCC *RC : Result)
1373 G->connectRefSCC(*RC);
1375 // Now erase all but the root's SCCs.
1376 SCCs.erase(remove_if(SCCs,
1378 return PostOrderMapping.lookup(&*C->begin()) !=
1379 RootPostOrderNumber;
1383 for (int i = 0, Size = SCCs.size(); i < Size; ++i)
1384 SCCIndices[SCCs[i]] = i;
1387 // Now we need to reconnect the current (root) SCC to the graph. We do this
1388 // manually because we can special case our leaf handling and detect errors.
1392 for (Node &N : *C) {
1393 for (Edge &E : *N) {
1394 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
1395 if (&ChildRC == this)
1397 ChildRC.Parents.insert(this);
1404 if (!Result.empty())
1405 assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new "
1406 "SCCs by removing this edge.");
1407 if (none_of(G->LeafRefSCCs, [&](RefSCC *C) { return C == this; }))
1408 assert(!IsLeaf && "This SCC cannot be a leaf as it already had child "
1409 "SCCs before we removed this edge.");
1411 // And connect both this RefSCC and all the new ones to the correct parents.
1412 // The easiest way to do this is just to re-analyze the old parent set.
1413 SmallVector<RefSCC *, 4> OldParents(Parents.begin(), Parents.end());
1415 for (RefSCC *ParentRC : OldParents)
1416 for (SCC &ParentC : *ParentRC)
1417 for (Node &ParentN : ParentC)
1418 for (Edge &E : *ParentN) {
1419 RefSCC &RC = *G->lookupRefSCC(E.getNode());
1420 if (&RC != ParentRC)
1421 RC.Parents.insert(ParentRC);
1424 // If this SCC stopped being a leaf through this edge removal, remove it from
1425 // the leaf SCC list. Note that this DTRT in the case where this was never
1427 // FIXME: As LeafRefSCCs could be very large, we might want to not walk the
1428 // entire list if this RefSCC wasn't a leaf before the edge removal.
1429 if (!Result.empty())
1430 G->LeafRefSCCs.erase(
1431 std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this),
1432 G->LeafRefSCCs.end());
1435 // Verify all of the new RefSCCs.
1436 for (RefSCC *RC : Result)
1440 // Return the new list of SCCs.
1444 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1446 // The only trivial case that requires any graph updates is when we add new
1447 // ref edge and may connect different RefSCCs along that path. This is only
1448 // because of the parents set. Every other part of the graph remains constant
1449 // after this edge insertion.
1450 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1451 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1452 if (&TargetRC == this) {
1457 #ifdef EXPENSIVE_CHECKS
1458 assert(TargetRC.isDescendantOf(*this) &&
1459 "Target must be a descendant of the Source.");
1461 // The only change required is to add this RefSCC to the parent set of the
1462 // target. This is a set and so idempotent if the edge already existed.
1463 TargetRC.Parents.insert(this);
1466 void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1469 // Check that the RefSCC is still valid when we finish.
1470 auto ExitVerifier = make_scope_exit([this] { verify(); });
1472 #ifdef EXPENSIVE_CHECKS
1473 // Check that we aren't breaking some invariants of the SCC graph. Note that
1474 // this is quadratic in the number of edges in the call graph!
1475 SCC &SourceC = *G->lookupSCC(SourceN);
1476 SCC &TargetC = *G->lookupSCC(TargetN);
1477 if (&SourceC != &TargetC)
1478 assert(SourceC.isAncestorOf(TargetC) &&
1479 "Call edge is not trivial in the SCC graph!");
1480 #endif // EXPENSIVE_CHECKS
1483 // First insert it into the source or find the existing edge.
1485 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1486 if (!InsertResult.second) {
1487 // Already an edge, just update it.
1488 Edge &E = SourceN->Edges[InsertResult.first->second];
1490 return; // Nothing to do!
1491 E.setKind(Edge::Call);
1493 // Create the new edge.
1494 SourceN->Edges.emplace_back(TargetN, Edge::Call);
1497 // Now that we have the edge, handle the graph fallout.
1498 handleTrivialEdgeInsertion(SourceN, TargetN);
1501 void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1503 // Check that the RefSCC is still valid when we finish.
1504 auto ExitVerifier = make_scope_exit([this] { verify(); });
1506 #ifdef EXPENSIVE_CHECKS
1507 // Check that we aren't breaking some invariants of the RefSCC graph.
1508 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1509 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1510 if (&SourceRC != &TargetRC)
1511 assert(SourceRC.isAncestorOf(TargetRC) &&
1512 "Ref edge is not trivial in the RefSCC graph!");
1513 #endif // EXPENSIVE_CHECKS
1516 // First insert it into the source or find the existing edge.
1518 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1519 if (!InsertResult.second)
1520 // Already an edge, we're done.
1523 // Create the new edge.
1524 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
1526 // Now that we have the edge, handle the graph fallout.
1527 handleTrivialEdgeInsertion(SourceN, TargetN);
1530 void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1531 Function &OldF = N.getFunction();
1534 // Check that the RefSCC is still valid when we finish.
1535 auto ExitVerifier = make_scope_exit([this] { verify(); });
1537 assert(G->lookupRefSCC(N) == this &&
1538 "Cannot replace the function of a node outside this RefSCC.");
1540 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1541 "Must not have already walked the new function!'");
1543 // It is important that this replacement not introduce graph changes so we
1544 // insist that the caller has already removed every use of the original
1545 // function and that all uses of the new function correspond to existing
1546 // edges in the graph. The common and expected way to use this is when
1547 // replacing the function itself in the IR without changing the call graph
1548 // shape and just updating the analysis based on that.
1549 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1550 assert(OldF.use_empty() &&
1551 "Must have moved all uses from the old function to the new!");
1554 N.replaceFunction(NewF);
1556 // Update various call graph maps.
1557 G->NodeMap.erase(&OldF);
1558 G->NodeMap[&NewF] = &N;
1561 void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
1562 assert(SCCMap.empty() &&
1563 "This method cannot be called after SCCs have been formed!");
1565 return SourceN->insertEdgeInternal(TargetN, EK);
1568 void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1569 assert(SCCMap.empty() &&
1570 "This method cannot be called after SCCs have been formed!");
1572 bool Removed = SourceN->removeEdgeInternal(TargetN);
1574 assert(Removed && "Target not in the edge set for this caller?");
1577 void LazyCallGraph::removeDeadFunction(Function &F) {
1578 // FIXME: This is unnecessarily restrictive. We should be able to remove
1579 // functions which recursively call themselves.
1580 assert(F.use_empty() &&
1581 "This routine should only be called on trivially dead functions!");
1583 auto NI = NodeMap.find(&F);
1584 if (NI == NodeMap.end())
1585 // Not in the graph at all!
1588 Node &N = *NI->second;
1591 // Remove this from the entry edges if present.
1592 EntryEdges.removeEdgeInternal(N);
1594 if (SCCMap.empty()) {
1595 // No SCCs have been formed, so removing this is fine and there is nothing
1596 // else necessary at this point but clearing out the node.
1601 // Cannot remove a function which has yet to be visited in the DFS walk, so
1602 // if we have a node at all then we must have an SCC and RefSCC.
1603 auto CI = SCCMap.find(&N);
1604 assert(CI != SCCMap.end() &&
1605 "Tried to remove a node without an SCC after DFS walk started!");
1606 SCC &C = *CI->second;
1608 RefSCC &RC = C.getOuterRefSCC();
1610 // This node must be the only member of its SCC as it has no callers, and
1611 // that SCC must be the only member of a RefSCC as it has no references.
1612 // Validate these properties first.
1613 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1614 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
1616 // Clean up any remaining reference edges. Note that we walk an unordered set
1617 // here but are just removing and so the order doesn't matter.
1618 for (RefSCC &ParentRC : RC.parents())
1619 for (SCC &ParentC : ParentRC)
1620 for (Node &ParentN : ParentC)
1622 ParentN->removeEdgeInternal(N);
1624 // Now remove this RefSCC from any parents sets and the leaf list.
1626 if (RefSCC *TargetRC = lookupRefSCC(E.getNode()))
1627 TargetRC->Parents.erase(&RC);
1628 // FIXME: This is a linear operation which could become hot and benefit from
1630 auto LRI = find(LeafRefSCCs, &RC);
1631 if (LRI != LeafRefSCCs.end())
1632 LeafRefSCCs.erase(LRI);
1634 auto RCIndexI = RefSCCIndices.find(&RC);
1635 int RCIndex = RCIndexI->second;
1636 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1637 RefSCCIndices.erase(RCIndexI);
1638 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1639 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1641 // Finally clear out all the data structures from the node down through the
1647 // Nothing to delete as all the objects are allocated in stable bump pointer
1651 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1652 return *new (MappedN = BPA.Allocate()) Node(*this, F);
1655 void LazyCallGraph::updateGraphPtrs() {
1656 // Process all nodes updating the graph pointers.
1658 SmallVector<Node *, 16> Worklist;
1659 for (Edge &E : EntryEdges)
1660 Worklist.push_back(&E.getNode());
1662 while (!Worklist.empty()) {
1663 Node &N = *Worklist.pop_back_val();
1667 Worklist.push_back(&E.getNode());
1671 // Process all SCCs updating the graph pointers.
1673 SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end());
1675 while (!Worklist.empty()) {
1676 RefSCC &C = *Worklist.pop_back_val();
1678 for (RefSCC &ParentC : C.parents())
1679 Worklist.push_back(&ParentC);
1684 template <typename RootsT, typename GetBeginT, typename GetEndT,
1685 typename GetNodeT, typename FormSCCCallbackT>
1686 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1687 GetEndT &&GetEnd, GetNodeT &&GetNode,
1688 FormSCCCallbackT &&FormSCC) {
1689 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT;
1691 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
1692 SmallVector<Node *, 16> PendingSCCStack;
1694 // Scan down the stack and DFS across the call edges.
1695 for (Node *RootN : Roots) {
1696 assert(DFSStack.empty() &&
1697 "Cannot begin a new root with a non-empty DFS stack!");
1698 assert(PendingSCCStack.empty() &&
1699 "Cannot begin a new root with pending nodes for an SCC!");
1701 // Skip any nodes we've already reached in the DFS.
1702 if (RootN->DFSNumber != 0) {
1703 assert(RootN->DFSNumber == -1 &&
1704 "Shouldn't have any mid-DFS root nodes!");
1708 RootN->DFSNumber = RootN->LowLink = 1;
1709 int NextDFSNumber = 2;
1711 DFSStack.push_back({RootN, GetBegin(*RootN)});
1715 std::tie(N, I) = DFSStack.pop_back_val();
1716 auto E = GetEnd(*N);
1718 Node &ChildN = GetNode(I);
1719 if (ChildN.DFSNumber == 0) {
1720 // We haven't yet visited this child, so descend, pushing the current
1721 // node onto the stack.
1722 DFSStack.push_back({N, I});
1724 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1731 // If the child has already been added to some child component, it
1732 // couldn't impact the low-link of this parent because it isn't
1733 // connected, and thus its low-link isn't relevant so skip it.
1734 if (ChildN.DFSNumber == -1) {
1739 // Track the lowest linked child as the lowest link for this node.
1740 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1741 if (ChildN.LowLink < N->LowLink)
1742 N->LowLink = ChildN.LowLink;
1744 // Move to the next edge.
1748 // We've finished processing N and its descendents, put it on our pending
1749 // SCC stack to eventually get merged into an SCC of nodes.
1750 PendingSCCStack.push_back(N);
1752 // If this node is linked to some lower entry, continue walking up the
1754 if (N->LowLink != N->DFSNumber)
1757 // Otherwise, we've completed an SCC. Append it to our post order list of
1759 int RootDFSNumber = N->DFSNumber;
1760 // Find the range of the node stack by walking down until we pass the
1762 auto SCCNodes = make_range(
1763 PendingSCCStack.rbegin(),
1764 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1765 return N->DFSNumber < RootDFSNumber;
1767 // Form a new SCC out of these nodes and then clear them off our pending
1770 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1771 } while (!DFSStack.empty());
1775 /// Build the internal SCCs for a RefSCC from a sequence of nodes.
1777 /// Appends the SCCs to the provided vector and updates the map with their
1778 /// indices. Both the vector and map must be empty when passed into this
1780 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1781 assert(RC.SCCs.empty() && "Already built SCCs!");
1782 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1784 for (Node *N : Nodes) {
1785 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1786 "We cannot have a low link in an SCC lower than its root on the "
1789 // This node will go into the next RefSCC, clear out its DFS and low link
1791 N->DFSNumber = N->LowLink = 0;
1794 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1795 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1796 // internal storage as we won't need it for the outer graph's DFS any longer.
1798 Nodes, [](Node &N) { return N->call_begin(); },
1799 [](Node &N) { return N->call_end(); },
1800 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1801 [this, &RC](node_stack_range Nodes) {
1802 RC.SCCs.push_back(createSCC(RC, Nodes));
1803 for (Node &N : *RC.SCCs.back()) {
1804 N.DFSNumber = N.LowLink = -1;
1805 SCCMap[&N] = RC.SCCs.back();
1809 // Wire up the SCC indices.
1810 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1811 RC.SCCIndices[RC.SCCs[i]] = i;
1814 void LazyCallGraph::buildRefSCCs() {
1815 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1816 // RefSCCs are either non-existent or already built!
1819 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1821 SmallVector<Node *, 16> Roots;
1822 for (Edge &E : *this)
1823 Roots.push_back(&E.getNode());
1825 // The roots will be popped of a stack, so use reverse to get a less
1826 // surprising order. This doesn't change any of the semantics anywhere.
1827 std::reverse(Roots.begin(), Roots.end());
1832 // We need to populate each node as we begin to walk its edges.
1836 [](Node &N) { return N->end(); },
1837 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
1838 [this](node_stack_range Nodes) {
1839 RefSCC *NewRC = createRefSCC(*this);
1840 buildSCCs(*NewRC, Nodes);
1841 connectRefSCC(*NewRC);
1843 // Push the new node into the postorder list and remember its position
1844 // in the index map.
1846 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1848 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1849 PostOrderRefSCCs.push_back(NewRC);
1856 // FIXME: We should move callers of this to embed the parent linking and leaf
1857 // tracking into their DFS in order to remove a full walk of all edges.
1858 void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1859 // Walk all edges in the RefSCC (this remains linear as we only do this once
1860 // when we build the RefSCC) to connect it to the parent sets of its
1865 for (Edge &E : *N) {
1866 RefSCC &ChildRC = *lookupRefSCC(E.getNode());
1867 if (&ChildRC == &RC)
1869 ChildRC.Parents.insert(&RC);
1873 // For the SCCs where we find no child SCCs, add them to the leaf list.
1875 LeafRefSCCs.push_back(&RC);
1878 AnalysisKey LazyCallGraphAnalysis::Key;
1880 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1882 static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
1883 OS << " Edges in function: " << N.getFunction().getName() << "\n";
1884 for (LazyCallGraph::Edge &E : N.populate())
1885 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1886 << E.getFunction().getName() << "\n";
1891 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1892 ptrdiff_t Size = std::distance(C.begin(), C.end());
1893 OS << " SCC with " << Size << " functions:\n";
1895 for (LazyCallGraph::Node &N : C)
1896 OS << " " << N.getFunction().getName() << "\n";
1899 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1900 ptrdiff_t Size = std::distance(C.begin(), C.end());
1901 OS << " RefSCC with " << Size << " call SCCs:\n";
1903 for (LazyCallGraph::SCC &InnerC : C)
1904 printSCC(OS, InnerC);
1909 PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
1910 ModuleAnalysisManager &AM) {
1911 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1913 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1916 for (Function &F : M)
1917 printNode(OS, G.get(F));
1920 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1923 return PreservedAnalyses::all();
1926 LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1929 static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1930 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1932 for (LazyCallGraph::Edge &E : N.populate()) {
1933 OS << " " << Name << " -> \""
1934 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1935 if (!E.isCall()) // It is a ref edge.
1936 OS << " [style=dashed,label=\"ref\"]";
1943 PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1944 ModuleAnalysisManager &AM) {
1945 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1947 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1949 for (Function &F : M)
1950 printNodeDOT(OS, G.get(F));
1954 return PreservedAnalyses::all();