blob: 0a71b9d275860f73780b68cbe1dec4495cdfdae9 [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
10#include "llvm/Analysis/LazyCallGraph.h"
Chandler Carruth18eadd922014-04-18 10:50:32 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000012#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000013#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000014#include "llvm/IR/Instructions.h"
15#include "llvm/IR/PassManager.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000016#include "llvm/Support/Debug.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000017#include "llvm/Support/raw_ostream.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000018
19using namespace llvm;
20
Chandler Carruthf1221bd2014-04-22 02:48:03 +000021#define DEBUG_TYPE "lcg"
22
Chandler Carruthbf71a342014-02-06 04:37:03 +000023static void findCallees(
24 SmallVectorImpl<Constant *> &Worklist, SmallPtrSetImpl<Constant *> &Visited,
Chandler Carruthe9b50612014-03-10 02:14:14 +000025 SmallVectorImpl<PointerUnion<Function *, LazyCallGraph::Node *>> &Callees,
Chandler Carruth0b623ba2014-04-23 04:00:17 +000026 DenseMap<Function *, size_t> &CalleeIndexMap) {
Chandler Carruthbf71a342014-02-06 04:37:03 +000027 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.
Chandler Carruth0b623ba2014-04-23 04:00:17 +000041 if (!F->isDeclaration() &&
42 CalleeIndexMap.insert(std::make_pair(F, Callees.size())).second) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000043 DEBUG(dbgs() << " Added callable function: " << F->getName()
44 << "\n");
Chandler Carruthe9b50612014-03-10 02:14:14 +000045 Callees.push_back(F);
Chandler Carruth99b756d2014-04-21 05:04:24 +000046 }
Chandler Carruthbf71a342014-02-06 04:37:03 +000047 continue;
48 }
49
Chandler Carruth1583e992014-03-03 10:42:58 +000050 for (Value *Op : C->operand_values())
51 if (Visited.insert(cast<Constant>(Op)))
52 Worklist.push_back(cast<Constant>(Op));
Chandler Carruthbf71a342014-02-06 04:37:03 +000053 }
54}
55
Chandler Carruth18eadd922014-04-18 10:50:32 +000056LazyCallGraph::Node::Node(LazyCallGraph &G, Function &F)
57 : G(&G), F(F), DFSNumber(0), LowLink(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000058 DEBUG(dbgs() << " Adding functions called by '" << F.getName()
59 << "' to the graph.\n");
60
Chandler Carruthbf71a342014-02-06 04:37:03 +000061 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.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000065 for (BasicBlock &BB : F)
66 for (Instruction &I : BB)
67 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000068 if (Constant *C = dyn_cast<Constant>(Op))
Chandler Carruthbf71a342014-02-06 04:37:03 +000069 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.
Chandler Carruth0b623ba2014-04-23 04:00:17 +000075 findCallees(Worklist, Visited, Callees, CalleeIndexMap);
Chandler Carruthbf71a342014-02-06 04:37:03 +000076}
77
Chandler Carruth2174f442014-04-18 20:44:16 +000078LazyCallGraph::LazyCallGraph(Module &M) : NextDFSNumber(0) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000079 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
80 << "\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000081 for (Function &F : M)
82 if (!F.isDeclaration() && !F.hasLocalLinkage())
Chandler Carruth0b623ba2014-04-23 04:00:17 +000083 if (EntryIndexMap.insert(std::make_pair(&F, EntryNodes.size())).second) {
Chandler Carruth99b756d2014-04-21 05:04:24 +000084 DEBUG(dbgs() << " Adding '" << F.getName()
85 << "' to entry set of the graph.\n");
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000086 EntryNodes.push_back(&F);
Chandler Carruth99b756d2014-04-21 05:04:24 +000087 }
Chandler Carruthbf71a342014-02-06 04:37:03 +000088
89 // Now add entry nodes for functions reachable via initializers to globals.
90 SmallVector<Constant *, 16> Worklist;
91 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000092 for (GlobalVariable &GV : M.globals())
93 if (GV.hasInitializer())
94 if (Visited.insert(GV.getInitializer()))
95 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +000096
Chandler Carruth99b756d2014-04-21 05:04:24 +000097 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
98 "entry set.\n");
Chandler Carruth0b623ba2014-04-23 04:00:17 +000099 findCallees(Worklist, Visited, EntryNodes, EntryIndexMap);
Chandler Carruth18eadd922014-04-18 10:50:32 +0000100
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());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000106}
107
Chandler Carruthbf71a342014-02-06 04:37:03 +0000108LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000109 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
110 EntryNodes(std::move(G.EntryNodes)),
Chandler Carruth0b623ba2014-04-23 04:00:17 +0000111 EntryIndexMap(std::move(G.EntryIndexMap)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruth18eadd922014-04-18 10:50:32 +0000112 SCCMap(std::move(G.SCCMap)), LeafSCCs(std::move(G.LeafSCCs)),
113 DFSStack(std::move(G.DFSStack)),
Chandler Carruth2174f442014-04-18 20:44:16 +0000114 SCCEntryNodes(std::move(G.SCCEntryNodes)),
115 NextDFSNumber(G.NextDFSNumber) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000116 updateGraphPtrs();
117}
118
119LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
120 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000121 NodeMap = std::move(G.NodeMap);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000122 EntryNodes = std::move(G.EntryNodes);
Chandler Carruth0b623ba2014-04-23 04:00:17 +0000123 EntryIndexMap = std::move(G.EntryIndexMap);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000124 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);
Chandler Carruth2174f442014-04-18 20:44:16 +0000129 NextDFSNumber = G.NextDFSNumber;
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000130 updateGraphPtrs();
131 return *this;
132}
133
134LazyCallGraph::Node *LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
135 return new (MappedN = BPA.Allocate()) Node(*this, F);
136}
137
138void LazyCallGraph::updateGraphPtrs() {
Chandler Carruthb60cb312014-04-17 07:25:59 +0000139 // Process all nodes updating the graph pointers.
140 SmallVector<Node *, 16> Worklist;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000141 for (auto &Entry : EntryNodes)
142 if (Node *EntryN = Entry.dyn_cast<Node *>())
Chandler Carruthb60cb312014-04-17 07:25:59 +0000143 Worklist.push_back(EntryN);
144
145 while (!Worklist.empty()) {
146 Node *N = Worklist.pop_back_val();
147 N->G = this;
148 for (auto &Callee : N->Callees)
149 if (Node *CalleeN = Callee.dyn_cast<Node *>())
150 Worklist.push_back(CalleeN);
151 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000152}
Chandler Carruthbf71a342014-02-06 04:37:03 +0000153
Chandler Carruth3f9869a2014-04-23 06:09:03 +0000154LazyCallGraph::SCC *LazyCallGraph::formSCCFromDFSStack(
155 SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack) {
156 // The tail of the stack is the new SCC. Allocate the SCC and pop the stack
157 // into it.
158 SCC *NewSCC = new (SCCBPA.Allocate()) SCC();
159
160 // Because we don't follow the strict Tarjan recursive formulation, walk
161 // from the top of the stack down, propagating the lowest link and stopping
162 // when the DFS number is the lowest link.
163 int LowestLink = DFSStack.back().first->LowLink;
164 do {
165 Node *SCCN = DFSStack.pop_back_val().first;
166 SCCMap[&SCCN->getFunction()] = NewSCC;
167 NewSCC->Nodes.push_back(SCCN);
168 LowestLink = std::min(LowestLink, SCCN->LowLink);
169 bool Inserted =
170 NewSCC->NodeSet.insert(&SCCN->getFunction());
171 (void)Inserted;
172 assert(Inserted && "Cannot have duplicates in the DFSStack!");
173 } while (!DFSStack.empty() && LowestLink <= DFSStack.back().first->DFSNumber);
174 assert(LowestLink == NewSCC->Nodes.back()->DFSNumber &&
175 "Cannot stop with a DFS number greater than the lowest link!");
176
177 // A final pass over all edges in the SCC (this remains linear as we only
178 // do this once when we build the SCC) to connect it to the parent sets of
179 // its children.
180 bool IsLeafSCC = true;
181 for (Node *SCCN : NewSCC->Nodes)
182 for (Node *SCCChildN : *SCCN) {
183 if (NewSCC->NodeSet.count(&SCCChildN->getFunction()))
184 continue;
185 SCC *ChildSCC = SCCMap.lookup(&SCCChildN->getFunction());
186 assert(ChildSCC &&
187 "Must have all child SCCs processed when building a new SCC!");
188 ChildSCC->ParentSCCs.insert(NewSCC);
189 IsLeafSCC = false;
190 }
191
192 // For the SCCs where we fine no child SCCs, add them to the leaf list.
193 if (IsLeafSCC)
194 LeafSCCs.push_back(NewSCC);
195
196 return NewSCC;
197}
198
Chandler Carruth18eadd922014-04-18 10:50:32 +0000199LazyCallGraph::SCC *LazyCallGraph::getNextSCCInPostOrder() {
200 // When the stack is empty, there are no more SCCs to walk in this graph.
201 if (DFSStack.empty()) {
202 // If we've handled all candidate entry nodes to the SCC forest, we're done.
203 if (SCCEntryNodes.empty())
204 return nullptr;
205
Chandler Carruthc7bad9a2014-04-23 08:08:49 +0000206 // Reset the DFS numbering.
207 NextDFSNumber = 1;
Chandler Carruth18eadd922014-04-18 10:50:32 +0000208 Node *N = get(*SCCEntryNodes.pop_back_val());
209 DFSStack.push_back(std::make_pair(N, N->begin()));
210 }
211
212 Node *N = DFSStack.back().first;
213 if (N->DFSNumber == 0) {
214 // This node hasn't been visited before, assign it a DFS number and remove
215 // it from the entry set.
216 N->LowLink = N->DFSNumber = NextDFSNumber++;
217 SCCEntryNodes.remove(&N->getFunction());
218 }
219
220 for (auto I = DFSStack.back().second, E = N->end(); I != E; ++I) {
221 Node *ChildN = *I;
222 if (ChildN->DFSNumber == 0) {
223 // Mark that we should start at this child when next this node is the
224 // top of the stack. We don't start at the next child to ensure this
225 // child's lowlink is reflected.
226 // FIXME: I don't actually think this is required, and we could start
227 // at the next child.
228 DFSStack.back().second = I;
229
230 // Recurse onto this node via a tail call.
231 DFSStack.push_back(std::make_pair(ChildN, ChildN->begin()));
232 return LazyCallGraph::getNextSCCInPostOrder();
233 }
234
235 // Track the lowest link of the childen, if any are still in the stack.
236 if (ChildN->LowLink < N->LowLink && !SCCMap.count(&ChildN->getFunction()))
237 N->LowLink = ChildN->LowLink;
238 }
239
Chandler Carruth3f9869a2014-04-23 06:09:03 +0000240 // Form the new SCC out of the top of the DFS stack.
241 return formSCCFromDFSStack(DFSStack);
Chandler Carruth18eadd922014-04-18 10:50:32 +0000242}
243
Chandler Carruthbf71a342014-02-06 04:37:03 +0000244char LazyCallGraphAnalysis::PassID;
245
246LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
247
248static void printNodes(raw_ostream &OS, LazyCallGraph::Node &N,
249 SmallPtrSetImpl<LazyCallGraph::Node *> &Printed) {
250 // Recurse depth first through the nodes.
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000251 for (LazyCallGraph::Node *ChildN : N)
252 if (Printed.insert(ChildN))
253 printNodes(OS, *ChildN, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000254
255 OS << " Call edges in function: " << N.getFunction().getName() << "\n";
256 for (LazyCallGraph::iterator I = N.begin(), E = N.end(); I != E; ++I)
257 OS << " -> " << I->getFunction().getName() << "\n";
258
259 OS << "\n";
260}
261
Chandler Carruth18eadd922014-04-18 10:50:32 +0000262static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &SCC) {
263 ptrdiff_t SCCSize = std::distance(SCC.begin(), SCC.end());
264 OS << " SCC with " << SCCSize << " functions:\n";
265
266 for (LazyCallGraph::Node *N : SCC)
267 OS << " " << N->getFunction().getName() << "\n";
268
269 OS << "\n";
270}
271
Chandler Carruthe9b50612014-03-10 02:14:14 +0000272PreservedAnalyses LazyCallGraphPrinterPass::run(Module *M,
273 ModuleAnalysisManager *AM) {
Chandler Carruthbf71a342014-02-06 04:37:03 +0000274 LazyCallGraph &G = AM->getResult<LazyCallGraphAnalysis>(M);
275
Chandler Carruthe9b50612014-03-10 02:14:14 +0000276 OS << "Printing the call graph for module: " << M->getModuleIdentifier()
277 << "\n\n";
Chandler Carruthbf71a342014-02-06 04:37:03 +0000278
279 SmallPtrSet<LazyCallGraph::Node *, 16> Printed;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000280 for (LazyCallGraph::Node *N : G)
281 if (Printed.insert(N))
282 printNodes(OS, *N, Printed);
Chandler Carruthbf71a342014-02-06 04:37:03 +0000283
Chandler Carruth18eadd922014-04-18 10:50:32 +0000284 for (LazyCallGraph::SCC *SCC : G.postorder_sccs())
285 printSCC(OS, *SCC);
286
Chandler Carruthbf71a342014-02-06 04:37:03 +0000287 return PreservedAnalyses::all();
Chandler Carruth18eadd922014-04-18 10:50:32 +0000288
Chandler Carruthbf71a342014-02-06 04:37:03 +0000289}