blob: 1b6691234b520d24af95b9cbb3a1d12b66a75263 [file] [log] [blame]
Chandler Carruthbf71a342014-02-06 04:37:03 +00001//===- 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
Chandler Carruth99b756d2014-04-21 05:04:24 +000010#define DEBUG_TYPE "lcg"
Chandler Carruthbf71a342014-02-06 04:37:03 +000011#include "llvm/Analysis/LazyCallGraph.h"
Chandler Carruth18eadd922014-04-18 10:50:32 +000012#include "llvm/ADT/STLExtras.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000013#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000014#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000015#include "llvm/IR/Instructions.h"
16#include "llvm/IR/PassManager.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000017#include "llvm/Support/Debug.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000018#include "llvm/Support/raw_ostream.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000019
20using namespace llvm;
21
22static void findCallees(
23 SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
Chandler Carruthe9b50612014-03-10 02:14:14 +000024 SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
Chandler Carruthbf71a342014-02-06 04:37:03 +000025 SmallPtrSetImpl<Function *> &CalleeSet) {
26 while (!Worklist.empty()) {
27 Constant *C = Worklist.pop_back_val();
28
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.
Chandler Carruth99b756d2014-04-21 05:04:24 +000040 if (!F->isDeclaration() && CalleeSet.insert(F)) {
41 DEBUG(dbgs() << " Added callable function: " << F->getName()
42 << "\n");
Chandler Carruthe9b50612014-03-10 02:14:14 +000043 Callees.push_back(F);
Chandler Carruth99b756d2014-04-21 05:04:24 +000044 }
Chandler Carruthbf71a342014-02-06 04:37:03 +000045 continue;
46 }
47
Chandler Carruth1583e992014-03-03 10:42:58 +000048 for (Value *Op : C->operand_values())
49 if (Visited.insert(cast<Constant>(Op)))
50 Worklist.push_back(cast<Constant>(Op));
Chandler Carruthbf71a342014-02-06 04:37:03 +000051 }
52}
53
Chandler Carruth18eadd922014-04-18 10:50:32 +000054LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
55 : G(&G), F(F), DFSNumber(0), LowLink(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000056 DEBUG(dbgs() << " Adding functions called by '" << F.getName()
57 << "' to the graph.\n");
58
Chandler Carruthbf71a342014-02-06 04:37:03 +000059 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.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000063 for (BasicBlock &BB : F)
64 for (Instruction &I : BB)
65 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000066 if (Constant *C = dyn_cast<Constant>(Op))
Chandler Carruthbf71a342014-02-06 04:37:03 +000067 if (Visited.insert(C))
68 Worklist.push_back(C);
69
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);
74}
75
Chandler Carruth2174f442014-04-18 20:44:16 +000076LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000077 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
78 << "\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000079 for (Function &F : M)
80 if (!F.isDeclaration() && !F.hasLocalLinkage())
Chandler Carruth99b756d2014-04-21 05:04:24 +000081 if (EntryNodeSet.insert(&F)) {
82 DEBUG(dbgs() << " Adding '" << F.getName()
83 << "' to entry set of the graph.\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000084 EntryNodes.push_back(&F);
Chandler Carruth99b756d2014-04-21 05:04:24 +000085 }
Chandler Carruthbf71a342014-02-06 04:37:03 +000086
87 // Now add entry nodes for functions reachable via initializers to globals.
88 SmallVector<Constant *, 16> Worklist;
89 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000090 for (GlobalVariable &GV : M.globals())
91 if (GV.hasInitializer())
92 if (Visited.insert(GV.getInitializer()))
93 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +000094
Chandler Carruth99b756d2014-04-21 05:04:24 +000095 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
96 "entry set.\n");
Chandler Carruthbf71a342014-02-06 04:37:03 +000097 findCallees(Worklist, Visited, EntryNodes, EntryNodeSet);
Chandler Carruth18eadd922014-04-18 10:50:32 +000098
99 for (auto &Entry : EntryNodes)
100 if (Function *F = Entry.dyn_cast<Function *>())
101 SCCEntryNodes.insert(F);
102 else
103 SCCEntryNodes.insert(&Entry.get<Node *>()->getFunction());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000104}
105
Chandler Carruthbf71a342014-02-06 04:37:03 +0000106LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000107 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
108 EntryNodes(std::move(G.EntryNodes)),
Chandler Carruth18eadd922014-04-18 10:50:32 +0000109 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)),
Chandler Carruth2174f442014-04-18 20:44:16 +0000112 SCCEntryNodes(std::move(G.SCCEntryNodes)),
113 NextDFSNumber(G.NextDFSNumber) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000114 updateGraphPtrs();
115}
116
117LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
118 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000119 NodeMap = std::move(G.NodeMap);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000120 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);
Chandler Carruth2174f442014-04-18 20:44:16 +0000127 NextDFSNumber = G.NextDFSNumber;
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000128 updateGraphPtrs();
129 return *this;
130}
131
132LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
133 return new (MappedN = BPA.Allocate()) Node(*this, F);
134}
135
136void LazyCallGraph::updateGraphPtrs() {
Chandler Carruthb60cb312014-04-17 07:25:59 +0000137 // Process all nodes updating the graph pointers.
138 SmallVector<Node *, 16> Worklist;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000139 for (auto &Entry : EntryNodes)
140 if (Node *EntryN = Entry.dyn_cast<Node *>())
Chandler Carruthb60cb312014-04-17 07:25:59 +0000141 Worklist.push_back(EntryN);
142
143 while (!Worklist.empty()) {
144 Node *N = Worklist.pop_back_val();
145 N->G = this;
146 for (auto &Callee : N->Callees)
147 if (Node *CalleeN = Callee.dyn_cast<Node *>())
148 Worklist.push_back(CalleeN);
149 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000150}
Chandler Carruthbf71a342014-02-06 04:37:03 +0000151
Chandler Carruth18eadd922014-04-18 10:50:32 +0000152LazyCallGraph::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())
157 return nullptr;
158
159 Node *N = get(*SCCEntryNodes.pop_back_val());
160 DFSStack.push_back(std::make_pair(N, N->begin()));
161 }
162
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());
169 }
170
171 for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
172 Node *ChildN = *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;
180
181 // Recurse onto this node via a tail call.
182 DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
183 return LazyCallGraph::getNextSCCInPostOrder();
184 }
185
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;
189 }
190
191 // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
192 // into it.
193 SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
194
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;
199 do {
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);
204 bool Inserted =
205 NewSCC->NodeSet.insert(&SCCN->getFunction());
206 (void)Inserted;
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!");
211
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
214 // its children.
215 bool IsLeafSCC = true;
216 for (Node *SCCN : NewSCC->Nodes)
217 for (Node *SCCChildN : *SCCN) {
218 if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
219 continue;
220 SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
221 assert(ChildSCC &&
222 "Must have all child SCCs processed when building a new SCC!");
223 ChildSCC->ParentSCCs.insert(NewSCC);
224 IsLeafSCC = false;
225 }
226
227 // For the SCCs where we fine no child SCCs, add them to the leaf list.
228 if (IsLeafSCC)
229 LeafSCCs.push_back(NewSCC);
230
231 return NewSCC;
232}
233
Chandler Carruthbf71a342014-02-06 04:37:03 +0000234char LazyCallGraphAnalysis::PassID;
235
236LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
237
238static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
239 SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
240 // Recurse depth first through the nodes.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000241 for (LazyCallGraph::Node *ChildN : N)
242 if (Printed.insert(ChildN))
243 printNodes(OS, *ChildN, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000244
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";
248
249 OS << "\n";
250}
251
Chandler Carruth18eadd922014-04-18 10:50:32 +0000252static 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";
255
256 for (LazyCallGraph::Node *N : SCC)
257 OS << " " << N->getFunction().getName() << "\n";
258
259 OS << "\n";
260}
261
Chandler Carruthe9b50612014-03-10 02:14:14 +0000262PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
263 ModuleAnalysisManager *AM) {
Chandler Carruthbf71a342014-02-06 04:37:03 +0000264 LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
265
Chandler Carruthe9b50612014-03-10 02:14:14 +0000266 OS << "Printing the call graph for module: " << M->getModuleIdentifier()
267 << "\n\n";
Chandler Carruthbf71a342014-02-06 04:37:03 +0000268
269 SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000270 for (LazyCallGraph::Node *N : G)
271 if (Printed.insert(N))
272 printNodes(OS, *N, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000273
Chandler Carruth18eadd922014-04-18 10:50:32 +0000274 for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
275 printSCC(OS, *SCC);
276
Chandler Carruthbf71a342014-02-06 04:37:03 +0000277 return PreservedAnalyses::all();
Chandler Carruth18eadd922014-04-18 10:50:32 +0000278
Chandler Carruthbf71a342014-02-06 04:37:03 +0000279}