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 #define DEBUG_TYPE "lcg"
11 #include "llvm/Analysis/LazyCallGraph.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/IR/CallSite.h"
14 #include "llvm/IR/InstVisitor.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/PassManager.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
22 static void findCallees(
23 SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
24 SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
25 SmallPtrSetImpl<Function *> &CalleeSet) {
26 while (!Worklist.empty()) {
27 Constant *C = Worklist.pop_back_val();
29 if (Function *F = dyn_cast<Function>(C)) {
30 // Note that we consider *any* function with a definition to be a viable
31 // edge. Even if the function's definition is subject to replacement by
32 // some other module (say, a weak definition) there may still be
33 // optimizations which essentially speculate based on the definition and
34 // a way to check that the specific definition is in fact the one being
35 // used. For example, this could be done by moving the weak definition to
36 // a strong (internal) definition and making the weak definition be an
37 // alias. Then a test of the address of the weak function against the new
38 // strong definition's address would be an effective way to determine the
39 // safety of optimizing a direct call edge.
40 if (!F->isDeclaration() && CalleeSet.insert(F)) {
41 DEBUG(dbgs() << " Added callable function: " << F->getName()
48 for (Value *Op : C->operand_values())
49 if (Visited.insert(cast<Constant>(Op)))
50 Worklist.push_back(cast<Constant>(Op));
54 LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
55 : G(&G), F(F), DFSNumber(0), LowLink(0) {
56 DEBUG(dbgs() << " Adding functions called by '" << F.getName()
57 << "' to the graph.\n");
59 SmallVector<Constant *, 16> Worklist;
60 SmallPtrSet<Constant *, 16> Visited;
61 // Find all the potential callees in this function. First walk the
62 // instructions and add every operand which is a constant to the worklist.
63 for (BasicBlock &BB : F)
64 for (Instruction &I : BB)
65 for (Value *Op : I.operand_values())
66 if (Constant *C = dyn_cast<Constant>(Op))
67 if (Visited.insert(C))
68 Worklist.push_back(C);
70 // We've collected all the constant (and thus potentially function or
71 // function containing) operands to all of the instructions in the function.
72 // Process them (recursively) collecting every function found.
73 findCallees(Worklist, Visited, Callees, CalleeSet);
76 LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
77 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
80 if (!F.isDeclaration() && !F.hasLocalLinkage())
81 if (EntryNodeSet.insert(&F)) {
82 DEBUG(dbgs() << " Adding '" << F.getName()
83 << "' to entry set of the graph.\n");
84 EntryNodes.push_back(&F);
87 // Now add entry nodes for functions reachable via initializers to globals.
88 SmallVector<Constant *, 16> Worklist;
89 SmallPtrSet<Constant *, 16> Visited;
90 for (GlobalVariable &GV : M.globals())
91 if (GV.hasInitializer())
92 if (Visited.insert(GV.getInitializer()))
93 Worklist.push_back(GV.getInitializer());
95 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
97 findCallees(Worklist, Visited, EntryNodes, EntryNodeSet);
99 for (auto &Entry : EntryNodes)
100 if (Function *F = Entry.dyn_cast<Function *>())
101 SCCEntryNodes.insert(F);
103 SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
106 LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
107 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
108 EntryNodes(std::move(G.EntryNodes)),
109 EntryNodeSet(std::move(G.EntryNodeSet)), SCCBPA(std::move(G.SCCBPA)),
110 SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
111 DFSStack(std::move(G.DFSStack)),
112 SCCEntryNodes(std::move(G.SCCEntryNodes)),
113 NextDFSNumber(G.NextDFSNumber) {
117 LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
118 BPA = std::move(G.BPA);
119 NodeMap = std::move(G.NodeMap);
120 EntryNodes = std::move(G.EntryNodes);
121 EntryNodeSet = std::move(G.EntryNodeSet);
122 SCCBPA = std::move(G.SCCBPA);
123 SCCMap = std::move(G.SCCMap);
124 LeafSCCs = std::move(G.LeafSCCs);
125 DFSStack = std::move(G.DFSStack);
126 SCCEntryNodes = std::move(G.SCCEntryNodes);
127 NextDFSNumber = G.NextDFSNumber;
132 LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
133 return new (MappedN = BPA.Allocate()) Node(*this, F);
136 void LazyCallGraph::updateGraphPtrs() {
137 // Process all nodes updating the graph pointers.
138 SmallVector<Node *, 16> Worklist;
139 for (auto &Entry : EntryNodes)
140 if (Node *EntryN = Entry.dyn_cast<Node *>())
141 Worklist.push_back(EntryN);
143 while (!Worklist.empty()) {
144 Node *N = Worklist.pop_back_val();
146 for (auto &Callee : N->Callees)
147 if (Node *CalleeN = Callee.dyn_cast<Node *>())
148 Worklist.push_back(CalleeN);
152 LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
153 // When the stack is empty, there are no more SCCs to walk in this graph.
154 if (DFSStack.empty()) {
155 // If we've handled all candidate entry nodes to the SCC forest, we're done.
156 if (SCCEntryNodes.empty())
159 Node *N = get(*SCCEntryNodes.pop_back_val());
160 DFSStack.push_back(std::make_pair(N, N->begin()));
163 Node *N = DFSStack.back().first;
164 if (N->DFSNumber == 0) {
165 // This node hasn't been visited before, assign it a DFS number and remove
166 // it from the entry set.
167 N->LowLink = N->DFSNumber = NextDFSNumber++;
168 SCCEntryNodes.remove(&N->getFunction());
171 for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
173 if (ChildN->DFSNumber == 0) {
174 // Mark that we should start at this child when next this node is the
175 // top of the stack. We don't start at the next child to ensure this
176 // child's lowlink is reflected.
177 // FIXME: I don't actually think this is required, and we could start
178 // at the next child.
179 DFSStack.back().second = I;
181 // Recurse onto this node via a tail call.
182 DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
183 return LazyCallGraph::getNextSCCInPostOrder();
186 // Track the lowest link of the childen, if any are still in the stack.
187 if (ChildN->LowLink < N->LowLink && !SCCMap.count(&ChildN->getFunction()))
188 N->LowLink = ChildN->LowLink;
191 // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
193 SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
195 // Because we don't follow the strict Tarjan recursive formulation, walk
196 // from the top of the stack down, propagating the lowest link and stopping
197 // when the DFS number is the lowest link.
198 int LowestLink = N->LowLink;
200 Node *SCCN = DFSStack.pop_back_val().first;
201 SCCMap.insert(std::make_pair(&SCCN->getFunction(), NewSCC));
202 NewSCC->Nodes.push_back(SCCN);
203 LowestLink = std::min(LowestLink, SCCN->LowLink);
205 NewSCC->NodeSet.insert(&SCCN->getFunction());
207 assert(Inserted && "Cannot have duplicates in the DFSStack!");
208 } while (!DFSStack.empty() && LowestLink <= DFSStack.back().first->DFSNumber);
209 assert(LowestLink == NewSCC->Nodes.back()->DFSNumber &&
210 "Cannot stop with a DFS number greater than the lowest link!");
212 // A final pass over all edges in the SCC (this remains linear as we only
213 // do this once when we build the SCC) to connect it to the parent sets of
215 bool IsLeafSCC = true;
216 for (Node *SCCN : NewSCC->Nodes)
217 for (Node *SCCChildN : *SCCN) {
218 if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
220 SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
222 "Must have all child SCCs processed when building a new SCC!");
223 ChildSCC->ParentSCCs.insert(NewSCC);
227 // For the SCCs where we fine no child SCCs, add them to the leaf list.
229 LeafSCCs.push_back(NewSCC);
234 char LazyCallGraphAnalysis::PassID;
236 LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
238 static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
239 SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
240 // Recurse depth first through the nodes.
241 for (LazyCallGraph::Node *ChildN : N)
242 if (Printed.insert(ChildN))
243 printNodes(OS, *ChildN, Printed);
245 OS << " Call edges in function: " << N.getFunction().getName() << "\n";
246 for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
247 OS << " -> " << I->getFunction().getName() << "\n";
252 static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
253 ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
254 OS << " SCC with " << SCCSize << " functions:\n";
256 for (LazyCallGraph::Node *N : SCC)
257 OS << " " << N->getFunction().getName() << "\n";
262 PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
263 ModuleAnalysisManager *AM) {
264 LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
266 OS << "Printing the call graph for module: " << M->getModuleIdentifier()
269 SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
270 for (LazyCallGraph::Node *N : G)
271 if (Printed.insert(N))
272 printNodes(OS, *N, Printed);
274 for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
277 return PreservedAnalyses::all();