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);
109 // Add implicit reference edges to any defined libcall functions (if we
110 // haven't found an explicit edge).
111 for (auto *F : G->LibFunctions)
112 if (!Visited.count(F))
113 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
114 LazyCallGraph::Edge::Ref);
119 void LazyCallGraph::Node::replaceFunction(Function &NewF) {
120 assert(F != &NewF && "Must not replace a function with itself!");
124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
125 LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
126 dbgs() << *this << '\n';
130 static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
133 // Either this is a normal library function or a "vectorizable" function.
134 return TLI.getLibFunc(F, LF) || TLI.isFunctionVectorizable(F.getName());
137 LazyCallGraph::LazyCallGraph(Module &M, TargetLibraryInfo &TLI) {
138 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
140 for (Function &F : M) {
141 if (F.isDeclaration())
143 // If this function is a known lib function to LLVM then we want to
144 // synthesize reference edges to it to model the fact that LLVM can turn
145 // arbitrary code into a library function call.
146 if (isKnownLibFunction(F, TLI))
147 LibFunctions.insert(&F);
149 if (F.hasLocalLinkage())
152 // External linkage defined functions have edges to them from other
154 DEBUG(dbgs() << " Adding '" << F.getName()
155 << "' to entry set of the graph.\n");
156 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
159 // Now add entry nodes for functions reachable via initializers to globals.
160 SmallVector<Constant *, 16> Worklist;
161 SmallPtrSet<Constant *, 16> Visited;
162 for (GlobalVariable &GV : M.globals())
163 if (GV.hasInitializer())
164 if (Visited.insert(GV.getInitializer()).second)
165 Worklist.push_back(GV.getInitializer());
167 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
169 visitReferences(Worklist, Visited, [&](Function &F) {
170 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
171 LazyCallGraph::Edge::Ref);
175 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
176 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
177 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
178 SCCMap(std::move(G.SCCMap)), LeafRefSCCs(std::move(G.LeafRefSCCs)),
179 LibFunctions(std::move(G.LibFunctions)) {
183 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
184 BPA = std::move(G.BPA);
185 NodeMap = std::move(G.NodeMap);
186 EntryEdges = std::move(G.EntryEdges);
187 SCCBPA = std::move(G.SCCBPA);
188 SCCMap = std::move(G.SCCMap);
189 LeafRefSCCs = std::move(G.LeafRefSCCs);
190 LibFunctions = std::move(G.LibFunctions);
195 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
196 LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
197 dbgs() << *this << '\n';
202 void LazyCallGraph::SCC::verify() {
203 assert(OuterRefSCC && "Can't have a null RefSCC!");
204 assert(!Nodes.empty() && "Can't have an empty SCC!");
206 for (Node *N : Nodes) {
207 assert(N && "Can't have a null node!");
208 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
209 "Node does not map to this SCC!");
210 assert(N->DFSNumber == -1 &&
211 "Must set DFS numbers to -1 when adding a node to an SCC!");
212 assert(N->LowLink == -1 &&
213 "Must set low link to -1 when adding a node to an SCC!");
215 assert(E.getNode() && "Can't have an unpopulated node!");
220 bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
224 for (Node &N : *this)
225 for (Edge &E : N->calls())
226 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
233 bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
234 if (this == &TargetC)
237 LazyCallGraph &G = *OuterRefSCC->G;
239 // Start with this SCC.
240 SmallPtrSet<const SCC *, 16> Visited = {this};
241 SmallVector<const SCC *, 16> Worklist = {this};
243 // Walk down the graph until we run out of edges or find a path to TargetC.
245 const SCC &C = *Worklist.pop_back_val();
247 for (Edge &E : N->calls()) {
248 SCC *CalleeC = G.lookupSCC(E.getNode());
252 // If the callee's SCC is the TargetC, we're done.
253 if (CalleeC == &TargetC)
256 // If this is the first time we've reached this SCC, put it on the
257 // worklist to recurse through.
258 if (Visited.insert(CalleeC).second)
259 Worklist.push_back(CalleeC);
261 } while (!Worklist.empty());
267 LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
269 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
270 LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
271 dbgs() << *this << '\n';
276 void LazyCallGraph::RefSCC::verify() {
277 assert(G && "Can't have a null graph!");
278 assert(!SCCs.empty() && "Can't have an empty SCC!");
280 // Verify basic properties of the SCCs.
281 SmallPtrSet<SCC *, 4> SCCSet;
282 for (SCC *C : SCCs) {
283 assert(C && "Can't have a null SCC!");
285 assert(&C->getOuterRefSCC() == this &&
286 "SCC doesn't think it is inside this RefSCC!");
287 bool Inserted = SCCSet.insert(C).second;
288 assert(Inserted && "Found a duplicate SCC!");
289 auto IndexIt = SCCIndices.find(C);
290 assert(IndexIt != SCCIndices.end() &&
291 "Found an SCC that doesn't have an index!");
294 // Check that our indices map correctly.
295 for (auto &SCCIndexPair : SCCIndices) {
296 SCC *C = SCCIndexPair.first;
297 int i = SCCIndexPair.second;
298 assert(C && "Can't have a null SCC in the indices!");
299 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
300 assert(SCCs[i] == C && "Index doesn't point to SCC!");
303 // Check that the SCCs are in fact in post-order.
304 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
305 SCC &SourceSCC = *SCCs[i];
306 for (Node &N : SourceSCC)
310 SCC &TargetSCC = *G->lookupSCC(E.getNode());
311 if (&TargetSCC.getOuterRefSCC() == this) {
312 assert(SCCIndices.find(&TargetSCC)->second <= i &&
313 "Edge between SCCs violates post-order relationship.");
316 assert(TargetSCC.getOuterRefSCC().Parents.count(this) &&
317 "Edge to a RefSCC missing us in its parent set.");
321 // Check that our parents are actually parents.
322 for (RefSCC *ParentRC : Parents) {
323 assert(ParentRC != this && "Cannot be our own parent!");
324 auto HasConnectingEdge = [&] {
325 for (SCC &C : *ParentRC)
328 if (G->lookupRefSCC(E.getNode()) == this)
332 assert(HasConnectingEdge() && "No edge connects the parent to us!");
337 bool LazyCallGraph::RefSCC::isDescendantOf(const RefSCC &C) const {
338 // Walk up the parents of this SCC and verify that we eventually find C.
339 SmallVector<const RefSCC *, 4> AncestorWorklist;
340 AncestorWorklist.push_back(this);
342 const RefSCC *AncestorC = AncestorWorklist.pop_back_val();
343 if (AncestorC->isChildOf(C))
345 for (const RefSCC *ParentC : AncestorC->Parents)
346 AncestorWorklist.push_back(ParentC);
347 } while (!AncestorWorklist.empty());
352 /// Generic helper that updates a postorder sequence of SCCs for a potentially
353 /// cycle-introducing edge insertion.
355 /// A postorder sequence of SCCs of a directed graph has one fundamental
356 /// property: all deges in the DAG of SCCs point "up" the sequence. That is,
357 /// all edges in the SCC DAG point to prior SCCs in the sequence.
359 /// This routine both updates a postorder sequence and uses that sequence to
360 /// compute the set of SCCs connected into a cycle. It should only be called to
361 /// insert a "downward" edge which will require changing the sequence to
362 /// restore it to a postorder.
364 /// When inserting an edge from an earlier SCC to a later SCC in some postorder
365 /// sequence, all of the SCCs which may be impacted are in the closed range of
366 /// those two within the postorder sequence. The algorithm used here to restore
367 /// the state is as follows:
369 /// 1) Starting from the source SCC, construct a set of SCCs which reach the
370 /// source SCC consisting of just the source SCC. Then scan toward the
371 /// target SCC in postorder and for each SCC, if it has an edge to an SCC
372 /// in the set, add it to the set. Otherwise, the source SCC is not
373 /// a successor, move it in the postorder sequence to immediately before
374 /// the source SCC, shifting the source SCC and all SCCs in the set one
375 /// position toward the target SCC. Stop scanning after processing the
377 /// 2) If the source SCC is now past the target SCC in the postorder sequence,
378 /// and thus the new edge will flow toward the start, we are done.
379 /// 3) Otherwise, starting from the target SCC, walk all edges which reach an
380 /// SCC between the source and the target, and add them to the set of
381 /// connected SCCs, then recurse through them. Once a complete set of the
382 /// SCCs the target connects to is known, hoist the remaining SCCs between
383 /// the source and the target to be above the target. Note that there is no
384 /// need to process the source SCC, it is already known to connect.
385 /// 4) At this point, all of the SCCs in the closed range between the source
386 /// SCC and the target SCC in the postorder sequence are connected,
387 /// including the target SCC and the source SCC. Inserting the edge from
388 /// the source SCC to the target SCC will form a cycle out of precisely
389 /// these SCCs. Thus we can merge all of the SCCs in this closed range into
392 /// This process has various important properties:
393 /// - Only mutates the SCCs when adding the edge actually changes the SCC
395 /// - Never mutates SCCs which are unaffected by the change.
396 /// - Updates the postorder sequence to correctly satisfy the postorder
397 /// constraint after the edge is inserted.
398 /// - Only reorders SCCs in the closed postorder sequence from the source to
399 /// the target, so easy to bound how much has changed even in the ordering.
400 /// - Big-O is the number of edges in the closed postorder range of SCCs from
401 /// source to target.
403 /// This helper routine, in addition to updating the postorder sequence itself
404 /// will also update a map from SCCs to indices within that sequecne.
406 /// The sequence and the map must operate on pointers to the SCC type.
408 /// Two callbacks must be provided. The first computes the subset of SCCs in
409 /// the postorder closed range from the source to the target which connect to
410 /// the source SCC via some (transitive) set of edges. The second computes the
411 /// subset of the same range which the target SCC connects to via some
412 /// (transitive) set of edges. Both callbacks should populate the set argument
414 template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
415 typename ComputeSourceConnectedSetCallableT,
416 typename ComputeTargetConnectedSetCallableT>
417 static iterator_range<typename PostorderSequenceT::iterator>
418 updatePostorderSequenceForEdgeInsertion(
419 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
420 SCCIndexMapT &SCCIndices,
421 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
422 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
423 int SourceIdx = SCCIndices[&SourceSCC];
424 int TargetIdx = SCCIndices[&TargetSCC];
425 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
427 SmallPtrSet<SCCT *, 4> ConnectedSet;
429 // Compute the SCCs which (transitively) reach the source.
430 ComputeSourceConnectedSet(ConnectedSet);
432 // Partition the SCCs in this part of the port-order sequence so only SCCs
433 // connecting to the source remain between it and the target. This is
434 // a benign partition as it preserves postorder.
435 auto SourceI = std::stable_partition(
436 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
437 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
438 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
439 SCCIndices.find(SCCs[i])->second = i;
441 // If the target doesn't connect to the source, then we've corrected the
442 // post-order and there are no cycles formed.
443 if (!ConnectedSet.count(&TargetSCC)) {
444 assert(SourceI > (SCCs.begin() + SourceIdx) &&
445 "Must have moved the source to fix the post-order.");
446 assert(*std::prev(SourceI) == &TargetSCC &&
447 "Last SCC to move should have bene the target.");
449 // Return an empty range at the target SCC indicating there is nothing to
451 return make_range(std::prev(SourceI), std::prev(SourceI));
454 assert(SCCs[TargetIdx] == &TargetSCC &&
455 "Should not have moved target if connected!");
456 SourceIdx = SourceI - SCCs.begin();
457 assert(SCCs[SourceIdx] == &SourceSCC &&
458 "Bad updated index computation for the source SCC!");
461 // See whether there are any remaining intervening SCCs between the source
462 // and target. If so we need to make sure they all are reachable form the
464 if (SourceIdx + 1 < TargetIdx) {
465 ConnectedSet.clear();
466 ComputeTargetConnectedSet(ConnectedSet);
468 // Partition SCCs so that only SCCs reached from the target remain between
469 // the source and the target. This preserves postorder.
470 auto TargetI = std::stable_partition(
471 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
472 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
473 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
474 SCCIndices.find(SCCs[i])->second = i;
475 TargetIdx = std::prev(TargetI) - SCCs.begin();
476 assert(SCCs[TargetIdx] == &TargetSCC &&
477 "Should always end with the target!");
480 // At this point, we know that connecting source to target forms a cycle
481 // because target connects back to source, and we know that all of the SCCs
482 // between the source and target in the postorder sequence participate in that
484 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
488 LazyCallGraph::RefSCC::switchInternalEdgeToCall(
489 Node &SourceN, Node &TargetN,
490 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
491 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
492 SmallVector<SCC *, 1> DeletedSCCs;
495 // In a debug build, verify the RefSCC is valid to start with and when this
498 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
501 SCC &SourceSCC = *G->lookupSCC(SourceN);
502 SCC &TargetSCC = *G->lookupSCC(TargetN);
504 // If the two nodes are already part of the same SCC, we're also done as
505 // we've just added more connectivity.
506 if (&SourceSCC == &TargetSCC) {
507 SourceN->setEdgeKind(TargetN, Edge::Call);
508 return false; // No new cycle.
511 // At this point we leverage the postorder list of SCCs to detect when the
512 // insertion of an edge changes the SCC structure in any way.
514 // First and foremost, we can eliminate the need for any changes when the
515 // edge is toward the beginning of the postorder sequence because all edges
516 // flow in that direction already. Thus adding a new one cannot form a cycle.
517 int SourceIdx = SCCIndices[&SourceSCC];
518 int TargetIdx = SCCIndices[&TargetSCC];
519 if (TargetIdx < SourceIdx) {
520 SourceN->setEdgeKind(TargetN, Edge::Call);
521 return false; // No new cycle.
524 // Compute the SCCs which (transitively) reach the source.
525 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
527 // Check that the RefSCC is still valid before computing this as the
528 // results will be nonsensical of we've broken its invariants.
531 ConnectedSet.insert(&SourceSCC);
532 auto IsConnected = [&](SCC &C) {
534 for (Edge &E : N->calls())
535 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
542 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
544 ConnectedSet.insert(C);
547 // Use a normal worklist to find which SCCs the target connects to. We still
548 // bound the search based on the range in the postorder list we care about,
549 // but because this is forward connectivity we just "recurse" through the
551 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
553 // Check that the RefSCC is still valid before computing this as the
554 // results will be nonsensical of we've broken its invariants.
557 ConnectedSet.insert(&TargetSCC);
558 SmallVector<SCC *, 4> Worklist;
559 Worklist.push_back(&TargetSCC);
561 SCC &C = *Worklist.pop_back_val();
566 SCC &EdgeC = *G->lookupSCC(E.getNode());
567 if (&EdgeC.getOuterRefSCC() != this)
568 // Not in this RefSCC...
570 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
571 // Not in the postorder sequence between source and target.
574 if (ConnectedSet.insert(&EdgeC).second)
575 Worklist.push_back(&EdgeC);
577 } while (!Worklist.empty());
580 // Use a generic helper to update the postorder sequence of SCCs and return
581 // a range of any SCCs connected into a cycle by inserting this edge. This
582 // routine will also take care of updating the indices into the postorder
584 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
585 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
586 ComputeTargetConnectedSet);
588 // Run the user's callback on the merged SCCs before we actually merge them.
590 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
592 // If the merge range is empty, then adding the edge didn't actually form any
593 // new cycles. We're done.
594 if (MergeRange.begin() == MergeRange.end()) {
595 // Now that the SCC structure is finalized, flip the kind to call.
596 SourceN->setEdgeKind(TargetN, Edge::Call);
597 return false; // No new cycle.
601 // Before merging, check that the RefSCC remains valid after all the
602 // postorder updates.
606 // Otherwise we need to merge all of the SCCs in the cycle into a single
609 // NB: We merge into the target because all of these functions were already
610 // reachable from the target, meaning any SCC-wide properties deduced about it
611 // other than the set of functions within it will not have changed.
612 for (SCC *C : MergeRange) {
613 assert(C != &TargetSCC &&
614 "We merge *into* the target and shouldn't process it here!");
616 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
617 for (Node *N : C->Nodes)
618 G->SCCMap[N] = &TargetSCC;
620 DeletedSCCs.push_back(C);
623 // Erase the merged SCCs from the list and update the indices of the
625 int IndexOffset = MergeRange.end() - MergeRange.begin();
626 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
627 for (SCC *C : make_range(EraseEnd, SCCs.end()))
628 SCCIndices[C] -= IndexOffset;
630 // Now that the SCC structure is finalized, flip the kind to call.
631 SourceN->setEdgeKind(TargetN, Edge::Call);
633 // And we're done, but we did form a new cycle.
637 void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
639 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
642 // In a debug build, verify the RefSCC is valid to start with and when this
645 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
648 assert(G->lookupRefSCC(SourceN) == this &&
649 "Source must be in this RefSCC.");
650 assert(G->lookupRefSCC(TargetN) == this &&
651 "Target must be in this RefSCC.");
652 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
653 "Source and Target must be in separate SCCs for this to be trivial!");
655 // Set the edge kind.
656 SourceN->setEdgeKind(TargetN, Edge::Ref);
659 iterator_range<LazyCallGraph::RefSCC::iterator>
660 LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
661 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
664 // In a debug build, verify the RefSCC is valid to start with and when this
667 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
670 assert(G->lookupRefSCC(SourceN) == this &&
671 "Source must be in this RefSCC.");
672 assert(G->lookupRefSCC(TargetN) == this &&
673 "Target must be in this RefSCC.");
675 SCC &TargetSCC = *G->lookupSCC(TargetN);
676 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
677 "the same SCC to require the "
680 // Set the edge kind.
681 SourceN->setEdgeKind(TargetN, Edge::Ref);
683 // Otherwise we are removing a call edge from a single SCC. This may break
684 // the cycle. In order to compute the new set of SCCs, we need to do a small
685 // DFS over the nodes within the SCC to form any sub-cycles that remain as
686 // distinct SCCs and compute a postorder over the resulting SCCs.
688 // However, we specially handle the target node. The target node is known to
689 // reach all other nodes in the original SCC by definition. This means that
690 // we want the old SCC to be replaced with an SCC contaning that node as it
691 // will be the root of whatever SCC DAG results from the DFS. Assumptions
692 // about an SCC such as the set of functions called will continue to hold,
695 SCC &OldSCC = TargetSCC;
696 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
697 SmallVector<Node *, 16> PendingSCCStack;
698 SmallVector<SCC *, 4> NewSCCs;
700 // Prepare the nodes for a fresh DFS.
701 SmallVector<Node *, 16> Worklist;
702 Worklist.swap(OldSCC.Nodes);
703 for (Node *N : Worklist) {
704 N->DFSNumber = N->LowLink = 0;
708 // Force the target node to be in the old SCC. This also enables us to take
709 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
710 // below: whenever we build an edge that reaches the target node, we know
711 // that the target node eventually connects back to all other nodes in our
712 // walk. As a consequence, we can detect and handle participants in that
713 // cycle without walking all the edges that form this connection, and instead
714 // by relying on the fundamental guarantee coming into this operation (all
715 // nodes are reachable from the target due to previously forming an SCC).
716 TargetN.DFSNumber = TargetN.LowLink = -1;
717 OldSCC.Nodes.push_back(&TargetN);
718 G->SCCMap[&TargetN] = &OldSCC;
720 // Scan down the stack and DFS across the call edges.
721 for (Node *RootN : Worklist) {
722 assert(DFSStack.empty() &&
723 "Cannot begin a new root with a non-empty DFS stack!");
724 assert(PendingSCCStack.empty() &&
725 "Cannot begin a new root with pending nodes for an SCC!");
727 // Skip any nodes we've already reached in the DFS.
728 if (RootN->DFSNumber != 0) {
729 assert(RootN->DFSNumber == -1 &&
730 "Shouldn't have any mid-DFS root nodes!");
734 RootN->DFSNumber = RootN->LowLink = 1;
735 int NextDFSNumber = 2;
737 DFSStack.push_back({RootN, (*RootN)->call_begin()});
740 EdgeSequence::call_iterator I;
741 std::tie(N, I) = DFSStack.pop_back_val();
742 auto E = (*N)->call_end();
744 Node &ChildN = I->getNode();
745 if (ChildN.DFSNumber == 0) {
746 // We haven't yet visited this child, so descend, pushing the current
747 // node onto the stack.
748 DFSStack.push_back({N, I});
750 assert(!G->SCCMap.count(&ChildN) &&
751 "Found a node with 0 DFS number but already in an SCC!");
752 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
754 I = (*N)->call_begin();
755 E = (*N)->call_end();
759 // Check for the child already being part of some component.
760 if (ChildN.DFSNumber == -1) {
761 if (G->lookupSCC(ChildN) == &OldSCC) {
762 // If the child is part of the old SCC, we know that it can reach
763 // every other node, so we have formed a cycle. Pull the entire DFS
764 // and pending stacks into it. See the comment above about setting
765 // up the old SCC for why we do this.
766 int OldSize = OldSCC.size();
767 OldSCC.Nodes.push_back(N);
768 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
769 PendingSCCStack.clear();
770 while (!DFSStack.empty())
771 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
772 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
773 N.DFSNumber = N.LowLink = -1;
774 G->SCCMap[&N] = &OldSCC;
780 // If the child has already been added to some child component, it
781 // couldn't impact the low-link of this parent because it isn't
782 // connected, and thus its low-link isn't relevant so skip it.
787 // Track the lowest linked child as the lowest link for this node.
788 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
789 if (ChildN.LowLink < N->LowLink)
790 N->LowLink = ChildN.LowLink;
792 // Move to the next edge.
796 // Cleared the DFS early, start another round.
799 // We've finished processing N and its descendents, put it on our pending
800 // SCC stack to eventually get merged into an SCC of nodes.
801 PendingSCCStack.push_back(N);
803 // If this node is linked to some lower entry, continue walking up the
805 if (N->LowLink != N->DFSNumber)
808 // Otherwise, we've completed an SCC. Append it to our post order list of
810 int RootDFSNumber = N->DFSNumber;
811 // Find the range of the node stack by walking down until we pass the
813 auto SCCNodes = make_range(
814 PendingSCCStack.rbegin(),
815 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
816 return N->DFSNumber < RootDFSNumber;
819 // Form a new SCC out of these nodes and then clear them off our pending
821 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
822 for (Node &N : *NewSCCs.back()) {
823 N.DFSNumber = N.LowLink = -1;
824 G->SCCMap[&N] = NewSCCs.back();
826 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
827 } while (!DFSStack.empty());
830 // Insert the remaining SCCs before the old one. The old SCC can reach all
831 // other SCCs we form because it contains the target node of the removed edge
832 // of the old SCC. This means that we will have edges into all of the new
833 // SCCs, which means the old one must come last for postorder.
834 int OldIdx = SCCIndices[&OldSCC];
835 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
837 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
838 // old SCC from the mapping.
839 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
840 SCCIndices[SCCs[Idx]] = Idx;
842 return make_range(SCCs.begin() + OldIdx,
843 SCCs.begin() + OldIdx + NewSCCs.size());
846 void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
848 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
850 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
851 assert(G->lookupRefSCC(TargetN) != this &&
852 "Target must not be in this RefSCC.");
853 #ifdef EXPENSIVE_CHECKS
854 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
855 "Target must be a descendant of the Source.");
858 // Edges between RefSCCs are the same regardless of call or ref, so we can
859 // just flip the edge here.
860 SourceN->setEdgeKind(TargetN, Edge::Call);
863 // Check that the RefSCC is still valid.
868 void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
870 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
872 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
873 assert(G->lookupRefSCC(TargetN) != this &&
874 "Target must not be in this RefSCC.");
875 #ifdef EXPENSIVE_CHECKS
876 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
877 "Target must be a descendant of the Source.");
880 // Edges between RefSCCs are the same regardless of call or ref, so we can
881 // just flip the edge here.
882 SourceN->setEdgeKind(TargetN, Edge::Ref);
885 // Check that the RefSCC is still valid.
890 void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
892 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
893 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
895 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
898 // Check that the RefSCC is still valid.
903 void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
905 // First insert it into the caller.
906 SourceN->insertEdgeInternal(TargetN, EK);
908 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
910 RefSCC &TargetC = *G->lookupRefSCC(TargetN);
911 assert(&TargetC != this && "Target must not be in this RefSCC.");
912 #ifdef EXPENSIVE_CHECKS
913 assert(TargetC.isDescendantOf(*this) &&
914 "Target must be a descendant of the Source.");
917 // The only change required is to add this SCC to the parent set of the
919 TargetC.Parents.insert(this);
922 // Check that the RefSCC is still valid.
927 SmallVector<LazyCallGraph::RefSCC *, 1>
928 LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
929 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
930 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
931 assert(&SourceC != this && "Source must not be in this RefSCC.");
932 #ifdef EXPENSIVE_CHECKS
933 assert(SourceC.isDescendantOf(*this) &&
934 "Source must be a descendant of the Target.");
937 SmallVector<RefSCC *, 1> DeletedRefSCCs;
940 // In a debug build, verify the RefSCC is valid to start with and when this
943 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
946 int SourceIdx = G->RefSCCIndices[&SourceC];
947 int TargetIdx = G->RefSCCIndices[this];
948 assert(SourceIdx < TargetIdx &&
949 "Postorder list doesn't see edge as incoming!");
951 // Compute the RefSCCs which (transitively) reach the source. We do this by
952 // working backwards from the source using the parent set in each RefSCC,
953 // skipping any RefSCCs that don't fall in the postorder range. This has the
954 // advantage of walking the sparser parent edge (in high fan-out graphs) but
955 // more importantly this removes examining all forward edges in all RefSCCs
956 // within the postorder range which aren't in fact connected. Only connected
957 // RefSCCs (and their edges) are visited here.
958 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
959 Set.insert(&SourceC);
960 SmallVector<RefSCC *, 4> Worklist;
961 Worklist.push_back(&SourceC);
963 RefSCC &RC = *Worklist.pop_back_val();
964 for (RefSCC &ParentRC : RC.parents()) {
965 // Skip any RefSCCs outside the range of source to target in the
966 // postorder sequence.
967 int ParentIdx = G->getRefSCCIndex(ParentRC);
968 assert(ParentIdx > SourceIdx && "Parent cannot precede source in postorder!");
969 if (ParentIdx > TargetIdx)
971 if (Set.insert(&ParentRC).second)
972 // First edge connecting to this parent, add it to our worklist.
973 Worklist.push_back(&ParentRC);
975 } while (!Worklist.empty());
978 // Use a normal worklist to find which SCCs the target connects to. We still
979 // bound the search based on the range in the postorder list we care about,
980 // but because this is forward connectivity we just "recurse" through the
982 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
984 SmallVector<RefSCC *, 4> Worklist;
985 Worklist.push_back(this);
987 RefSCC &RC = *Worklist.pop_back_val();
991 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
992 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
993 // Not in the postorder sequence between source and target.
996 if (Set.insert(&EdgeRC).second)
997 Worklist.push_back(&EdgeRC);
999 } while (!Worklist.empty());
1002 // Use a generic helper to update the postorder sequence of RefSCCs and return
1003 // a range of any RefSCCs connected into a cycle by inserting this edge. This
1004 // routine will also take care of updating the indices into the postorder
1006 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
1007 updatePostorderSequenceForEdgeInsertion(
1008 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
1009 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1011 // Build a set so we can do fast tests for whether a RefSCC will end up as
1012 // part of the merged RefSCC.
1013 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
1015 // This RefSCC will always be part of that set, so just insert it here.
1016 MergeSet.insert(this);
1018 // Now that we have identified all of the SCCs which need to be merged into
1019 // a connected set with the inserted edge, merge all of them into this SCC.
1020 SmallVector<SCC *, 16> MergedSCCs;
1022 for (RefSCC *RC : MergeRange) {
1023 assert(RC != this && "We're merging into the target RefSCC, so it "
1024 "shouldn't be in the range.");
1026 // Merge the parents which aren't part of the merge into the our parents.
1027 for (RefSCC *ParentRC : RC->Parents)
1028 if (!MergeSet.count(ParentRC))
1029 Parents.insert(ParentRC);
1030 RC->Parents.clear();
1032 // Walk the inner SCCs to update their up-pointer and walk all the edges to
1033 // update any parent sets.
1034 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1035 // walk by updating the parent sets in some other manner.
1036 for (SCC &InnerC : *RC) {
1037 InnerC.OuterRefSCC = this;
1038 SCCIndices[&InnerC] = SCCIndex++;
1039 for (Node &N : InnerC) {
1040 G->SCCMap[&N] = &InnerC;
1041 for (Edge &E : *N) {
1042 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
1043 if (MergeSet.count(&ChildRC))
1045 ChildRC.Parents.erase(RC);
1046 ChildRC.Parents.insert(this);
1051 // Now merge in the SCCs. We can actually move here so try to reuse storage
1052 // the first time through.
1053 if (MergedSCCs.empty())
1054 MergedSCCs = std::move(RC->SCCs);
1056 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1058 DeletedRefSCCs.push_back(RC);
1061 // Append our original SCCs to the merged list and move it into place.
1062 for (SCC &InnerC : *this)
1063 SCCIndices[&InnerC] = SCCIndex++;
1064 MergedSCCs.append(SCCs.begin(), SCCs.end());
1065 SCCs = std::move(MergedSCCs);
1067 // Remove the merged away RefSCCs from the post order sequence.
1068 for (RefSCC *RC : MergeRange)
1069 G->RefSCCIndices.erase(RC);
1070 int IndexOffset = MergeRange.end() - MergeRange.begin();
1072 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1073 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1074 G->RefSCCIndices[RC] -= IndexOffset;
1076 // At this point we have a merged RefSCC with a post-order SCCs list, just
1077 // connect the nodes to form the new edge.
1078 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
1080 // We return the list of SCCs which were merged so that callers can
1081 // invalidate any data they have associated with those SCCs. Note that these
1082 // SCCs are no longer in an interesting state (they are totally empty) but
1083 // the pointers will remain stable for the life of the graph itself.
1084 return DeletedRefSCCs;
1087 void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1088 assert(G->lookupRefSCC(SourceN) == this &&
1089 "The source must be a member of this RefSCC.");
1091 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1092 assert(&TargetRC != this && "The target must not be a member of this RefSCC");
1094 assert(!is_contained(G->LeafRefSCCs, this) &&
1095 "Cannot have a leaf RefSCC source.");
1098 // In a debug build, verify the RefSCC is valid to start with and when this
1099 // routine finishes.
1101 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1104 // First remove it from the node.
1105 bool Removed = SourceN->removeEdgeInternal(TargetN);
1107 assert(Removed && "Target not in the edge set for this caller?");
1109 bool HasOtherEdgeToChildRC = false;
1110 bool HasOtherChildRC = false;
1111 for (SCC *InnerC : SCCs) {
1112 for (Node &N : *InnerC) {
1113 for (Edge &E : *N) {
1114 RefSCC &OtherChildRC = *G->lookupRefSCC(E.getNode());
1115 if (&OtherChildRC == &TargetRC) {
1116 HasOtherEdgeToChildRC = true;
1119 if (&OtherChildRC != this)
1120 HasOtherChildRC = true;
1122 if (HasOtherEdgeToChildRC)
1125 if (HasOtherEdgeToChildRC)
1128 // Because the SCCs form a DAG, deleting such an edge cannot change the set
1129 // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
1130 // the source SCC no longer connected to the target SCC. If so, we need to
1131 // update the target SCC's map of its parents.
1132 if (!HasOtherEdgeToChildRC) {
1133 bool Removed = TargetRC.Parents.erase(this);
1136 "Did not find the source SCC in the target SCC's parent list!");
1138 // It may orphan an SCC if it is the last edge reaching it, but that does
1139 // not violate any invariants of the graph.
1140 if (TargetRC.Parents.empty())
1141 DEBUG(dbgs() << "LCG: Update removing " << SourceN.getFunction().getName()
1142 << " -> " << TargetN.getFunction().getName()
1143 << " edge orphaned the callee's SCC!\n");
1145 // It may make the Source SCC a leaf SCC.
1146 if (!HasOtherChildRC)
1147 G->LeafRefSCCs.push_back(this);
1151 SmallVector<LazyCallGraph::RefSCC *, 1>
1152 LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
1153 assert(!(*SourceN)[TargetN].isCall() &&
1154 "Cannot remove a call edge, it must first be made a ref edge");
1157 // In a debug build, verify the RefSCC is valid to start with and when this
1158 // routine finishes.
1160 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1163 // First remove the actual edge.
1164 bool Removed = SourceN->removeEdgeInternal(TargetN);
1166 assert(Removed && "Target not in the edge set for this caller?");
1168 // We return a list of the resulting *new* RefSCCs in post-order.
1169 SmallVector<RefSCC *, 1> Result;
1171 // Direct recursion doesn't impact the SCC graph at all.
1172 if (&SourceN == &TargetN)
1175 // If this ref edge is within an SCC then there are sufficient other edges to
1176 // form a cycle without this edge so removing it is a no-op.
1177 SCC &SourceC = *G->lookupSCC(SourceN);
1178 SCC &TargetC = *G->lookupSCC(TargetN);
1179 if (&SourceC == &TargetC)
1182 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
1183 // for each inner SCC. We also store these associated with *nodes* rather
1184 // than SCCs because this saves a round-trip through the node->SCC map and in
1185 // the common case, SCCs are small. We will verify that we always give the
1186 // same number to every node in the SCC such that these are equivalent.
1187 const int RootPostOrderNumber = 0;
1188 int PostOrderNumber = RootPostOrderNumber + 1;
1189 SmallDenseMap<Node *, int> PostOrderMapping;
1191 // Every node in the target SCC can already reach every node in this RefSCC
1192 // (by definition). It is the only node we know will stay inside this RefSCC.
1193 // Everything which transitively reaches Target will also remain in the
1194 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
1195 // back to the root post order number.
1197 // This also enables us to take a very significant short-cut in the standard
1198 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
1199 // references the target node, we know that the target node eventually
1200 // references all other nodes in our walk. As a consequence, we can detect
1201 // and handle participants in that cycle without walking all the edges that
1202 // form the connections, and instead by relying on the fundamental guarantee
1203 // coming into this operation.
1204 for (Node &N : TargetC)
1205 PostOrderMapping[&N] = RootPostOrderNumber;
1207 // Reset all the other nodes to prepare for a DFS over them, and add them to
1209 SmallVector<Node *, 8> Worklist;
1210 for (SCC *C : SCCs) {
1215 N.DFSNumber = N.LowLink = 0;
1217 Worklist.append(C->Nodes.begin(), C->Nodes.end());
1220 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1221 N.DFSNumber = N.LowLink = -1;
1222 PostOrderMapping[&N] = Number;
1225 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
1226 SmallVector<Node *, 4> PendingRefSCCStack;
1228 assert(DFSStack.empty() &&
1229 "Cannot begin a new root with a non-empty DFS stack!");
1230 assert(PendingRefSCCStack.empty() &&
1231 "Cannot begin a new root with pending nodes for an SCC!");
1233 Node *RootN = Worklist.pop_back_val();
1234 // Skip any nodes we've already reached in the DFS.
1235 if (RootN->DFSNumber != 0) {
1236 assert(RootN->DFSNumber == -1 &&
1237 "Shouldn't have any mid-DFS root nodes!");
1241 RootN->DFSNumber = RootN->LowLink = 1;
1242 int NextDFSNumber = 2;
1244 DFSStack.push_back({RootN, (*RootN)->begin()});
1247 EdgeSequence::iterator I;
1248 std::tie(N, I) = DFSStack.pop_back_val();
1249 auto E = (*N)->end();
1251 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1252 "before processing a node.");
1255 Node &ChildN = I->getNode();
1256 if (ChildN.DFSNumber == 0) {
1257 // Mark that we should start at this child when next this node is the
1258 // top of the stack. We don't start at the next child to ensure this
1259 // child's lowlink is reflected.
1260 DFSStack.push_back({N, I});
1262 // Continue, resetting to the child node.
1263 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1265 I = ChildN->begin();
1269 if (ChildN.DFSNumber == -1) {
1270 // Check if this edge's target node connects to the deleted edge's
1271 // target node. If so, we know that every node connected will end up
1272 // in this RefSCC, so collapse the entire current stack into the root
1273 // slot in our SCC numbering. See above for the motivation of
1274 // optimizing the target connected nodes in this way.
1275 auto PostOrderI = PostOrderMapping.find(&ChildN);
1276 if (PostOrderI != PostOrderMapping.end() &&
1277 PostOrderI->second == RootPostOrderNumber) {
1278 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1279 while (!PendingRefSCCStack.empty())
1280 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1281 RootPostOrderNumber);
1282 while (!DFSStack.empty())
1283 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1284 RootPostOrderNumber);
1285 // Ensure we break all the way out of the enclosing loop.
1290 // If this child isn't currently in this RefSCC, no need to process
1291 // it. However, we do need to remove this RefSCC from its RefSCC's
1293 RefSCC &ChildRC = *G->lookupRefSCC(ChildN);
1294 ChildRC.Parents.erase(this);
1299 // Track the lowest link of the children, if any are still in the stack.
1300 // Any child not on the stack will have a LowLink of -1.
1301 assert(ChildN.LowLink != 0 &&
1302 "Low-link must not be zero with a non-zero DFS number.");
1303 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1304 N->LowLink = ChildN.LowLink;
1308 // We short-circuited this node.
1311 // We've finished processing N and its descendents, put it on our pending
1312 // stack to eventually get merged into a RefSCC.
1313 PendingRefSCCStack.push_back(N);
1315 // If this node is linked to some lower entry, continue walking up the
1317 if (N->LowLink != N->DFSNumber) {
1318 assert(!DFSStack.empty() &&
1319 "We never found a viable root for a RefSCC to pop off!");
1323 // Otherwise, form a new RefSCC from the top of the pending node stack.
1324 int RootDFSNumber = N->DFSNumber;
1325 // Find the range of the node stack by walking down until we pass the
1327 auto RefSCCNodes = make_range(
1328 PendingRefSCCStack.rbegin(),
1329 find_if(reverse(PendingRefSCCStack), [RootDFSNumber](const Node *N) {
1330 return N->DFSNumber < RootDFSNumber;
1333 // Mark the postorder number for these nodes and clear them off the
1334 // stack. We'll use the postorder number to pull them into RefSCCs at the
1335 // end. FIXME: Fuse with the loop above.
1336 int RefSCCNumber = PostOrderNumber++;
1337 for (Node *N : RefSCCNodes)
1338 MarkNodeForSCCNumber(*N, RefSCCNumber);
1340 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1341 PendingRefSCCStack.end());
1342 } while (!DFSStack.empty());
1344 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
1345 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
1346 } while (!Worklist.empty());
1348 // We now have a post-order numbering for RefSCCs and a mapping from each
1349 // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1350 // (re-using this RefSCC node for the root) and build a radix-sort style map
1351 // from postorder number to the RefSCC. We then append SCCs to each of these
1352 // RefSCCs in the order they occured in the original SCCs container.
1353 for (int i = 1; i < PostOrderNumber; ++i)
1354 Result.push_back(G->createRefSCC(*G));
1356 // Insert the resulting postorder sequence into the global graph postorder
1357 // sequence before the current RefSCC in that sequence. The idea being that
1358 // this RefSCC is the target of the reference edge removed, and thus has
1359 // a direct or indirect edge to every other RefSCC formed and so must be at
1360 // the end of any postorder traversal.
1362 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1363 // range over the global postorder sequence and generally use that sequence
1364 // rather than building a separate result vector here.
1365 if (!Result.empty()) {
1366 int Idx = G->getRefSCCIndex(*this);
1367 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx,
1368 Result.begin(), Result.end());
1369 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1370 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1371 assert(G->PostOrderRefSCCs[G->getRefSCCIndex(*this)] == this &&
1372 "Failed to update this RefSCC's index after insertion!");
1375 for (SCC *C : SCCs) {
1376 auto PostOrderI = PostOrderMapping.find(&*C->begin());
1377 assert(PostOrderI != PostOrderMapping.end() &&
1378 "Cannot have missing mappings for nodes!");
1379 int SCCNumber = PostOrderI->second;
1382 assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1383 "Cannot have different numbers for nodes in the same SCC!");
1386 // The root node is handled separately by removing the SCCs.
1389 RefSCC &RC = *Result[SCCNumber - 1];
1390 int SCCIndex = RC.SCCs.size();
1391 RC.SCCs.push_back(C);
1392 RC.SCCIndices[C] = SCCIndex;
1393 C->OuterRefSCC = &RC;
1396 // FIXME: We re-walk the edges in each RefSCC to establish whether it is
1397 // a leaf and connect it to the rest of the graph's parents lists. This is
1398 // really wasteful. We should instead do this during the DFS to avoid yet
1399 // another edge walk.
1400 for (RefSCC *RC : Result)
1401 G->connectRefSCC(*RC);
1403 // Now erase all but the root's SCCs.
1404 SCCs.erase(remove_if(SCCs,
1406 return PostOrderMapping.lookup(&*C->begin()) !=
1407 RootPostOrderNumber;
1411 for (int i = 0, Size = SCCs.size(); i < Size; ++i)
1412 SCCIndices[SCCs[i]] = i;
1415 // Now we need to reconnect the current (root) SCC to the graph. We do this
1416 // manually because we can special case our leaf handling and detect errors.
1420 for (Node &N : *C) {
1421 for (Edge &E : *N) {
1422 RefSCC &ChildRC = *G->lookupRefSCC(E.getNode());
1423 if (&ChildRC == this)
1425 ChildRC.Parents.insert(this);
1432 if (!Result.empty())
1433 assert(!IsLeaf && "This SCC cannot be a leaf as we have split out new "
1434 "SCCs by removing this edge.");
1435 if (none_of(G->LeafRefSCCs, [&](RefSCC *C) { return C == this; }))
1436 assert(!IsLeaf && "This SCC cannot be a leaf as it already had child "
1437 "SCCs before we removed this edge.");
1439 // And connect both this RefSCC and all the new ones to the correct parents.
1440 // The easiest way to do this is just to re-analyze the old parent set.
1441 SmallVector<RefSCC *, 4> OldParents(Parents.begin(), Parents.end());
1443 for (RefSCC *ParentRC : OldParents)
1444 for (SCC &ParentC : *ParentRC)
1445 for (Node &ParentN : ParentC)
1446 for (Edge &E : *ParentN) {
1447 RefSCC &RC = *G->lookupRefSCC(E.getNode());
1448 if (&RC != ParentRC)
1449 RC.Parents.insert(ParentRC);
1452 // If this SCC stopped being a leaf through this edge removal, remove it from
1453 // the leaf SCC list. Note that this DTRT in the case where this was never
1455 // FIXME: As LeafRefSCCs could be very large, we might want to not walk the
1456 // entire list if this RefSCC wasn't a leaf before the edge removal.
1457 if (!Result.empty())
1458 G->LeafRefSCCs.erase(
1459 std::remove(G->LeafRefSCCs.begin(), G->LeafRefSCCs.end(), this),
1460 G->LeafRefSCCs.end());
1463 // Verify all of the new RefSCCs.
1464 for (RefSCC *RC : Result)
1468 // Return the new list of SCCs.
1472 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1474 // The only trivial case that requires any graph updates is when we add new
1475 // ref edge and may connect different RefSCCs along that path. This is only
1476 // because of the parents set. Every other part of the graph remains constant
1477 // after this edge insertion.
1478 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1479 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1480 if (&TargetRC == this) {
1485 #ifdef EXPENSIVE_CHECKS
1486 assert(TargetRC.isDescendantOf(*this) &&
1487 "Target must be a descendant of the Source.");
1489 // The only change required is to add this RefSCC to the parent set of the
1490 // target. This is a set and so idempotent if the edge already existed.
1491 TargetRC.Parents.insert(this);
1494 void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1497 // Check that the RefSCC is still valid when we finish.
1498 auto ExitVerifier = make_scope_exit([this] { verify(); });
1500 #ifdef EXPENSIVE_CHECKS
1501 // Check that we aren't breaking some invariants of the SCC graph. Note that
1502 // this is quadratic in the number of edges in the call graph!
1503 SCC &SourceC = *G->lookupSCC(SourceN);
1504 SCC &TargetC = *G->lookupSCC(TargetN);
1505 if (&SourceC != &TargetC)
1506 assert(SourceC.isAncestorOf(TargetC) &&
1507 "Call edge is not trivial in the SCC graph!");
1508 #endif // EXPENSIVE_CHECKS
1511 // First insert it into the source or find the existing edge.
1513 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1514 if (!InsertResult.second) {
1515 // Already an edge, just update it.
1516 Edge &E = SourceN->Edges[InsertResult.first->second];
1518 return; // Nothing to do!
1519 E.setKind(Edge::Call);
1521 // Create the new edge.
1522 SourceN->Edges.emplace_back(TargetN, Edge::Call);
1525 // Now that we have the edge, handle the graph fallout.
1526 handleTrivialEdgeInsertion(SourceN, TargetN);
1529 void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1531 // Check that the RefSCC is still valid when we finish.
1532 auto ExitVerifier = make_scope_exit([this] { verify(); });
1534 #ifdef EXPENSIVE_CHECKS
1535 // Check that we aren't breaking some invariants of the RefSCC graph.
1536 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1537 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1538 if (&SourceRC != &TargetRC)
1539 assert(SourceRC.isAncestorOf(TargetRC) &&
1540 "Ref edge is not trivial in the RefSCC graph!");
1541 #endif // EXPENSIVE_CHECKS
1544 // First insert it into the source or find the existing edge.
1546 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
1547 if (!InsertResult.second)
1548 // Already an edge, we're done.
1551 // Create the new edge.
1552 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
1554 // Now that we have the edge, handle the graph fallout.
1555 handleTrivialEdgeInsertion(SourceN, TargetN);
1558 void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1559 Function &OldF = N.getFunction();
1562 // Check that the RefSCC is still valid when we finish.
1563 auto ExitVerifier = make_scope_exit([this] { verify(); });
1565 assert(G->lookupRefSCC(N) == this &&
1566 "Cannot replace the function of a node outside this RefSCC.");
1568 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1569 "Must not have already walked the new function!'");
1571 // It is important that this replacement not introduce graph changes so we
1572 // insist that the caller has already removed every use of the original
1573 // function and that all uses of the new function correspond to existing
1574 // edges in the graph. The common and expected way to use this is when
1575 // replacing the function itself in the IR without changing the call graph
1576 // shape and just updating the analysis based on that.
1577 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1578 assert(OldF.use_empty() &&
1579 "Must have moved all uses from the old function to the new!");
1582 N.replaceFunction(NewF);
1584 // Update various call graph maps.
1585 G->NodeMap.erase(&OldF);
1586 G->NodeMap[&NewF] = &N;
1589 void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
1590 assert(SCCMap.empty() &&
1591 "This method cannot be called after SCCs have been formed!");
1593 return SourceN->insertEdgeInternal(TargetN, EK);
1596 void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1597 assert(SCCMap.empty() &&
1598 "This method cannot be called after SCCs have been formed!");
1600 bool Removed = SourceN->removeEdgeInternal(TargetN);
1602 assert(Removed && "Target not in the edge set for this caller?");
1605 void LazyCallGraph::removeDeadFunction(Function &F) {
1606 // FIXME: This is unnecessarily restrictive. We should be able to remove
1607 // functions which recursively call themselves.
1608 assert(F.use_empty() &&
1609 "This routine should only be called on trivially dead functions!");
1611 // We shouldn't remove library functions as they are never really dead while
1612 // the call graph is in use -- every function definition refers to them.
1613 assert(!isLibFunction(F) &&
1614 "Must not remove lib functions from the call graph!");
1616 auto NI = NodeMap.find(&F);
1617 if (NI == NodeMap.end())
1618 // Not in the graph at all!
1621 Node &N = *NI->second;
1624 // Remove this from the entry edges if present.
1625 EntryEdges.removeEdgeInternal(N);
1627 if (SCCMap.empty()) {
1628 // No SCCs have been formed, so removing this is fine and there is nothing
1629 // else necessary at this point but clearing out the node.
1634 // Cannot remove a function which has yet to be visited in the DFS walk, so
1635 // if we have a node at all then we must have an SCC and RefSCC.
1636 auto CI = SCCMap.find(&N);
1637 assert(CI != SCCMap.end() &&
1638 "Tried to remove a node without an SCC after DFS walk started!");
1639 SCC &C = *CI->second;
1641 RefSCC &RC = C.getOuterRefSCC();
1643 // This node must be the only member of its SCC as it has no callers, and
1644 // that SCC must be the only member of a RefSCC as it has no references.
1645 // Validate these properties first.
1646 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1647 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
1649 // Clean up any remaining reference edges. Note that we walk an unordered set
1650 // here but are just removing and so the order doesn't matter.
1651 for (RefSCC &ParentRC : RC.parents())
1652 for (SCC &ParentC : ParentRC)
1653 for (Node &ParentN : ParentC)
1655 ParentN->removeEdgeInternal(N);
1657 // Now remove this RefSCC from any parents sets and the leaf list.
1659 if (RefSCC *TargetRC = lookupRefSCC(E.getNode()))
1660 TargetRC->Parents.erase(&RC);
1661 // FIXME: This is a linear operation which could become hot and benefit from
1663 auto LRI = find(LeafRefSCCs, &RC);
1664 if (LRI != LeafRefSCCs.end())
1665 LeafRefSCCs.erase(LRI);
1667 auto RCIndexI = RefSCCIndices.find(&RC);
1668 int RCIndex = RCIndexI->second;
1669 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1670 RefSCCIndices.erase(RCIndexI);
1671 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1672 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1674 // Finally clear out all the data structures from the node down through the
1680 // Nothing to delete as all the objects are allocated in stable bump pointer
1684 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1685 return *new (MappedN = BPA.Allocate()) Node(*this, F);
1688 void LazyCallGraph::updateGraphPtrs() {
1689 // Process all nodes updating the graph pointers.
1691 SmallVector<Node *, 16> Worklist;
1692 for (Edge &E : EntryEdges)
1693 Worklist.push_back(&E.getNode());
1695 while (!Worklist.empty()) {
1696 Node &N = *Worklist.pop_back_val();
1700 Worklist.push_back(&E.getNode());
1704 // Process all SCCs updating the graph pointers.
1706 SmallVector<RefSCC *, 16> Worklist(LeafRefSCCs.begin(), LeafRefSCCs.end());
1708 while (!Worklist.empty()) {
1709 RefSCC &C = *Worklist.pop_back_val();
1711 for (RefSCC &ParentC : C.parents())
1712 Worklist.push_back(&ParentC);
1717 template <typename RootsT, typename GetBeginT, typename GetEndT,
1718 typename GetNodeT, typename FormSCCCallbackT>
1719 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1720 GetEndT &&GetEnd, GetNodeT &&GetNode,
1721 FormSCCCallbackT &&FormSCC) {
1722 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT;
1724 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
1725 SmallVector<Node *, 16> PendingSCCStack;
1727 // Scan down the stack and DFS across the call edges.
1728 for (Node *RootN : Roots) {
1729 assert(DFSStack.empty() &&
1730 "Cannot begin a new root with a non-empty DFS stack!");
1731 assert(PendingSCCStack.empty() &&
1732 "Cannot begin a new root with pending nodes for an SCC!");
1734 // Skip any nodes we've already reached in the DFS.
1735 if (RootN->DFSNumber != 0) {
1736 assert(RootN->DFSNumber == -1 &&
1737 "Shouldn't have any mid-DFS root nodes!");
1741 RootN->DFSNumber = RootN->LowLink = 1;
1742 int NextDFSNumber = 2;
1744 DFSStack.push_back({RootN, GetBegin(*RootN)});
1748 std::tie(N, I) = DFSStack.pop_back_val();
1749 auto E = GetEnd(*N);
1751 Node &ChildN = GetNode(I);
1752 if (ChildN.DFSNumber == 0) {
1753 // We haven't yet visited this child, so descend, pushing the current
1754 // node onto the stack.
1755 DFSStack.push_back({N, I});
1757 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1764 // If the child has already been added to some child component, it
1765 // couldn't impact the low-link of this parent because it isn't
1766 // connected, and thus its low-link isn't relevant so skip it.
1767 if (ChildN.DFSNumber == -1) {
1772 // Track the lowest linked child as the lowest link for this node.
1773 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1774 if (ChildN.LowLink < N->LowLink)
1775 N->LowLink = ChildN.LowLink;
1777 // Move to the next edge.
1781 // We've finished processing N and its descendents, put it on our pending
1782 // SCC stack to eventually get merged into an SCC of nodes.
1783 PendingSCCStack.push_back(N);
1785 // If this node is linked to some lower entry, continue walking up the
1787 if (N->LowLink != N->DFSNumber)
1790 // Otherwise, we've completed an SCC. Append it to our post order list of
1792 int RootDFSNumber = N->DFSNumber;
1793 // Find the range of the node stack by walking down until we pass the
1795 auto SCCNodes = make_range(
1796 PendingSCCStack.rbegin(),
1797 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1798 return N->DFSNumber < RootDFSNumber;
1800 // Form a new SCC out of these nodes and then clear them off our pending
1803 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1804 } while (!DFSStack.empty());
1808 /// Build the internal SCCs for a RefSCC from a sequence of nodes.
1810 /// Appends the SCCs to the provided vector and updates the map with their
1811 /// indices. Both the vector and map must be empty when passed into this
1813 void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1814 assert(RC.SCCs.empty() && "Already built SCCs!");
1815 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1817 for (Node *N : Nodes) {
1818 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1819 "We cannot have a low link in an SCC lower than its root on the "
1822 // This node will go into the next RefSCC, clear out its DFS and low link
1824 N->DFSNumber = N->LowLink = 0;
1827 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1828 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1829 // internal storage as we won't need it for the outer graph's DFS any longer.
1831 Nodes, [](Node &N) { return N->call_begin(); },
1832 [](Node &N) { return N->call_end(); },
1833 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1834 [this, &RC](node_stack_range Nodes) {
1835 RC.SCCs.push_back(createSCC(RC, Nodes));
1836 for (Node &N : *RC.SCCs.back()) {
1837 N.DFSNumber = N.LowLink = -1;
1838 SCCMap[&N] = RC.SCCs.back();
1842 // Wire up the SCC indices.
1843 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1844 RC.SCCIndices[RC.SCCs[i]] = i;
1847 void LazyCallGraph::buildRefSCCs() {
1848 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1849 // RefSCCs are either non-existent or already built!
1852 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1854 SmallVector<Node *, 16> Roots;
1855 for (Edge &E : *this)
1856 Roots.push_back(&E.getNode());
1858 // The roots will be popped of a stack, so use reverse to get a less
1859 // surprising order. This doesn't change any of the semantics anywhere.
1860 std::reverse(Roots.begin(), Roots.end());
1865 // We need to populate each node as we begin to walk its edges.
1869 [](Node &N) { return N->end(); },
1870 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
1871 [this](node_stack_range Nodes) {
1872 RefSCC *NewRC = createRefSCC(*this);
1873 buildSCCs(*NewRC, Nodes);
1874 connectRefSCC(*NewRC);
1876 // Push the new node into the postorder list and remember its position
1877 // in the index map.
1879 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1881 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1882 PostOrderRefSCCs.push_back(NewRC);
1889 // FIXME: We should move callers of this to embed the parent linking and leaf
1890 // tracking into their DFS in order to remove a full walk of all edges.
1891 void LazyCallGraph::connectRefSCC(RefSCC &RC) {
1892 // Walk all edges in the RefSCC (this remains linear as we only do this once
1893 // when we build the RefSCC) to connect it to the parent sets of its
1898 for (Edge &E : *N) {
1899 RefSCC &ChildRC = *lookupRefSCC(E.getNode());
1900 if (&ChildRC == &RC)
1902 ChildRC.Parents.insert(&RC);
1906 // For the SCCs where we find no child SCCs, add them to the leaf list.
1908 LeafRefSCCs.push_back(&RC);
1911 AnalysisKey LazyCallGraphAnalysis::Key;
1913 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1915 static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
1916 OS << " Edges in function: " << N.getFunction().getName() << "\n";
1917 for (LazyCallGraph::Edge &E : N.populate())
1918 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1919 << E.getFunction().getName() << "\n";
1924 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1925 ptrdiff_t Size = std::distance(C.begin(), C.end());
1926 OS << " SCC with " << Size << " functions:\n";
1928 for (LazyCallGraph::Node &N : C)
1929 OS << " " << N.getFunction().getName() << "\n";
1932 static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
1933 ptrdiff_t Size = std::distance(C.begin(), C.end());
1934 OS << " RefSCC with " << Size << " call SCCs:\n";
1936 for (LazyCallGraph::SCC &InnerC : C)
1937 printSCC(OS, InnerC);
1942 PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
1943 ModuleAnalysisManager &AM) {
1944 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1946 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1949 for (Function &F : M)
1950 printNode(OS, G.get(F));
1953 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1956 return PreservedAnalyses::all();
1959 LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1962 static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1963 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1965 for (LazyCallGraph::Edge &E : N.populate()) {
1966 OS << " " << Name << " -> \""
1967 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1968 if (!E.isCall()) // It is a ref edge.
1969 OS << " [style=dashed,label=\"ref\"]";
1976 PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1977 ModuleAnalysisManager &AM) {
1978 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1980 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1982 for (Function &F : M)
1983 printNodeDOT(OS, G.get(F));
1987 return PreservedAnalyses::all();