2
0

LazyCallGraph.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/Analysis/LazyCallGraph.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/IR/CallSite.h"
  12. #include "llvm/IR/InstVisitor.h"
  13. #include "llvm/IR/Instructions.h"
  14. #include "llvm/IR/PassManager.h"
  15. #include "llvm/Support/Debug.h"
  16. #include "llvm/Support/raw_ostream.h"
  17. using namespace llvm;
  18. #define DEBUG_TYPE "lcg"
  19. static void findCallees(
  20. SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
  21. SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
  22. DenseMap<Function *, size_t> &CalleeIndexMap) {
  23. while (!Worklist.empty()) {
  24. Constant *C = Worklist.pop_back_val();
  25. if (Function *F = dyn_cast<Function>(C)) {
  26. // Note that we consider *any* function with a definition to be a viable
  27. // edge. Even if the function's definition is subject to replacement by
  28. // some other module (say, a weak definition) there may still be
  29. // optimizations which essentially speculate based on the definition and
  30. // a way to check that the specific definition is in fact the one being
  31. // used. For example, this could be done by moving the weak definition to
  32. // a strong (internal) definition and making the weak definition be an
  33. // alias. Then a test of the address of the weak function against the new
  34. // strong definition's address would be an effective way to determine the
  35. // safety of optimizing a direct call edge.
  36. if (!F->isDeclaration() &&
  37. CalleeIndexMap.insert(std::make_pair(F, Callees.size())).second) {
  38. DEBUG(dbgs() << " Added callable function: " << F->getName()
  39. << "\n");
  40. Callees.push_back(F);
  41. }
  42. continue;
  43. }
  44. for (Value *Op : C->operand_values())
  45. if (Visited.insert(cast<Constant>(Op)).second)
  46. Worklist.push_back(cast<Constant>(Op));
  47. }
  48. }
  49. LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
  50. : G(&G), F(F), DFSNumber(0), LowLink(0) {
  51. DEBUG(dbgs() << " Adding functions called by '" << F.getName()
  52. << "' to the graph.\n");
  53. SmallVector<Constant *, 16> Worklist;
  54. SmallPtrSet<Constant *, 16> Visited;
  55. // Find all the potential callees in this function. First walk the
  56. // instructions and add every operand which is a constant to the worklist.
  57. for (BasicBlock &BB : F)
  58. for (Instruction &I : BB)
  59. for (Value *Op : I.operand_values())
  60. if (Constant *C = dyn_cast<Constant>(Op))
  61. if (Visited.insert(C).second)
  62. Worklist.push_back(C);
  63. // We've collected all the constant (and thus potentially function or
  64. // function containing) operands to all of the instructions in the function.
  65. // Process them (recursively) collecting every function found.
  66. findCallees(Worklist, Visited, Callees, CalleeIndexMap);
  67. }
  68. void LazyCallGraph::Node::insertEdgeInternal(Function &Callee) {
  69. if (Node *N = G->lookup(Callee))
  70. return insertEdgeInternal(*N);
  71. CalleeIndexMap.insert(std::make_pair(&Callee, Callees.size()));
  72. Callees.push_back(&Callee);
  73. }
  74. void LazyCallGraph::Node::insertEdgeInternal(Node &CalleeN) {
  75. CalleeIndexMap.insert(std::make_pair(&CalleeN.getFunction(), Callees.size()));
  76. Callees.push_back(&CalleeN);
  77. }
  78. void LazyCallGraph::Node::removeEdgeInternal(Function &Callee) {
  79. auto IndexMapI = CalleeIndexMap.find(&Callee);
  80. assert(IndexMapI != CalleeIndexMap.end() &&
  81. "Callee not in the callee set for this caller?");
  82. Callees[IndexMapI->second] = nullptr;
  83. CalleeIndexMap.erase(IndexMapI);
  84. }
  85. LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
  86. DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
  87. << "\n");
  88. for (Function &F : M)
  89. if (!F.isDeclaration() && !F.hasLocalLinkage())
  90. if (EntryIndexMap.insert(std::make_pair(&F, EntryNodes.size())).second) {
  91. DEBUG(dbgs() << " Adding '" << F.getName()
  92. << "' to entry set of the graph.\n");
  93. EntryNodes.push_back(&F);
  94. }
  95. // Now add entry nodes for functions reachable via initializers to globals.
  96. SmallVector<Constant *, 16> Worklist;
  97. SmallPtrSet<Constant *, 16> Visited;
  98. for (GlobalVariable &GV : M.globals())
  99. if (GV.hasInitializer())
  100. if (Visited.insert(GV.getInitializer()).second)
  101. Worklist.push_back(GV.getInitializer());
  102. DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
  103. "entry set.\n");
  104. findCallees(Worklist, Visited, EntryNodes, EntryIndexMap);
  105. for (auto &Entry : EntryNodes) {
  106. assert(!Entry.isNull() &&
  107. "We can't have removed edges before we finish the constructor!");
  108. if (Function *F = Entry.dyn_cast<Function *>())
  109. SCCEntryNodes.push_back(F);
  110. else
  111. SCCEntryNodes.push_back(&Entry.get<Node *>()->getFunction());
  112. }
  113. }
  114. LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
  115. : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
  116. EntryNodes(std::move(G.EntryNodes)),
  117. EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
  118. SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
  119. DFSStack(std::move(G.DFSStack)),
  120. SCCEntryNodes(std::move(G.SCCEntryNodes)),
  121. NextDFSNumber(G.NextDFSNumber) {
  122. updateGraphPtrs();
  123. }
  124. LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
  125. BPA = std::move(G.BPA);
  126. NodeMap = std::move(G.NodeMap);
  127. EntryNodes = std::move(G.EntryNodes);
  128. EntryIndexMap = std::move(G.EntryIndexMap);
  129. SCCBPA = std::move(G.SCCBPA);
  130. SCCMap = std::move(G.SCCMap);
  131. LeafSCCs = std::move(G.LeafSCCs);
  132. DFSStack = std::move(G.DFSStack);
  133. SCCEntryNodes = std::move(G.SCCEntryNodes);
  134. NextDFSNumber = G.NextDFSNumber;
  135. updateGraphPtrs();
  136. return *this;
  137. }
  138. void LazyCallGraph::SCC::insert(Node &N) {
  139. N.DFSNumber = N.LowLink = -1;
  140. Nodes.push_back(&N);
  141. G->SCCMap[&N] = this;
  142. }
  143. bool LazyCallGraph::SCC::isDescendantOf(const SCC &C) const {
  144. // Walk up the parents of this SCC and verify that we eventually find C.
  145. SmallVector<const SCC *, 4> AncestorWorklist;
  146. AncestorWorklist.push_back(this);
  147. do {
  148. const SCC *AncestorC = AncestorWorklist.pop_back_val();
  149. if (AncestorC->isChildOf(C))
  150. return true;
  151. for (const SCC *ParentC : AncestorC->ParentSCCs)
  152. AncestorWorklist.push_back(ParentC);
  153. } while (!AncestorWorklist.empty());
  154. return false;
  155. }
  156. void LazyCallGraph::SCC::insertIntraSCCEdge(Node &CallerN, Node &CalleeN) {
  157. // First insert it into the caller.
  158. CallerN.insertEdgeInternal(CalleeN);
  159. assert(G->SCCMap.lookup(&CallerN) == this && "Caller must be in this SCC.");
  160. assert(G->SCCMap.lookup(&CalleeN) == this && "Callee must be in this SCC.");
  161. // Nothing changes about this SCC or any other.
  162. }
  163. void LazyCallGraph::SCC::insertOutgoingEdge(Node &CallerN, Node &CalleeN) {
  164. // First insert it into the caller.
  165. CallerN.insertEdgeInternal(CalleeN);
  166. assert(G->SCCMap.lookup(&CallerN) == this && "Caller must be in this SCC.");
  167. SCC &CalleeC = *G->SCCMap.lookup(&CalleeN);
  168. assert(&CalleeC != this && "Callee must not be in this SCC.");
  169. assert(CalleeC.isDescendantOf(*this) &&
  170. "Callee must be a descendant of the Caller.");
  171. // The only change required is to add this SCC to the parent set of the callee.
  172. CalleeC.ParentSCCs.insert(this);
  173. }
  174. SmallVector<LazyCallGraph::SCC *, 1>
  175. LazyCallGraph::SCC::insertIncomingEdge(Node &CallerN, Node &CalleeN) {
  176. // First insert it into the caller.
  177. CallerN.insertEdgeInternal(CalleeN);
  178. assert(G->SCCMap.lookup(&CalleeN) == this && "Callee must be in this SCC.");
  179. SCC &CallerC = *G->SCCMap.lookup(&CallerN);
  180. assert(&CallerC != this && "Caller must not be in this SCC.");
  181. assert(CallerC.isDescendantOf(*this) &&
  182. "Caller must be a descendant of the Callee.");
  183. // The algorithm we use for merging SCCs based on the cycle introduced here
  184. // is to walk the SCC inverted DAG formed by the parent SCC sets. The inverse
  185. // graph has the same cycle properties as the actual DAG of the SCCs, and
  186. // when forming SCCs lazily by a DFS, the bottom of the graph won't exist in
  187. // many cases which should prune the search space.
  188. //
  189. // FIXME: We can get this pruning behavior even after the incremental SCC
  190. // formation by leaving behind (conservative) DFS numberings in the nodes,
  191. // and pruning the search with them. These would need to be cleverly updated
  192. // during the removal of intra-SCC edges, but could be preserved
  193. // conservatively.
  194. // The set of SCCs that are connected to the caller, and thus will
  195. // participate in the merged connected component.
  196. SmallPtrSet<SCC *, 8> ConnectedSCCs;
  197. ConnectedSCCs.insert(this);
  198. ConnectedSCCs.insert(&CallerC);
  199. // We build up a DFS stack of the parents chains.
  200. SmallVector<std::pair<SCC *, SCC::parent_iterator>, 8> DFSSCCs;
  201. SmallPtrSet<SCC *, 8> VisitedSCCs;
  202. int ConnectedDepth = -1;
  203. SCC *C = this;
  204. parent_iterator I = parent_begin(), E = parent_end();
  205. for (;;) {
  206. while (I != E) {
  207. SCC &ParentSCC = *I++;
  208. // If we have already processed this parent SCC, skip it, and remember
  209. // whether it was connected so we don't have to check the rest of the
  210. // stack. This also handles when we reach a child of the 'this' SCC (the
  211. // callee) which terminates the search.
  212. if (ConnectedSCCs.count(&ParentSCC)) {
  213. ConnectedDepth = std::max<int>(ConnectedDepth, DFSSCCs.size());
  214. continue;
  215. }
  216. if (VisitedSCCs.count(&ParentSCC))
  217. continue;
  218. // We fully explore the depth-first space, adding nodes to the connected
  219. // set only as we pop them off, so "recurse" by rotating to the parent.
  220. DFSSCCs.push_back(std::make_pair(C, I));
  221. C = &ParentSCC;
  222. I = ParentSCC.parent_begin();
  223. E = ParentSCC.parent_end();
  224. }
  225. // If we've found a connection anywhere below this point on the stack (and
  226. // thus up the parent graph from the caller), the current node needs to be
  227. // added to the connected set now that we've processed all of its parents.
  228. if ((int)DFSSCCs.size() == ConnectedDepth) {
  229. --ConnectedDepth; // We're finished with this connection.
  230. ConnectedSCCs.insert(C);
  231. } else {
  232. // Otherwise remember that its parents don't ever connect.
  233. assert(ConnectedDepth < (int)DFSSCCs.size() &&
  234. "Cannot have a connected depth greater than the DFS depth!");
  235. VisitedSCCs.insert(C);
  236. }
  237. if (DFSSCCs.empty())
  238. break; // We've walked all the parents of the caller transitively.
  239. // Pop off the prior node and position to unwind the depth first recursion.
  240. std::tie(C, I) = DFSSCCs.pop_back_val();
  241. E = C->parent_end();
  242. }
  243. // Now that we have identified all of the SCCs which need to be merged into
  244. // a connected set with the inserted edge, merge all of them into this SCC.
  245. // FIXME: This operation currently creates ordering stability problems
  246. // because we don't use stably ordered containers for the parent SCCs or the
  247. // connected SCCs.
  248. unsigned NewNodeBeginIdx = Nodes.size();
  249. for (SCC *C : ConnectedSCCs) {
  250. if (C == this)
  251. continue;
  252. for (SCC *ParentC : C->ParentSCCs)
  253. if (!ConnectedSCCs.count(ParentC))
  254. ParentSCCs.insert(ParentC);
  255. C->ParentSCCs.clear();
  256. for (Node *N : *C) {
  257. for (Node &ChildN : *N) {
  258. SCC &ChildC = *G->SCCMap.lookup(&ChildN);
  259. if (&ChildC != C)
  260. ChildC.ParentSCCs.erase(C);
  261. }
  262. G->SCCMap[N] = this;
  263. Nodes.push_back(N);
  264. }
  265. C->Nodes.clear();
  266. }
  267. for (auto I = Nodes.begin() + NewNodeBeginIdx, E = Nodes.end(); I != E; ++I)
  268. for (Node &ChildN : **I) {
  269. SCC &ChildC = *G->SCCMap.lookup(&ChildN);
  270. if (&ChildC != this)
  271. ChildC.ParentSCCs.insert(this);
  272. }
  273. // We return the list of SCCs which were merged so that callers can
  274. // invalidate any data they have associated with those SCCs. Note that these
  275. // SCCs are no longer in an interesting state (they are totally empty) but
  276. // the pointers will remain stable for the life of the graph itself.
  277. return SmallVector<SCC *, 1>(ConnectedSCCs.begin(), ConnectedSCCs.end());
  278. }
  279. void LazyCallGraph::SCC::removeInterSCCEdge(Node &CallerN, Node &CalleeN) {
  280. // First remove it from the node.
  281. CallerN.removeEdgeInternal(CalleeN.getFunction());
  282. assert(G->SCCMap.lookup(&CallerN) == this &&
  283. "The caller must be a member of this SCC.");
  284. SCC &CalleeC = *G->SCCMap.lookup(&CalleeN);
  285. assert(&CalleeC != this &&
  286. "This API only supports the rmoval of inter-SCC edges.");
  287. assert(std::find(G->LeafSCCs.begin(), G->LeafSCCs.end(), this) ==
  288. G->LeafSCCs.end() &&
  289. "Cannot have a leaf SCC caller with a different SCC callee.");
  290. bool HasOtherCallToCalleeC = false;
  291. bool HasOtherCallOutsideSCC = false;
  292. for (Node *N : *this) {
  293. for (Node &OtherCalleeN : *N) {
  294. SCC &OtherCalleeC = *G->SCCMap.lookup(&OtherCalleeN);
  295. if (&OtherCalleeC == &CalleeC) {
  296. HasOtherCallToCalleeC = true;
  297. break;
  298. }
  299. if (&OtherCalleeC != this)
  300. HasOtherCallOutsideSCC = true;
  301. }
  302. if (HasOtherCallToCalleeC)
  303. break;
  304. }
  305. // Because the SCCs form a DAG, deleting such an edge cannot change the set
  306. // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
  307. // the caller no longer a parent of the callee. Walk the other call edges
  308. // in the caller to tell.
  309. if (!HasOtherCallToCalleeC) {
  310. bool Removed = CalleeC.ParentSCCs.erase(this);
  311. (void)Removed;
  312. assert(Removed &&
  313. "Did not find the caller SCC in the callee SCC's parent list!");
  314. // It may orphan an SCC if it is the last edge reaching it, but that does
  315. // not violate any invariants of the graph.
  316. if (CalleeC.ParentSCCs.empty())
  317. DEBUG(dbgs() << "LCG: Update removing " << CallerN.getFunction().getName()
  318. << " -> " << CalleeN.getFunction().getName()
  319. << " edge orphaned the callee's SCC!\n");
  320. }
  321. // It may make the Caller SCC a leaf SCC.
  322. if (!HasOtherCallOutsideSCC)
  323. G->LeafSCCs.push_back(this);
  324. }
  325. void LazyCallGraph::SCC::internalDFS(
  326. SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack,
  327. SmallVectorImpl<Node *> &PendingSCCStack, Node *N,
  328. SmallVectorImpl<SCC *> &ResultSCCs) {
  329. Node::iterator I = N->begin();
  330. N->LowLink = N->DFSNumber = 1;
  331. int NextDFSNumber = 2;
  332. for (;;) {
  333. assert(N->DFSNumber != 0 && "We should always assign a DFS number "
  334. "before processing a node.");
  335. // We simulate recursion by popping out of the nested loop and continuing.
  336. Node::iterator E = N->end();
  337. while (I != E) {
  338. Node &ChildN = *I;
  339. if (SCC *ChildSCC = G->SCCMap.lookup(&ChildN)) {
  340. // Check if we have reached a node in the new (known connected) set of
  341. // this SCC. If so, the entire stack is necessarily in that set and we
  342. // can re-start.
  343. if (ChildSCC == this) {
  344. insert(*N);
  345. while (!PendingSCCStack.empty())
  346. insert(*PendingSCCStack.pop_back_val());
  347. while (!DFSStack.empty())
  348. insert(*DFSStack.pop_back_val().first);
  349. return;
  350. }
  351. // If this child isn't currently in this SCC, no need to process it.
  352. // However, we do need to remove this SCC from its SCC's parent set.
  353. ChildSCC->ParentSCCs.erase(this);
  354. ++I;
  355. continue;
  356. }
  357. if (ChildN.DFSNumber == 0) {
  358. // Mark that we should start at this child when next this node is the
  359. // top of the stack. We don't start at the next child to ensure this
  360. // child's lowlink is reflected.
  361. DFSStack.push_back(std::make_pair(N, I));
  362. // Continue, resetting to the child node.
  363. ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
  364. N = &ChildN;
  365. I = ChildN.begin();
  366. E = ChildN.end();
  367. continue;
  368. }
  369. // Track the lowest link of the children, if any are still in the stack.
  370. // Any child not on the stack will have a LowLink of -1.
  371. assert(ChildN.LowLink != 0 &&
  372. "Low-link must not be zero with a non-zero DFS number.");
  373. if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
  374. N->LowLink = ChildN.LowLink;
  375. ++I;
  376. }
  377. if (N->LowLink == N->DFSNumber) {
  378. ResultSCCs.push_back(G->formSCC(N, PendingSCCStack));
  379. if (DFSStack.empty())
  380. return;
  381. } else {
  382. // At this point we know that N cannot ever be an SCC root. Its low-link
  383. // is not its dfs-number, and we've processed all of its children. It is
  384. // just sitting here waiting until some node further down the stack gets
  385. // low-link == dfs-number and pops it off as well. Move it to the pending
  386. // stack which is pulled into the next SCC to be formed.
  387. PendingSCCStack.push_back(N);
  388. assert(!DFSStack.empty() && "We shouldn't have an empty stack!");
  389. }
  390. N = DFSStack.back().first;
  391. I = DFSStack.back().second;
  392. DFSStack.pop_back();
  393. }
  394. }
  395. SmallVector<LazyCallGraph::SCC *, 1>
  396. LazyCallGraph::SCC::removeIntraSCCEdge(Node &CallerN,
  397. Node &CalleeN) {
  398. // First remove it from the node.
  399. CallerN.removeEdgeInternal(CalleeN.getFunction());
  400. // We return a list of the resulting *new* SCCs in postorder.
  401. SmallVector<SCC *, 1> ResultSCCs;
  402. // Direct recursion doesn't impact the SCC graph at all.
  403. if (&CallerN == &CalleeN)
  404. return ResultSCCs;
  405. // The worklist is every node in the original SCC.
  406. SmallVector<Node *, 1> Worklist;
  407. Worklist.swap(Nodes);
  408. for (Node *N : Worklist) {
  409. // The nodes formerly in this SCC are no longer in any SCC.
  410. N->DFSNumber = 0;
  411. N->LowLink = 0;
  412. G->SCCMap.erase(N);
  413. }
  414. assert(Worklist.size() > 1 && "We have to have at least two nodes to have an "
  415. "edge between them that is within the SCC.");
  416. // The callee can already reach every node in this SCC (by definition). It is
  417. // the only node we know will stay inside this SCC. Everything which
  418. // transitively reaches Callee will also remain in the SCC. To model this we
  419. // incrementally add any chain of nodes which reaches something in the new
  420. // node set to the new node set. This short circuits one side of the Tarjan's
  421. // walk.
  422. insert(CalleeN);
  423. // We're going to do a full mini-Tarjan's walk using a local stack here.
  424. SmallVector<std::pair<Node *, Node::iterator>, 4> DFSStack;
  425. SmallVector<Node *, 4> PendingSCCStack;
  426. do {
  427. Node *N = Worklist.pop_back_val();
  428. if (N->DFSNumber == 0)
  429. internalDFS(DFSStack, PendingSCCStack, N, ResultSCCs);
  430. assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
  431. assert(PendingSCCStack.empty() && "Didn't flush all pending SCC nodes!");
  432. } while (!Worklist.empty());
  433. // Now we need to reconnect the current SCC to the graph.
  434. bool IsLeafSCC = true;
  435. for (Node *N : Nodes) {
  436. for (Node &ChildN : *N) {
  437. SCC &ChildSCC = *G->SCCMap.lookup(&ChildN);
  438. if (&ChildSCC == this)
  439. continue;
  440. ChildSCC.ParentSCCs.insert(this);
  441. IsLeafSCC = false;
  442. }
  443. }
  444. #ifndef NDEBUG
  445. if (!ResultSCCs.empty())
  446. assert(!IsLeafSCC && "This SCC cannot be a leaf as we have split out new "
  447. "SCCs by removing this edge.");
  448. if (!std::any_of(G->LeafSCCs.begin(), G->LeafSCCs.end(),
  449. [&](SCC *C) { return C == this; }))
  450. assert(!IsLeafSCC && "This SCC cannot be a leaf as it already had child "
  451. "SCCs before we removed this edge.");
  452. #endif
  453. // If this SCC stopped being a leaf through this edge removal, remove it from
  454. // the leaf SCC list.
  455. if (!IsLeafSCC && !ResultSCCs.empty())
  456. G->LeafSCCs.erase(std::remove(G->LeafSCCs.begin(), G->LeafSCCs.end(), this),
  457. G->LeafSCCs.end());
  458. // Return the new list of SCCs.
  459. return ResultSCCs;
  460. }
  461. void LazyCallGraph::insertEdge(Node &CallerN, Function &Callee) {
  462. assert(SCCMap.empty() && DFSStack.empty() &&
  463. "This method cannot be called after SCCs have been formed!");
  464. return CallerN.insertEdgeInternal(Callee);
  465. }
  466. void LazyCallGraph::removeEdge(Node &CallerN, Function &Callee) {
  467. assert(SCCMap.empty() && DFSStack.empty() &&
  468. "This method cannot be called after SCCs have been formed!");
  469. return CallerN.removeEdgeInternal(Callee);
  470. }
  471. LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
  472. return *new (MappedN = BPA.Allocate()) Node(*this, F);
  473. }
  474. void LazyCallGraph::updateGraphPtrs() {
  475. // Process all nodes updating the graph pointers.
  476. {
  477. SmallVector<Node *, 16> Worklist;
  478. for (auto &Entry : EntryNodes)
  479. if (Node *EntryN = Entry.dyn_cast<Node *>())
  480. Worklist.push_back(EntryN);
  481. while (!Worklist.empty()) {
  482. Node *N = Worklist.pop_back_val();
  483. N->G = this;
  484. for (auto &Callee : N->Callees)
  485. if (!Callee.isNull())
  486. if (Node *CalleeN = Callee.dyn_cast<Node *>())
  487. Worklist.push_back(CalleeN);
  488. }
  489. }
  490. // Process all SCCs updating the graph pointers.
  491. {
  492. SmallVector<SCC *, 16> Worklist(LeafSCCs.begin(), LeafSCCs.end());
  493. while (!Worklist.empty()) {
  494. SCC *C = Worklist.pop_back_val();
  495. C->G = this;
  496. Worklist.insert(Worklist.end(), C->ParentSCCs.begin(),
  497. C->ParentSCCs.end());
  498. }
  499. }
  500. }
  501. LazyCallGraph::SCC *LazyCallGraph::formSCC(Node *RootN,
  502. SmallVectorImpl<Node *> &NodeStack) {
  503. // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
  504. // into it.
  505. SCC *NewSCC = new (SCCBPA.Allocate()) SCC(*this);
  506. while (!NodeStack.empty() && NodeStack.back()->DFSNumber > RootN->DFSNumber) {
  507. assert(NodeStack.back()->LowLink >= RootN->LowLink &&
  508. "We cannot have a low link in an SCC lower than its root on the "
  509. "stack!");
  510. NewSCC->insert(*NodeStack.pop_back_val());
  511. }
  512. NewSCC->insert(*RootN);
  513. // A final pass over all edges in the SCC (this remains linear as we only
  514. // do this once when we build the SCC) to connect it to the parent sets of
  515. // its children.
  516. bool IsLeafSCC = true;
  517. for (Node *SCCN : NewSCC->Nodes)
  518. for (Node &SCCChildN : *SCCN) {
  519. SCC &ChildSCC = *SCCMap.lookup(&SCCChildN);
  520. if (&ChildSCC == NewSCC)
  521. continue;
  522. ChildSCC.ParentSCCs.insert(NewSCC);
  523. IsLeafSCC = false;
  524. }
  525. // For the SCCs where we fine no child SCCs, add them to the leaf list.
  526. if (IsLeafSCC)
  527. LeafSCCs.push_back(NewSCC);
  528. return NewSCC;
  529. }
  530. LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
  531. Node *N;
  532. Node::iterator I;
  533. if (!DFSStack.empty()) {
  534. N = DFSStack.back().first;
  535. I = DFSStack.back().second;
  536. DFSStack.pop_back();
  537. } else {
  538. // If we've handled all candidate entry nodes to the SCC forest, we're done.
  539. do {
  540. if (SCCEntryNodes.empty())
  541. return nullptr;
  542. N = &get(*SCCEntryNodes.pop_back_val());
  543. } while (N->DFSNumber != 0);
  544. I = N->begin();
  545. N->LowLink = N->DFSNumber = 1;
  546. NextDFSNumber = 2;
  547. }
  548. for (;;) {
  549. assert(N->DFSNumber != 0 && "We should always assign a DFS number "
  550. "before placing a node onto the stack.");
  551. Node::iterator E = N->end();
  552. while (I != E) {
  553. Node &ChildN = *I;
  554. if (ChildN.DFSNumber == 0) {
  555. // Mark that we should start at this child when next this node is the
  556. // top of the stack. We don't start at the next child to ensure this
  557. // child's lowlink is reflected.
  558. DFSStack.push_back(std::make_pair(N, N->begin()));
  559. // Recurse onto this node via a tail call.
  560. assert(!SCCMap.count(&ChildN) &&
  561. "Found a node with 0 DFS number but already in an SCC!");
  562. ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
  563. N = &ChildN;
  564. I = ChildN.begin();
  565. E = ChildN.end();
  566. continue;
  567. }
  568. // Track the lowest link of the children, if any are still in the stack.
  569. assert(ChildN.LowLink != 0 &&
  570. "Low-link must not be zero with a non-zero DFS number.");
  571. if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
  572. N->LowLink = ChildN.LowLink;
  573. ++I;
  574. }
  575. if (N->LowLink == N->DFSNumber)
  576. // Form the new SCC out of the top of the DFS stack.
  577. return formSCC(N, PendingSCCStack);
  578. // At this point we know that N cannot ever be an SCC root. Its low-link
  579. // is not its dfs-number, and we've processed all of its children. It is
  580. // just sitting here waiting until some node further down the stack gets
  581. // low-link == dfs-number and pops it off as well. Move it to the pending
  582. // stack which is pulled into the next SCC to be formed.
  583. PendingSCCStack.push_back(N);
  584. assert(!DFSStack.empty() && "We never found a viable root!");
  585. N = DFSStack.back().first;
  586. I = DFSStack.back().second;
  587. DFSStack.pop_back();
  588. }
  589. }
  590. char LazyCallGraphAnalysis::PassID;
  591. LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
  592. static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
  593. SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
  594. // Recurse depth first through the nodes.
  595. for (LazyCallGraph::Node &ChildN : N)
  596. if (Printed.insert(&ChildN).second)
  597. printNodes(OS, ChildN, Printed);
  598. OS << " Call edges in function: " << N.getFunction().getName() << "\n";
  599. for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
  600. OS << " -> " << I->getFunction().getName() << "\n";
  601. OS << "\n";
  602. }
  603. static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
  604. ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
  605. OS << " SCC with " << SCCSize << " functions:\n";
  606. for (LazyCallGraph::Node *N : SCC)
  607. OS << " " << N->getFunction().getName() << "\n";
  608. OS << "\n";
  609. }
  610. PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
  611. ModuleAnalysisManager *AM) {
  612. LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
  613. OS << "Printing the call graph for module: " << M.getModuleIdentifier()
  614. << "\n\n";
  615. SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
  616. for (LazyCallGraph::Node &N : G)
  617. if (Printed.insert(&N).second)
  618. printNodes(OS, N, Printed);
  619. for (LazyCallGraph::SCC &SCC : G.postorder_sccs())
  620. printSCC(OS, SCC);
  621. return PreservedAnalyses::all();
  622. }