[LCG] Refactor the duplicated code I added in my last commit here into
[oota-llvm.git] / lib / Analysis / LazyCallGraph.cpp
1 //===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Analysis/LazyCallGraph.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/IR/CallSite.h"
13 #include "llvm/IR/InstVisitor.h"
14 #include "llvm/IR/Instructions.h"
15 #include "llvm/IR/PassManager.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/raw_ostream.h"
18
19 using namespace llvm;
20
21 #define DEBUG_TYPE "lcg"
22
23 static void findCallees(
24     SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
25     SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
26     DenseMap<Function *, size_t> &CalleeIndexMap) {
27   while (!Worklist.empty()) {
28     Constant *C = Worklist.pop_back_val();
29
30     if (Function *F = dyn_cast<Function>(C)) {
31       // Note that we consider *any* function with a definition to be a viable
32       // edge. Even if the function's definition is subject to replacement by
33       // some other module (say, a weak definition) there may still be
34       // optimizations which essentially speculate based on the definition and
35       // a way to check that the specific definition is in fact the one being
36       // used. For example, this could be done by moving the weak definition to
37       // a strong (internal) definition and making the weak definition be an
38       // alias. Then a test of the address of the weak function against the new
39       // strong definition's address would be an effective way to determine the
40       // safety of optimizing a direct call edge.
41       if (!F->isDeclaration() &&
42           CalleeIndexMap.insert(std::make_pair(F, Callees.size())).second) {
43         DEBUG(dbgs() << "    Added callable function: " << F->getName()
44                      << "\n");
45         Callees.push_back(F);
46       }
47       continue;
48     }
49
50     for (Value *Op : C->operand_values())
51       if (Visited.insert(cast<Constant>(Op)))
52         Worklist.push_back(cast<Constant>(Op));
53   }
54 }
55
56 LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
57     : G(&G), F(F), DFSNumber(0), LowLink(0) {
58   DEBUG(dbgs() << "  Adding functions called by '" << F.getName()
59                << "' to the graph.\n");
60
61   SmallVector<Constant *, 16> Worklist;
62   SmallPtrSet<Constant *, 16> Visited;
63   // Find all the potential callees in this function. First walk the
64   // instructions and add every operand which is a constant to the worklist.
65   for (BasicBlock &BB : F)
66     for (Instruction &I : BB)
67       for (Value *Op : I.operand_values())
68         if (Constant *C = dyn_cast<Constant>(Op))
69           if (Visited.insert(C))
70             Worklist.push_back(C);
71
72   // We've collected all the constant (and thus potentially function or
73   // function containing) operands to all of the instructions in the function.
74   // Process them (recursively) collecting every function found.
75   findCallees(Worklist, Visited, Callees, CalleeIndexMap);
76 }
77
78 LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
79   DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
80                << "\n");
81   for (Function &F : M)
82     if (!F.isDeclaration() && !F.hasLocalLinkage())
83       if (EntryIndexMap.insert(std::make_pair(&F, EntryNodes.size())).second) {
84         DEBUG(dbgs() << "  Adding '" << F.getName()
85                      << "' to entry set of the graph.\n");
86         EntryNodes.push_back(&F);
87       }
88
89   // Now add entry nodes for functions reachable via initializers to globals.
90   SmallVector<Constant *, 16> Worklist;
91   SmallPtrSet<Constant *, 16> Visited;
92   for (GlobalVariable &GV : M.globals())
93     if (GV.hasInitializer())
94       if (Visited.insert(GV.getInitializer()))
95         Worklist.push_back(GV.getInitializer());
96
97   DEBUG(dbgs() << "  Adding functions referenced by global initializers to the "
98                   "entry set.\n");
99   findCallees(Worklist, Visited, EntryNodes, EntryIndexMap);
100
101   for (auto &Entry : EntryNodes)
102     if (Function *F = Entry.dyn_cast<Function *>())
103       SCCEntryNodes.insert(F);
104     else
105       SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
106 }
107
108 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
109     : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
110       EntryNodes(std::move(G.EntryNodes)),
111       EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
112       SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
113       DFSStack(std::move(G.DFSStack)),
114       SCCEntryNodes(std::move(G.SCCEntryNodes)),
115       NextDFSNumber(G.NextDFSNumber) {
116   updateGraphPtrs();
117 }
118
119 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
120   BPA = std::move(G.BPA);
121   NodeMap = std::move(G.NodeMap);
122   EntryNodes = std::move(G.EntryNodes);
123   EntryIndexMap = std::move(G.EntryIndexMap);
124   SCCBPA = std::move(G.SCCBPA);
125   SCCMap = std::move(G.SCCMap);
126   LeafSCCs = std::move(G.LeafSCCs);
127   DFSStack = std::move(G.DFSStack);
128   SCCEntryNodes = std::move(G.SCCEntryNodes);
129   NextDFSNumber = G.NextDFSNumber;
130   updateGraphPtrs();
131   return *this;
132 }
133
134 void LazyCallGraph::SCC::insert(LazyCallGraph &G, Node &N) {
135   N.DFSNumber = N.LowLink = -1;
136   Nodes.push_back(&N);
137   G.SCCMap[&N] = this;
138 }
139
140 void LazyCallGraph::SCC::removeEdge(LazyCallGraph &G, Function &Caller,
141                                     Function &Callee, SCC &CalleeC) {
142   assert(std::find(G.LeafSCCs.begin(), G.LeafSCCs.end(), this) ==
143              G.LeafSCCs.end() &&
144          "Cannot have a leaf SCC caller with a different SCC callee.");
145
146   bool HasOtherCallToCalleeC = false;
147   bool HasOtherCallOutsideSCC = false;
148   for (Node *N : *this) {
149     for (Node &Callee : *N) {
150       SCC &OtherCalleeC = *G.SCCMap.lookup(&Callee);
151       if (&OtherCalleeC == &CalleeC) {
152         HasOtherCallToCalleeC = true;
153         break;
154       }
155       if (&OtherCalleeC != this)
156         HasOtherCallOutsideSCC = true;
157     }
158     if (HasOtherCallToCalleeC)
159       break;
160   }
161   // Because the SCCs form a DAG, deleting such an edge cannot change the set
162   // of SCCs in the graph. However, it may cut an edge of the SCC DAG, making
163   // the caller no longer a parent of the callee. Walk the other call edges
164   // in the caller to tell.
165   if (!HasOtherCallToCalleeC) {
166     bool Removed = CalleeC.ParentSCCs.erase(this);
167     (void)Removed;
168     assert(Removed &&
169            "Did not find the caller SCC in the callee SCC's parent list!");
170
171     // It may orphan an SCC if it is the last edge reaching it, but that does
172     // not violate any invariants of the graph.
173     if (CalleeC.ParentSCCs.empty())
174       DEBUG(dbgs() << "LCG: Update removing " << Caller.getName() << " -> "
175                    << Callee.getName() << " edge orphaned the callee's SCC!\n");
176   }
177
178   // It may make the Caller SCC a leaf SCC.
179   if (!HasOtherCallOutsideSCC)
180     G.LeafSCCs.push_back(this);
181 }
182
183 SmallVector<LazyCallGraph::SCC *, 1>
184 LazyCallGraph::SCC::removeInternalEdge(LazyCallGraph &G, Node &Caller,
185                                        Node &Callee) {
186   // We return a list of the resulting SCCs, where 'this' is always the first
187   // element.
188   SmallVector<SCC *, 1> ResultSCCs;
189   ResultSCCs.push_back(this);
190
191   // We're going to do a full mini-Tarjan's walk using a local stack here.
192   int NextDFSNumber;
193   SmallVector<std::pair<Node *, Node::iterator>, 4> DFSStack;
194   SmallVector<Node *, 4> PendingSCCStack;
195
196   // The worklist is every node in the original SCC.
197   SmallVector<Node *, 1> Worklist;
198   Worklist.swap(Nodes);
199   for (Node *N : Worklist) {
200     // The nodes formerly in this SCC are no longer in any SCC.
201     N->DFSNumber = 0;
202     N->LowLink = 0;
203     G.SCCMap.erase(N);
204   }
205
206   // The callee can already reach every node in this SCC (by definition). It is
207   // the only node we know will stay inside this SCC. Everything which
208   // transitively reaches Callee will also remain in the SCC. To model this we
209   // incrementally add any chain of nodes which reaches something in the new
210   // node set to the new node set. This short circuits one side of the Tarjan's
211   // walk.
212   insert(G, Callee);
213
214   for (;;) {
215     if (DFSStack.empty()) {
216       // Clear off any nodes which have already been visited in the DFS.
217       while (!Worklist.empty() && Worklist.back()->DFSNumber != 0)
218         Worklist.pop_back();
219       if (Worklist.empty())
220         break;
221       Node *N = Worklist.pop_back_val();
222       N->LowLink = N->DFSNumber = 1;
223       NextDFSNumber = 2;
224       DFSStack.push_back(std::make_pair(N, N->begin()));
225       assert(PendingSCCStack.empty() && "Cannot start a fresh DFS walk with "
226                                         "pending nodes from a prior walk.");
227     }
228
229     Node *N = DFSStack.back().first;
230     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
231                                 "before placing a node onto the stack.");
232
233     // We simulate recursion by popping out of the nested loop and continuing.
234     bool Recurse = false;
235     for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
236       Node &ChildN = *I;
237       if (SCC *ChildSCC = G.SCCMap.lookup(&ChildN)) {
238         // Check if we have reached a node in the new (known connected) set of
239         // this SCC. If so, the entire stack is necessarily in that set and we
240         // can re-start.
241         if (ChildSCC == this) {
242           while (!PendingSCCStack.empty())
243             insert(G, *PendingSCCStack.pop_back_val());
244           while (!DFSStack.empty())
245             insert(G, *DFSStack.pop_back_val().first);
246           Recurse = true;
247           break;
248         }
249
250         // If this child isn't currently in this SCC, no need to process it.
251         // However, we do need to remove this SCC from its SCC's parent set.
252         ChildSCC->ParentSCCs.erase(this);
253         continue;
254       }
255
256       if (ChildN.DFSNumber == 0) {
257         // Mark that we should start at this child when next this node is the
258         // top of the stack. We don't start at the next child to ensure this
259         // child's lowlink is reflected.
260         DFSStack.back().second = I;
261
262         // Recurse onto this node via a tail call.
263         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
264         DFSStack.push_back(std::make_pair(&ChildN, ChildN.begin()));
265         Recurse = true;
266         break;
267       }
268
269       // Track the lowest link of the childen, if any are still in the stack.
270       // Any child not on the stack will have a LowLink of -1.
271       assert(ChildN.LowLink != 0 &&
272              "Low-link must not be zero with a non-zero DFS number.");
273       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
274         N->LowLink = ChildN.LowLink;
275     }
276     if (Recurse)
277       continue;
278
279     // No more children to process, pop it off the core DFS stack.
280     DFSStack.pop_back();
281
282     if (N->LowLink == N->DFSNumber) {
283       ResultSCCs.push_back(G.formSCC(N, PendingSCCStack));
284       continue;
285     }
286
287     assert(!DFSStack.empty() && "We shouldn't have an empty stack!");
288
289     // At this point we know that N cannot ever be an SCC root. Its low-link
290     // is not its dfs-number, and we've processed all of its children. It is
291     // just sitting here waiting until some node further down the stack gets
292     // low-link == dfs-number and pops it off as well. Move it to the pending
293     // stack which is pulled into the next SCC to be formed.
294     PendingSCCStack.push_back(N);
295   }
296
297   // Now we need to reconnect the current SCC to the graph.
298   bool IsLeafSCC = true;
299   for (Node *N : Nodes) {
300     for (Node &ChildN : *N) {
301       SCC &ChildSCC = *G.SCCMap.lookup(&ChildN);
302       if (&ChildSCC == this)
303         continue;
304       ChildSCC.ParentSCCs.insert(this);
305       IsLeafSCC = false;
306     }
307   }
308 #ifndef NDEBUG
309   if (ResultSCCs.size() > 1)
310     assert(!IsLeafSCC && "This SCC cannot be a leaf as we have split out new "
311                          "SCCs by removing this edge.");
312   if (!std::any_of(G.LeafSCCs.begin(), G.LeafSCCs.end(),
313                    [&](SCC *C) { return C == this; }))
314     assert(!IsLeafSCC && "This SCC cannot be a leaf as it already had child "
315                          "SCCs before we removed this edge.");
316 #endif
317   // If this SCC stopped being a leaf through this edge removal, remove it from
318   // the leaf SCC list.
319   if (!IsLeafSCC && ResultSCCs.size() > 1)
320     G.LeafSCCs.erase(std::remove(G.LeafSCCs.begin(), G.LeafSCCs.end(), this),
321                      G.LeafSCCs.end());
322
323   // Return the new list of SCCs.
324   return ResultSCCs;
325 }
326
327 void LazyCallGraph::removeEdge(Node &CallerN, Function &Callee) {
328   auto IndexMapI = CallerN.CalleeIndexMap.find(&Callee);
329   assert(IndexMapI != CallerN.CalleeIndexMap.end() &&
330          "Callee not in the callee set for the caller?");
331
332   Node *CalleeN = CallerN.Callees[IndexMapI->second].dyn_cast<Node *>();
333   CallerN.Callees.erase(CallerN.Callees.begin() + IndexMapI->second);
334   CallerN.CalleeIndexMap.erase(IndexMapI);
335
336   SCC *CallerC = SCCMap.lookup(&CallerN);
337   if (!CallerC) {
338     // We can only remove edges when the edge isn't actively participating in
339     // a DFS walk. Either it must have been popped into an SCC, or it must not
340     // yet have been reached by the DFS walk. Assert the latter here.
341     assert(std::all_of(DFSStack.begin(), DFSStack.end(),
342                        [&](const std::pair<Node *, iterator> &StackEntry) {
343              return StackEntry.first != &CallerN;
344            }) &&
345            "Found the caller on the DFSStack!");
346     return;
347   }
348
349   assert(CalleeN && "If the caller is in an SCC, we have to have explored all "
350                     "its transitively called functions.");
351
352   SCC *CalleeC = SCCMap.lookup(CalleeN);
353   assert(CalleeC &&
354          "The caller has an SCC, and thus by necessity so does the callee.");
355
356   // The easy case is when they are different SCCs.
357   if (CallerC != CalleeC) {
358     CallerC->removeEdge(*this, CallerN.getFunction(), Callee, *CalleeC);
359     return;
360   }
361
362   // The hard case is when we remove an edge within a SCC. This may cause new
363   // SCCs to need to be added to the graph.
364   CallerC->removeInternalEdge(*this, CallerN, *CalleeN);
365 }
366
367 LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
368   return *new (MappedN = BPA.Allocate()) Node(*this, F);
369 }
370
371 void LazyCallGraph::updateGraphPtrs() {
372   // Process all nodes updating the graph pointers.
373   SmallVector<Node *, 16> Worklist;
374   for (auto &Entry : EntryNodes)
375     if (Node *EntryN = Entry.dyn_cast<Node *>())
376       Worklist.push_back(EntryN);
377
378   while (!Worklist.empty()) {
379     Node *N = Worklist.pop_back_val();
380     N->G = this;
381     for (auto &Callee : N->Callees)
382       if (Node *CalleeN = Callee.dyn_cast<Node *>())
383         Worklist.push_back(CalleeN);
384   }
385 }
386
387 LazyCallGraph::SCC *LazyCallGraph::formSCC(Node *RootN,
388                                            SmallVectorImpl<Node *> &NodeStack) {
389   // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
390   // into it.
391   SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
392
393   while (!NodeStack.empty() && NodeStack.back()->DFSNumber > RootN->DFSNumber) {
394     assert(NodeStack.back()->LowLink >= RootN->LowLink &&
395            "We cannot have a low link in an SCC lower than its root on the "
396            "stack!");
397     NewSCC->insert(*this, *NodeStack.pop_back_val());
398   }
399   NewSCC->insert(*this, *RootN);
400
401   // A final pass over all edges in the SCC (this remains linear as we only
402   // do this once when we build the SCC) to connect it to the parent sets of
403   // its children.
404   bool IsLeafSCC = true;
405   for (Node *SCCN : NewSCC->Nodes)
406     for (Node &SCCChildN : *SCCN) {
407       if (SCCMap.lookup(&SCCChildN) == NewSCC)
408         continue;
409       SCC &ChildSCC = *SCCMap.lookup(&SCCChildN);
410       ChildSCC.ParentSCCs.insert(NewSCC);
411       IsLeafSCC = false;
412     }
413
414   // For the SCCs where we fine no child SCCs, add them to the leaf list.
415   if (IsLeafSCC)
416     LeafSCCs.push_back(NewSCC);
417
418   return NewSCC;
419 }
420
421 LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
422   // When the stack is empty, there are no more SCCs to walk in this graph.
423   if (DFSStack.empty()) {
424     // If we've handled all candidate entry nodes to the SCC forest, we're done.
425     if (SCCEntryNodes.empty())
426       return nullptr;
427
428     Node &N = get(*SCCEntryNodes.pop_back_val());
429     N.LowLink = N.DFSNumber = 1;
430     NextDFSNumber = 2;
431     DFSStack.push_back(std::make_pair(&N, N.begin()));
432   }
433
434   for (;;) {
435     Node *N = DFSStack.back().first;
436     assert(N->DFSNumber != 0 && "We should always assign a DFS number "
437                                 "before placing a node onto the stack.");
438
439     bool Recurse = false; // Used to simulate recursing onto a child.
440     for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
441       Node &ChildN = *I;
442       if (ChildN.DFSNumber == 0) {
443         // Mark that we should start at this child when next this node is the
444         // top of the stack. We don't start at the next child to ensure this
445         // child's lowlink is reflected.
446         DFSStack.back().second = I;
447
448         // Recurse onto this node via a tail call.
449         assert(!SCCMap.count(&ChildN) &&
450                "Found a node with 0 DFS number but already in an SCC!");
451         ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
452         SCCEntryNodes.remove(&ChildN.getFunction());
453         DFSStack.push_back(std::make_pair(&ChildN, ChildN.begin()));
454         Recurse = true;
455         break;
456       }
457
458       // Track the lowest link of the childen, if any are still in the stack.
459       assert(ChildN.LowLink != 0 &&
460              "Low-link must not be zero with a non-zero DFS number.");
461       if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
462         N->LowLink = ChildN.LowLink;
463     }
464     if (Recurse)
465       // Continue the outer loop when we exit the inner loop in order to
466       // recurse onto a child.
467       continue;
468
469     // No more children to process here, pop the node off the stack.
470     DFSStack.pop_back();
471
472     if (N->LowLink == N->DFSNumber)
473       // Form the new SCC out of the top of the DFS stack.
474       return formSCC(N, PendingSCCStack);
475
476     assert(!DFSStack.empty() && "We never found a viable root!");
477
478     // At this point we know that N cannot ever be an SCC root. Its low-link
479     // is not its dfs-number, and we've processed all of its children. It is
480     // just sitting here waiting until some node further down the stack gets
481     // low-link == dfs-number and pops it off as well. Move it to the pending
482     // stack which is pulled into the next SCC to be formed.
483     PendingSCCStack.push_back(N);
484   }
485 }
486
487 char LazyCallGraphAnalysis::PassID;
488
489 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
490
491 static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
492                        SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
493   // Recurse depth first through the nodes.
494   for (LazyCallGraph::Node &ChildN : N)
495     if (Printed.insert(&ChildN))
496       printNodes(OS, ChildN, Printed);
497
498   OS << "  Call edges in function: " << N.getFunction().getName() << "\n";
499   for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
500     OS << "    -> " << I->getFunction().getName() << "\n";
501
502   OS << "\n";
503 }
504
505 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
506   ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
507   OS << "  SCC with " << SCCSize << " functions:\n";
508
509   for (LazyCallGraph::Node *N : SCC)
510     OS << "    " << N->getFunction().getName() << "\n";
511
512   OS << "\n";
513 }
514
515 PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
516                                                 ModuleAnalysisManager *AM) {
517   LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
518
519   OS << "Printing the call graph for module: " << M->getModuleIdentifier()
520      << "\n\n";
521
522   SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
523   for (LazyCallGraph::Node &N : G)
524     if (Printed.insert(&N))
525       printNodes(OS, N, Printed);
526
527   for (LazyCallGraph::SCC &SCC : G.postorder_sccs())
528     printSCC(OS, SCC);
529
530   return PreservedAnalyses::all();
531
532 }