LLVM API Documentation

LazyCallGraph.cpp
Go to the documentation of this file.
00001 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/Analysis/LazyCallGraph.h"
00011 #include "llvm/ADT/STLExtras.h"
00012 #include "llvm/IR/CallSite.h"
00013 #include "llvm/IR/InstVisitor.h"
00014 #include "llvm/IR/Instructions.h"
00015 #include "llvm/IR/PassManager.h"
00016 #include "llvm/Support/Debug.h"
00017 #include "llvm/Support/raw_ostream.h"
00018 
00019 using namespace llvm;
00020 
00021 #define DEBUG_TYPE "lcg"
00022 
00023 static void findCallees(
00024     SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
00025     SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
00026     DenseMap<Function *, size_t> &CalleeIndexMap) {
00027   while (!Worklist.empty()) {
00028     Constant *C = Worklist.pop_back_val();
00029 
00030     if (Function *F = dyn_cast<Function>(C)) {
00031       // Note that we consider *any* function with a definition to be a viable
00032       // edge. Even if the function's definition is subject to replacement by
00033       // some other module (say, a weak definition) there may still be
00034       // optimizations which essentially speculate based on the definition and
00035       // a way to check that the specific definition is in fact the one being
00036       // used. For example, this could be done by moving the weak definition to
00037       // a strong (internal) definition and making the weak definition be an
00038       // alias. Then a test of the address of the weak function against the new
00039       // strong definition's address would be an effective way to determine the
00040       // safety of optimizing a direct call edge.
00041       if (!F->isDeclaration() &&
00042           CalleeIndexMap.insert(std::make_pair(F, Callees.size())).second) {
00043         DEBUG(dbgs() << "    Added callable function: " << F->getName()
00044                      << "\n");
00045         Callees.push_back(F);
00046       }
00047       continue;
00048     }
00049 
00050     for (Value *Op : C->operand_values())
00051       if (Visited.insert(cast<Constant>(Op)))
00052         Worklist.push_back(cast<Constant>(Op));
00053   }
00054 }
00055 
00056 LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
00057     : G(&G), F(F), DFSNumber(0), LowLink(0) {
00058   DEBUG(dbgs() << "  Adding functions called by '" << F.getName()
00059                << "' to the graph.\n");
00060 
00061   SmallVector<Constant *, 16> Worklist;
00062   SmallPtrSet<Constant *, 16> Visited;
00063   // Find all the potential callees in this function. First walk the
00064   // instructions and add every operand which is a constant to the worklist.
00065   for (BasicBlock &BB : F)
00066     for (Instruction &I : BB)
00067       for (Value *Op : I.operand_values())
00068         if (Constant *C = dyn_cast<Constant>(Op))
00069           if (Visited.insert(C))
00070             Worklist.push_back(C);
00071 
00072   // We've collected all the constant (and thus potentially function or
00073   // function containing) operands to all of the instructions in the function.
00074   // Process them (recursively) collecting every function found.
00075   findCallees(Worklist, Visited, Callees, CalleeIndexMap);
00076 }
00077 
00078 void LazyCallGraph::Node::insertEdgeInternal(Function &Callee) {
00079   if (Node *N = G->lookup(Callee))
00080     return insertEdgeInternal(*N);
00081 
00082   CalleeIndexMap.insert(std::make_pair(&Callee, Callees.size()));
00083   Callees.push_back(&Callee);
00084 }
00085 
00086 void LazyCallGraph::Node::insertEdgeInternal(Node &CalleeN) {
00087   CalleeIndexMap.insert(std::make_pair(&CalleeN.getFunction(), Callees.size()));
00088   Callees.push_back(&CalleeN);
00089 }
00090 
00091 void LazyCallGraph::Node::removeEdgeInternal(Function &Callee) {
00092   auto IndexMapI = CalleeIndexMap.find(&Callee);
00093   assert(IndexMapI != CalleeIndexMap.end() &&
00094          "Callee not in the callee set for this caller?");
00095 
00096   Callees[IndexMapI->second] = nullptr;
00097   CalleeIndexMap.erase(IndexMapI);
00098 }
00099 
00100 LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
00101   DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
00102                << "\n");
00103   for (Function &F : M)
00104     if (!F.isDeclaration() && !F.hasLocalLinkage())
00105       if (EntryIndexMap.insert(std::make_pair(&F, EntryNodes.size())).second) {
00106         DEBUG(dbgs() << "  Adding '" << F.getName()
00107                      << "' to entry set of the graph.\n");
00108         EntryNodes.push_back(&F);
00109       }
00110 
00111   // Now add entry nodes for functions reachable via initializers to globals.
00112   SmallVector<Constant *, 16> Worklist;
00113   SmallPtrSet<Constant *, 16> Visited;
00114   for (GlobalVariable &GV : M.globals())
00115     if (GV.hasInitializer())
00116       if (Visited.insert(GV.getInitializer()))
00117         Worklist.push_back(GV.getInitializer());
00118 
00119   DEBUG(dbgs() << "  Adding functions referenced by global initializers to the "
00120                   "entry set.\n");
00121   findCallees(Worklist, Visited, EntryNodes, EntryIndexMap);
00122 
00123   for (auto &Entry : EntryNodes) {
00124     assert(!Entry.isNull() &&
00125            "We can't have removed edges before we finish the constructor!");
00126     if (Function *F = Entry.dyn_cast<Function *>())
00127       SCCEntryNodes.push_back(F);
00128     else
00129       SCCEntryNodes.push_back(&Entry.get<Node *>()->getFunction());
00130   }
00131 }
00132 
00133 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
00134     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
00135       EntryNodes(std::move(G.EntryNodes)),
00136       EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
00137       SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
00138       DFSStack(std::move(G.DFSStack)),
00139       SCCEntryNodes(std::move(G.SCCEntryNodes)),
00140       NextDFSNumber(G.NextDFSNumber) {
00141   updateGraphPtrs();
00142 }
00143 
00144 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
00145   BPA = std::move(G.BPA);
00146   NodeMap = std::move(G.NodeMap);
00147   EntryNodes = std::move(G.EntryNodes);
00148   EntryIndexMap = std::move(G.EntryIndexMap);
00149   SCCBPA = std::move(G.SCCBPA);
00150   SCCMap = std::move(G.SCCMap);
00151   LeafSCCs = std::move(G.LeafSCCs);
00152   DFSStack = std::move(G.DFSStack);
00153   SCCEntryNodes = std::move(G.SCCEntryNodes);
00154   NextDFSNumber = G.NextDFSNumber;
00155   updateGraphPtrs();
00156   return *this;
00157 }
00158 
00159 void LazyCallGraph::SCC::insert(Node &N) {
00160   N.DFSNumber = N.LowLink = -1;
00161   Nodes.push_back(&N);
00162   G->SCCMap[&N] = this;
00163 }
00164 
00165 bool LazyCallGraph::SCC::isDescendantOf(const SCC &C) const {
00166   // Walk up the parents of this SCC and verify that we eventually find C.
00167   SmallVector<const SCC *, 4> AncestorWorklist;
00168   AncestorWorklist.push_back(this);
00169   do {
00170     const SCC *AncestorC = AncestorWorklist.pop_back_val();
00171     if (AncestorC->isChildOf(C))
00172       return true;
00173     for (const SCC *ParentC : AncestorC->ParentSCCs)
00174       AncestorWorklist.push_back(ParentC);
00175   } while (!AncestorWorklist.empty());
00176 
00177   return false;
00178 }
00179 
00180 void LazyCallGraph::SCC::insertIntraSCCEdge(Node &CallerN, Node &CalleeN) {
00181   // First insert it into the caller.
00182   CallerN.insertEdgeInternal(CalleeN);
00183 
00184   assert(G->SCCMap.lookup(&CallerN) == this && "Caller must be in this SCC.");
00185   assert(G->SCCMap.lookup(&CalleeN) == this && "Callee must be in this SCC.");
00186 
00187   // Nothing changes about this SCC or any other.
00188 }
00189 
00190 void LazyCallGraph::SCC::insertOutgoingEdge(Node &CallerN, Node &CalleeN) {
00191   // First insert it into the caller.
00192   CallerN.insertEdgeInternal(CalleeN);
00193 
00194   assert(G->SCCMap.lookup(&CallerN) == this && "Caller must be in this SCC.");
00195 
00196   SCC &CalleeC = *G->SCCMap.lookup(&CalleeN);
00197   assert(&CalleeC != this && "Callee must not be in this SCC.");
00198   assert(CalleeC.isDescendantOf(*this) &&
00199          "Callee must be a descendant of the Caller.");
00200 
00201   // The only change required is to add this SCC to the parent set of the callee.
00202   CalleeC.ParentSCCs.insert(this);
00203 }
00204 
00205 SmallVector<LazyCallGraph::SCC *, 1>
00206 LazyCallGraph::SCC::insertIncomingEdge(Node &CallerN, Node &CalleeN) {
00207   // First insert it into the caller.
00208   CallerN.insertEdgeInternal(CalleeN);
00209 
00210   assert(G->SCCMap.lookup(&CalleeN) == this && "Callee must be in this SCC.");
00211 
00212   SCC &CallerC = *G->SCCMap.lookup(&CallerN);
00213   assert(&CallerC != this && "Caller must not be in this SCC.");
00214   assert(CallerC.isDescendantOf(*this) &&
00215          "Caller must be a descendant of the Callee.");
00216 
00217   // The algorithm we use for merging SCCs based on the cycle introduced here
00218   // is to walk the SCC inverted DAG formed by the parent SCC sets. The inverse
00219   // graph has the same cycle properties as the actual DAG of the SCCs, and
00220   // when forming SCCs lazily by a DFS, the bottom of the graph won't exist in
00221   // many cases which should prune the search space.
00222   //
00223   // FIXME: We can get this pruning behavior even after the incremental SCC
00224   // formation by leaving behind (conservative) DFS numberings in the nodes,
00225   // and pruning the search with them. These would need to be cleverly updated
00226   // during the removal of intra-SCC edges, but could be preserved
00227   // conservatively.
00228 
00229   // The set of SCCs that are connected to the caller, and thus will
00230   // participate in the merged connected component.
00231   SmallPtrSet<SCC *, 8> ConnectedSCCs;
00232   ConnectedSCCs.insert(this);
00233   ConnectedSCCs.insert(&CallerC);
00234 
00235   // We build up a DFS stack of the parents chains.
00236   SmallVector<std::pair<SCC *, SCC::parent_iterator>, 8> DFSSCCs;
00237   SmallPtrSet<SCC *, 8> VisitedSCCs;
00238   int ConnectedDepth = -1;
00239   SCC *C = this;
00240   parent_iterator I = parent_begin(), E = parent_end();
00241   for (;;) {
00242     while (I != E) {
00243       SCC &ParentSCC = *I++;
00244 
00245       // If we have already processed this parent SCC, skip it, and remember
00246       // whether it was connected so we don't have to check the rest of the
00247       // stack. This also handles when we reach a child of the 'this' SCC (the
00248       // callee) which terminates the search.
00249       if (ConnectedSCCs.count(&ParentSCC)) {
00250         ConnectedDepth = std::max<int>(ConnectedDepth, DFSSCCs.size());
00251         continue;
00252       }
00253       if (VisitedSCCs.count(&ParentSCC))
00254         continue;
00255 
00256       // We fully explore the depth-first space, adding nodes to the connected
00257       // set only as we pop them off, so "recurse" by rotating to the parent.
00258       DFSSCCs.push_back(std::make_pair(C, I));
00259       C = &ParentSCC;
00260       I = ParentSCC.parent_begin();
00261       E = ParentSCC.parent_end();
00262     }
00263 
00264     // If we've found a connection anywhere below this point on the stack (and
00265     // thus up the parent graph from the caller), the current node needs to be
00266     // added to the connected set now that we've processed all of its parents.
00267     if ((int)DFSSCCs.size() == ConnectedDepth) {
00268       --ConnectedDepth; // We're finished with this connection.
00269       ConnectedSCCs.insert(C);
00270     } else {
00271       // Otherwise remember that its parents don't ever connect.
00272       assert(ConnectedDepth < (int)DFSSCCs.size() &&
00273              "Cannot have a connected depth greater than the DFS depth!");
00274       VisitedSCCs.insert(C);
00275     }
00276 
00277     if (DFSSCCs.empty())
00278       break; // We've walked all the parents of the caller transitively.
00279 
00280     // Pop off the prior node and position to unwind the depth first recursion.
00281     std::tie(C, I) = DFSSCCs.pop_back_val();
00282     E = C->parent_end();
00283   }
00284 
00285   // Now that we have identified all of the SCCs which need to be merged into
00286   // a connected set with the inserted edge, merge all of them into this SCC.
00287   // FIXME: This operation currently creates ordering stability problems
00288   // because we don't use stably ordered containers for the parent SCCs or the
00289   // connected SCCs.
00290   unsigned NewNodeBeginIdx = Nodes.size();
00291   for (SCC *C : ConnectedSCCs) {
00292     if (C == this)
00293       continue;
00294     for (SCC *ParentC : C->ParentSCCs)
00295       if (!ConnectedSCCs.count(ParentC))
00296         ParentSCCs.insert(ParentC);
00297     C->ParentSCCs.clear();
00298 
00299     for (Node *N : *C) {
00300       for (Node &ChildN : *N) {
00301         SCC &ChildC = *G->SCCMap.lookup(&ChildN);
00302         if (&ChildC != C)
00303           ChildC.ParentSCCs.erase(C);
00304       }
00305       G->SCCMap[N] = this;
00306       Nodes.push_back(N);
00307     }
00308     C->Nodes.clear();
00309   }
00310   for (auto I = Nodes.begin() + NewNodeBeginIdx, E = Nodes.end(); I != E; ++I)
00311     for (Node &ChildN : **I) {
00312       SCC &ChildC = *G->SCCMap.lookup(&ChildN);
00313       if (&ChildC != this)
00314         ChildC.ParentSCCs.insert(this);
00315     }
00316 
00317   // We return the list of SCCs which were merged so that callers can
00318   // invalidate any data they have associated with those SCCs. Note that these
00319   // SCCs are no longer in an interesting state (they are totally empty) but
00320   // the pointers will remain stable for the life of the graph itself.
00321   return SmallVector<SCC *, 1>(ConnectedSCCs.begin(), ConnectedSCCs.end());
00322 }
00323 
00324 void LazyCallGraph::SCC::removeInterSCCEdge(Node &CallerN, Node &CalleeN) {
00325   // First remove it from the node.
00326   CallerN.removeEdgeInternal(CalleeN.getFunction());
00327 
00328   assert(G->SCCMap.lookup(&CallerN) == this &&
00329          "The caller must be a member of this SCC.");
00330 
00331   SCC &CalleeC = *G->SCCMap.lookup(&CalleeN);
00332   assert(&CalleeC != this &&
00333          "This API only supports the rmoval of inter-SCC edges.");
00334 
00335   assert(std::find(G->LeafSCCs.begin(), G->LeafSCCs.end(), this) ==
00336              G->LeafSCCs.end() &&
00337          "Cannot have a leaf SCC caller with a different SCC callee.");
00338 
00339   bool HasOtherCallToCalleeC = false;
00340   bool HasOtherCallOutsideSCC = false;
00341   for (Node *N : *this) {
00342     for (Node &OtherCalleeN : *N) {
00343       SCC &OtherCalleeC = *G->SCCMap.lookup(&OtherCalleeN);
00344       if (&OtherCalleeC == &CalleeC) {
00345         HasOtherCallToCalleeC = true;
00346         break;
00347       }
00348       if (&OtherCalleeC != this)
00349         HasOtherCallOutsideSCC = true;
00350     }
00351     if (HasOtherCallToCalleeC)
00352       break;
00353   }
00354   // Because the SCCs form a DAG, deleting such an edge cannot change the set
00355   // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
00356   // the caller no longer a parent of the callee. Walk the other call edges
00357   // in the caller to tell.
00358   if (!HasOtherCallToCalleeC) {
00359     bool Removed = CalleeC.ParentSCCs.erase(this);
00360     (void)Removed;
00361     assert(Removed &&
00362            "Did not find the caller SCC in the callee SCC's parent list!");
00363 
00364     // It may orphan an SCC if it is the last edge reaching it, but that does
00365     // not violate any invariants of the graph.
00366     if (CalleeC.ParentSCCs.empty())
00367       DEBUG(dbgs() << "LCG: Update removing " << CallerN.getFunction().getName()
00368                    << " -> " << CalleeN.getFunction().getName()
00369                    << " edge orphaned the callee's SCC!\n");
00370   }
00371 
00372   // It may make the Caller SCC a leaf SCC.
00373   if (!HasOtherCallOutsideSCC)
00374     G->LeafSCCs.push_back(this);
00375 }
00376 
00377 void LazyCallGraph::SCC::internalDFS(
00378     SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack,
00379     SmallVectorImpl<Node *> &PendingSCCStack, Node *N,
00380     SmallVectorImpl<SCC *> &ResultSCCs) {
00381   Node::iterator I = N->begin();
00382   N->LowLink = N->DFSNumber = 1;
00383   int NextDFSNumber = 2;
00384   for (;;) {
00385     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
00386                                 "before processing a node.");
00387 
00388     // We simulate recursion by popping out of the nested loop and continuing.
00389     Node::iterator E = N->end();
00390     while (I != E) {
00391       Node &ChildN = *I;
00392       if (SCC *ChildSCC = G->SCCMap.lookup(&ChildN)) {
00393         // Check if we have reached a node in the new (known connected) set of
00394         // this SCC. If so, the entire stack is necessarily in that set and we
00395         // can re-start.
00396         if (ChildSCC == this) {
00397           insert(*N);
00398           while (!PendingSCCStack.empty())
00399             insert(*PendingSCCStack.pop_back_val());
00400           while (!DFSStack.empty())
00401             insert(*DFSStack.pop_back_val().first);
00402           return;
00403         }
00404 
00405         // If this child isn't currently in this SCC, no need to process it.
00406         // However, we do need to remove this SCC from its SCC's parent set.
00407         ChildSCC->ParentSCCs.erase(this);
00408         ++I;
00409         continue;
00410       }
00411 
00412       if (ChildN.DFSNumber == 0) {
00413         // Mark that we should start at this child when next this node is the
00414         // top of the stack. We don't start at the next child to ensure this
00415         // child's lowlink is reflected.
00416         DFSStack.push_back(std::make_pair(N, I));
00417 
00418         // Continue, resetting to the child node.
00419         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
00420         N = &ChildN;
00421         I = ChildN.begin();
00422         E = ChildN.end();
00423         continue;
00424       }
00425 
00426       // Track the lowest link of the children, if any are still in the stack.
00427       // Any child not on the stack will have a LowLink of -1.
00428       assert(ChildN.LowLink != 0 &&
00429              "Low-link must not be zero with a non-zero DFS number.");
00430       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
00431         N->LowLink = ChildN.LowLink;
00432       ++I;
00433     }
00434 
00435     if (N->LowLink == N->DFSNumber) {
00436       ResultSCCs.push_back(G->formSCC(N, PendingSCCStack));
00437       if (DFSStack.empty())
00438         return;
00439     } else {
00440       // At this point we know that N cannot ever be an SCC root. Its low-link
00441       // is not its dfs-number, and we've processed all of its children. It is
00442       // just sitting here waiting until some node further down the stack gets
00443       // low-link == dfs-number and pops it off as well. Move it to the pending
00444       // stack which is pulled into the next SCC to be formed.
00445       PendingSCCStack.push_back(N);
00446 
00447       assert(!DFSStack.empty() && "We shouldn't have an empty stack!");
00448     }
00449 
00450     N = DFSStack.back().first;
00451     I = DFSStack.back().second;
00452     DFSStack.pop_back();
00453   }
00454 }
00455 
00456 SmallVector<LazyCallGraph::SCC *, 1>
00457 LazyCallGraph::SCC::removeIntraSCCEdge(Node &CallerN,
00458                                        Node &CalleeN) {
00459   // First remove it from the node.
00460   CallerN.removeEdgeInternal(CalleeN.getFunction());
00461 
00462   // We return a list of the resulting *new* SCCs in postorder.
00463   SmallVector<SCC *, 1> ResultSCCs;
00464 
00465   // Direct recursion doesn't impact the SCC graph at all.
00466   if (&CallerN == &CalleeN)
00467     return ResultSCCs;
00468 
00469   // The worklist is every node in the original SCC.
00470   SmallVector<Node *, 1> Worklist;
00471   Worklist.swap(Nodes);
00472   for (Node *N : Worklist) {
00473     // The nodes formerly in this SCC are no longer in any SCC.
00474     N->DFSNumber = 0;
00475     N->LowLink = 0;
00476     G->SCCMap.erase(N);
00477   }
00478   assert(Worklist.size() > 1 && "We have to have at least two nodes to have an "
00479                                 "edge between them that is within the SCC.");
00480 
00481   // The callee can already reach every node in this SCC (by definition). It is
00482   // the only node we know will stay inside this SCC. Everything which
00483   // transitively reaches Callee will also remain in the SCC. To model this we
00484   // incrementally add any chain of nodes which reaches something in the new
00485   // node set to the new node set. This short circuits one side of the Tarjan's
00486   // walk.
00487   insert(CalleeN);
00488 
00489   // We're going to do a full mini-Tarjan's walk using a local stack here.
00490   SmallVector<std::pair<Node *, Node::iterator>, 4> DFSStack;
00491   SmallVector<Node *, 4> PendingSCCStack;
00492   do {
00493     Node *N = Worklist.pop_back_val();
00494     if (N->DFSNumber == 0)
00495       internalDFS(DFSStack, PendingSCCStack, N, ResultSCCs);
00496 
00497     assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
00498     assert(PendingSCCStack.empty() && "Didn't flush all pending SCC nodes!");
00499   } while (!Worklist.empty());
00500 
00501   // Now we need to reconnect the current SCC to the graph.
00502   bool IsLeafSCC = true;
00503   for (Node *N : Nodes) {
00504     for (Node &ChildN : *N) {
00505       SCC &ChildSCC = *G->SCCMap.lookup(&ChildN);
00506       if (&ChildSCC == this)
00507         continue;
00508       ChildSCC.ParentSCCs.insert(this);
00509       IsLeafSCC = false;
00510     }
00511   }
00512 #ifndef NDEBUG
00513   if (!ResultSCCs.empty())
00514     assert(!IsLeafSCC && "This SCC cannot be a leaf as we have split out new "
00515                          "SCCs by removing this edge.");
00516   if (!std::any_of(G->LeafSCCs.begin(), G->LeafSCCs.end(),
00517                    [&](SCC *C) { return C == this; }))
00518     assert(!IsLeafSCC && "This SCC cannot be a leaf as it already had child "
00519                          "SCCs before we removed this edge.");
00520 #endif
00521   // If this SCC stopped being a leaf through this edge removal, remove it from
00522   // the leaf SCC list.
00523   if (!IsLeafSCC && !ResultSCCs.empty())
00524     G->LeafSCCs.erase(std::remove(G->LeafSCCs.begin(), G->LeafSCCs.end(), this),
00525                      G->LeafSCCs.end());
00526 
00527   // Return the new list of SCCs.
00528   return ResultSCCs;
00529 }
00530 
00531 void LazyCallGraph::insertEdge(Node &CallerN, Function &Callee) {
00532   assert(SCCMap.empty() && DFSStack.empty() &&
00533          "This method cannot be called after SCCs have been formed!");
00534 
00535   return CallerN.insertEdgeInternal(Callee);
00536 }
00537 
00538 void LazyCallGraph::removeEdge(Node &CallerN, Function &Callee) {
00539   assert(SCCMap.empty() && DFSStack.empty() &&
00540          "This method cannot be called after SCCs have been formed!");
00541 
00542   return CallerN.removeEdgeInternal(Callee);
00543 }
00544 
00545 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
00546   return *new (MappedN = BPA.Allocate()) Node(*this, F);
00547 }
00548 
00549 void LazyCallGraph::updateGraphPtrs() {
00550   // Process all nodes updating the graph pointers.
00551   {
00552     SmallVector<Node *, 16> Worklist;
00553     for (auto &Entry : EntryNodes)
00554       if (Node *EntryN = Entry.dyn_cast<Node *>())
00555         Worklist.push_back(EntryN);
00556 
00557     while (!Worklist.empty()) {
00558       Node *N = Worklist.pop_back_val();
00559       N->G = this;
00560       for (auto &Callee : N->Callees)
00561         if (!Callee.isNull())
00562           if (Node *CalleeN = Callee.dyn_cast<Node *>())
00563             Worklist.push_back(CalleeN);
00564     }
00565   }
00566 
00567   // Process all SCCs updating the graph pointers.
00568   {
00569     SmallVector<SCC *, 16> Worklist(LeafSCCs.begin(), LeafSCCs.end());
00570 
00571     while (!Worklist.empty()) {
00572       SCC *C = Worklist.pop_back_val();
00573       C->G = this;
00574       Worklist.insert(Worklist.end(), C->ParentSCCs.begin(),
00575                       C->ParentSCCs.end());
00576     }
00577   }
00578 }
00579 
00580 LazyCallGraph::SCC *LazyCallGraph::formSCC(Node *RootN,
00581                                            SmallVectorImpl<Node *> &NodeStack) {
00582   // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
00583   // into it.
00584   SCC *NewSCC = new (SCCBPA.Allocate()) SCC(*this);
00585 
00586   while (!NodeStack.empty() && NodeStack.back()->DFSNumber > RootN->DFSNumber) {
00587     assert(NodeStack.back()->LowLink >= RootN->LowLink &&
00588            "We cannot have a low link in an SCC lower than its root on the "
00589            "stack!");
00590     NewSCC->insert(*NodeStack.pop_back_val());
00591   }
00592   NewSCC->insert(*RootN);
00593 
00594   // A final pass over all edges in the SCC (this remains linear as we only
00595   // do this once when we build the SCC) to connect it to the parent sets of
00596   // its children.
00597   bool IsLeafSCC = true;
00598   for (Node *SCCN : NewSCC->Nodes)
00599     for (Node &SCCChildN : *SCCN) {
00600       SCC &ChildSCC = *SCCMap.lookup(&SCCChildN);
00601       if (&ChildSCC == NewSCC)
00602         continue;
00603       ChildSCC.ParentSCCs.insert(NewSCC);
00604       IsLeafSCC = false;
00605     }
00606 
00607   // For the SCCs where we fine no child SCCs, add them to the leaf list.
00608   if (IsLeafSCC)
00609     LeafSCCs.push_back(NewSCC);
00610 
00611   return NewSCC;
00612 }
00613 
00614 LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
00615   Node *N;
00616   Node::iterator I;
00617   if (!DFSStack.empty()) {
00618     N = DFSStack.back().first;
00619     I = DFSStack.back().second;
00620     DFSStack.pop_back();
00621   } else {
00622     // If we've handled all candidate entry nodes to the SCC forest, we're done.
00623     do {
00624       if (SCCEntryNodes.empty())
00625         return nullptr;
00626 
00627       N = &get(*SCCEntryNodes.pop_back_val());
00628     } while (N->DFSNumber != 0);
00629     I = N->begin();
00630     N->LowLink = N->DFSNumber = 1;
00631     NextDFSNumber = 2;
00632   }
00633 
00634   for (;;) {
00635     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
00636                                 "before placing a node onto the stack.");
00637 
00638     Node::iterator E = N->end();
00639     while (I != E) {
00640       Node &ChildN = *I;
00641       if (ChildN.DFSNumber == 0) {
00642         // Mark that we should start at this child when next this node is the
00643         // top of the stack. We don't start at the next child to ensure this
00644         // child's lowlink is reflected.
00645         DFSStack.push_back(std::make_pair(N, N->begin()));
00646 
00647         // Recurse onto this node via a tail call.
00648         assert(!SCCMap.count(&ChildN) &&
00649                "Found a node with 0 DFS number but already in an SCC!");
00650         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
00651         N = &ChildN;
00652         I = ChildN.begin();
00653         E = ChildN.end();
00654         continue;
00655       }
00656 
00657       // Track the lowest link of the children, if any are still in the stack.
00658       assert(ChildN.LowLink != 0 &&
00659              "Low-link must not be zero with a non-zero DFS number.");
00660       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
00661         N->LowLink = ChildN.LowLink;
00662       ++I;
00663     }
00664 
00665     if (N->LowLink == N->DFSNumber)
00666       // Form the new SCC out of the top of the DFS stack.
00667       return formSCC(N, PendingSCCStack);
00668 
00669     // At this point we know that N cannot ever be an SCC root. Its low-link
00670     // is not its dfs-number, and we've processed all of its children. It is
00671     // just sitting here waiting until some node further down the stack gets
00672     // low-link == dfs-number and pops it off as well. Move it to the pending
00673     // stack which is pulled into the next SCC to be formed.
00674     PendingSCCStack.push_back(N);
00675 
00676     assert(!DFSStack.empty() && "We never found a viable root!");
00677     N = DFSStack.back().first;
00678     I = DFSStack.back().second;
00679     DFSStack.pop_back();
00680   }
00681 }
00682 
00683 char LazyCallGraphAnalysis::PassID;
00684 
00685 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
00686 
00687 static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
00688                        SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
00689   // Recurse depth first through the nodes.
00690   for (LazyCallGraph::Node &ChildN : N)
00691     if (Printed.insert(&ChildN))
00692       printNodes(OS, ChildN, Printed);
00693 
00694   OS << "  Call edges in function: " << N.getFunction().getName() << "\n";
00695   for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
00696     OS << "    -> " << I->getFunction().getName() << "\n";
00697 
00698   OS << "\n";
00699 }
00700 
00701 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
00702   ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
00703   OS << "  SCC with " << SCCSize << " functions:\n";
00704 
00705   for (LazyCallGraph::Node *N : SCC)
00706     OS << "    " << N->getFunction().getName() << "\n";
00707 
00708   OS << "\n";
00709 }
00710 
00711 PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
00712                                                 ModuleAnalysisManager *AM) {
00713   LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
00714 
00715   OS << "Printing the call graph for module: " << M->getModuleIdentifier()
00716      << "\n\n";
00717 
00718   SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
00719   for (LazyCallGraph::Node &N : G)
00720     if (Printed.insert(&N))
00721       printNodes(OS, N, Printed);
00722 
00723   for (LazyCallGraph::SCC &SCC : G.postorder_sccs())
00724     printSCC(OS, SCC);
00725 
00726   return PreservedAnalyses::all();
00727 
00728 }