blob: 594e886e53947c91fcca30da685069d1ff091838 [file] [log] [blame]
Chris Lattnerd852cc32002-03-06 18:00:49 +00001//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerbbf3ae82001-09-28 00:08:15 +00009
10#include "llvm/Analysis/CallGraph.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000011#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000012#include "llvm/IR/Instructions.h"
13#include "llvm/IR/IntrinsicInst.h"
14#include "llvm/IR/Module.h"
David Greeneba44b3e2009-12-23 20:03:58 +000015#include "llvm/Support/Debug.h"
Chris Lattner13626022009-08-23 06:03:38 +000016#include "llvm/Support/raw_ostream.h"
Chris Lattner8b6db182004-04-12 05:36:32 +000017using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000018
Chandler Carruth6378cf52013-11-26 04:19:30 +000019//===----------------------------------------------------------------------===//
20// Implementations of the CallGraph class methods.
21//
22
23CallGraph::CallGraph(Module &M)
Craig Topper353eda42014-04-24 06:44:33 +000024 : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
David Blaikiea5d7de92015-08-05 20:55:50 +000025 CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
Chandler Carruth6378cf52013-11-26 04:19:30 +000026 // Add every function to the call graph.
Yaron Keren26ceb082015-06-12 05:15:27 +000027 for (Function &F : M)
28 addToCallGraph(&F);
Chandler Carruth6378cf52013-11-26 04:19:30 +000029
30 // If we didn't find a main function, use the external call graph node
Craig Topper353eda42014-04-24 06:44:33 +000031 if (!Root)
Chandler Carruth6378cf52013-11-26 04:19:30 +000032 Root = ExternalCallingNode;
33}
34
Chandler Carruth5efd5302015-08-16 06:35:19 +000035CallGraph::CallGraph(CallGraph &&Arg)
36 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), Root(Arg.Root),
37 ExternalCallingNode(Arg.ExternalCallingNode),
38 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
39 Arg.FunctionMap.clear();
40 Arg.Root = nullptr;
41 Arg.ExternalCallingNode = nullptr;
42}
43
Chandler Carruth6378cf52013-11-26 04:19:30 +000044CallGraph::~CallGraph() {
45 // CallsExternalNode is not in the function map, delete it explicitly.
David Blaikiea5d7de92015-08-05 20:55:50 +000046 if (CallsExternalNode)
47 CallsExternalNode->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000048
49// Reset all node's use counts to zero before deleting them to prevent an
50// assertion from firing.
51#ifndef NDEBUG
Yaron Keren26ceb082015-06-12 05:15:27 +000052 for (auto &I : FunctionMap)
53 I.second->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000054#endif
Chris Lattnerbbf3ae82001-09-28 00:08:15 +000055}
56
Rafael Espindola6554e5a2013-10-31 03:03:55 +000057void CallGraph::addToCallGraph(Function *F) {
58 CallGraphNode *Node = getOrInsertFunction(F);
59
60 // If this function has external linkage, anything could call it.
61 if (!F->hasLocalLinkage()) {
62 ExternalCallingNode->addCalledFunction(CallSite(), Node);
63
64 // Found the entry point?
65 if (F->getName() == "main") {
66 if (Root) // Found multiple external mains? Don't pick one.
67 Root = ExternalCallingNode;
68 else
69 Root = Node; // Found a main, keep track of it!
70 }
71 }
72
73 // If this function has its address taken, anything could call it.
74 if (F->hasAddressTaken())
75 ExternalCallingNode->addCalledFunction(CallSite(), Node);
76
77 // If this function is not defined in this translation unit, it could call
78 // anything.
79 if (F->isDeclaration() && !F->isIntrinsic())
David Blaikiea5d7de92015-08-05 20:55:50 +000080 Node->addCalledFunction(CallSite(), CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000081
82 // Look for calls by this function.
83 for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
84 for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
85 ++II) {
86 CallSite CS(cast<Value>(II));
87 if (CS) {
88 const Function *Callee = CS.getCalledFunction();
Sanjoy Dasc65d43e2015-06-18 19:28:26 +000089 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
Rafael Espindola6554e5a2013-10-31 03:03:55 +000090 // Indirect calls of intrinsics are not allowed so no need to check.
Sanjoy Dasc65d43e2015-06-18 19:28:26 +000091 // We can be more precise here by using TargetArg returned by
92 // Intrinsic::isLeaf.
David Blaikiea5d7de92015-08-05 20:55:50 +000093 Node->addCalledFunction(CS, CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000094 else if (!Callee->isIntrinsic())
95 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
96 }
97 }
98}
99
Chandler Carruth6378cf52013-11-26 04:19:30 +0000100void CallGraph::print(raw_ostream &OS) const {
Rafael Espindola6554e5a2013-10-31 03:03:55 +0000101 OS << "CallGraph Root is: ";
102 if (Function *F = Root->getFunction())
103 OS << F->getName() << "\n";
104 else {
105 OS << "<<null function: 0x" << Root << ">>\n";
106 }
107
Sanjoy Das18c9dd32015-06-19 23:20:31 +0000108 // Print in a deterministic order by sorting CallGraphNodes by name. We do
109 // this here to avoid slowing down the non-printing fast path.
110
111 SmallVector<CallGraphNode *, 16> Nodes;
112 Nodes.reserve(FunctionMap.size());
113
114 for (auto I = begin(), E = end(); I != E; ++I)
David Blaikiea5d7de92015-08-05 20:55:50 +0000115 Nodes.push_back(I->second.get());
Sanjoy Das18c9dd32015-06-19 23:20:31 +0000116
117 std::sort(Nodes.begin(), Nodes.end(),
118 [](CallGraphNode *LHS, CallGraphNode *RHS) {
119 if (Function *LF = LHS->getFunction())
120 if (Function *RF = RHS->getFunction())
121 return LF->getName() < RF->getName();
122
123 return RHS->getFunction() != nullptr;
124 });
125
126 for (CallGraphNode *CN : Nodes)
127 CN->print(OS);
Chris Lattner6b5411022004-08-08 03:27:49 +0000128}
129
Davide Italiano6f93df82015-11-23 02:58:42 +0000130LLVM_DUMP_METHOD
Chandler Carruth6378cf52013-11-26 04:19:30 +0000131void CallGraph::dump() const { print(dbgs()); }
Chris Lattner03946cd2001-11-26 18:51:25 +0000132
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000133// removeFunctionFromModule - Unlink the function from this module, returning
134// it. Because this removes the function from the module, the call graph node
135// is destroyed. This is only valid if the function does not call any other
136// functions (ie, there are no edges in it's CGN). The easiest way to do this
Chris Lattner03946cd2001-11-26 18:51:25 +0000137// is to dropAllReferences before calling this.
138//
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000139Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
Chris Lattner4275cf22009-08-31 02:24:20 +0000140 assert(CGN->empty() && "Cannot remove function from call "
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000141 "graph if it references other functions!");
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000142 Function *F = CGN->getFunction(); // Get the function for the call graph node
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000143 FunctionMap.erase(F); // Remove the call graph node from the map
Chris Lattner03946cd2001-11-26 18:51:25 +0000144
Chandler Carruth6378cf52013-11-26 04:19:30 +0000145 M.getFunctionList().remove(F);
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000146 return F;
Chris Lattner03946cd2001-11-26 18:51:25 +0000147}
148
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000149/// spliceFunction - Replace the function represented by this node by another.
150/// This does not rescan the body of the function, so it is suitable when
151/// splicing the body of the old function to the new while also updating all
152/// callers from old to new.
153///
154void CallGraph::spliceFunction(const Function *From, const Function *To) {
155 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
156 assert(!FunctionMap.count(To) &&
157 "Pointing CallGraphNode at a function that already exists");
158 FunctionMapTy::iterator I = FunctionMap.find(From);
159 I->second->F = const_cast<Function*>(To);
David Blaikiea5d7de92015-08-05 20:55:50 +0000160 FunctionMap[To] = std::move(I->second);
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000161 FunctionMap.erase(I);
162}
163
Chris Lattner00ca8d22006-01-14 20:03:00 +0000164// getOrInsertFunction - This method is identical to calling operator[], but
165// it will insert a new CallGraphNode for the specified function if one does
166// not already exist.
167CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
David Blaikiea5d7de92015-08-05 20:55:50 +0000168 auto &CGN = FunctionMap[F];
Chandler Carruth6378cf52013-11-26 04:19:30 +0000169 if (CGN)
David Blaikiea5d7de92015-08-05 20:55:50 +0000170 return CGN.get();
Chandler Carruth6378cf52013-11-26 04:19:30 +0000171
172 assert((!F || F->getParent() == &M) && "Function not in current module!");
David Blaikiea5d7de92015-08-05 20:55:50 +0000173 CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
174 return CGN.get();
Chris Lattner00ca8d22006-01-14 20:03:00 +0000175}
176
Chandler Carruth6378cf52013-11-26 04:19:30 +0000177//===----------------------------------------------------------------------===//
178// Implementations of the CallGraphNode class methods.
179//
180
Chris Lattner13626022009-08-23 06:03:38 +0000181void CallGraphNode::print(raw_ostream &OS) const {
Chris Lattnerbe1987772005-12-22 06:07:52 +0000182 if (Function *F = getFunction())
Chris Lattner081375b2009-08-31 03:15:49 +0000183 OS << "Call graph node for function: '" << F->getName() << "'";
Chris Lattnerbe1987772005-12-22 06:07:52 +0000184 else
Chris Lattner081375b2009-08-31 03:15:49 +0000185 OS << "Call graph node <<null function>>";
186
Chris Lattner8c562542010-04-23 18:23:40 +0000187 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000188
Chris Lattner8c562542010-04-23 18:23:40 +0000189 for (const_iterator I = begin(), E = end(); I != E; ++I) {
190 OS << " CS<" << I->first << "> calls ";
Gabor Greif191812f2009-01-14 17:09:04 +0000191 if (Function *FI = I->second->getFunction())
Chris Lattner8c562542010-04-23 18:23:40 +0000192 OS << "function '" << FI->getName() <<"'\n";
193 else
194 OS << "external node\n";
195 }
196 OS << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000197}
198
Davide Italiano6f93df82015-11-23 02:58:42 +0000199LLVM_DUMP_METHOD
David Greeneba44b3e2009-12-23 20:03:58 +0000200void CallGraphNode::dump() const { print(dbgs()); }
Chris Lattnerbe1987772005-12-22 06:07:52 +0000201
Chris Lattnercc9709c2008-04-13 19:41:25 +0000202/// removeCallEdgeFor - This method removes the edge in the node for the
203/// specified call site. Note that this method takes linear time, so it
204/// should be used sparingly.
205void CallGraphNode::removeCallEdgeFor(CallSite CS) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000206 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
207 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chris Lattner063d0652009-09-01 06:31:31 +0000208 if (I->first == CS.getInstruction()) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000209 I->second->DropRef();
210 *I = CalledFunctions.back();
211 CalledFunctions.pop_back();
212 return;
213 }
Chris Lattnercc9709c2008-04-13 19:41:25 +0000214 }
215}
216
Chris Lattner824a2182004-09-18 21:34:34 +0000217// removeAnyCallEdgeTo - This method removes any call edges from this node to
218// the specified callee function. This takes more time to execute than
219// removeCallEdgeTo, so it should not be used unless necessary.
220void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000221 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000222 if (CalledFunctions[i].second == Callee) {
Chris Lattner081375b2009-08-31 03:15:49 +0000223 Callee->DropRef();
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000224 CalledFunctions[i] = CalledFunctions.back();
225 CalledFunctions.pop_back();
226 --i; --e;
Chris Lattner824a2182004-09-18 21:34:34 +0000227 }
228}
Reid Spencerbe535662006-06-07 22:00:26 +0000229
Duncan Sands3a813a52008-10-03 07:36:09 +0000230/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
231/// from this node to the specified callee function.
232void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
Gabor Greif20b722f2009-01-17 19:46:01 +0000233 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
234 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
235 CallRecord &CR = *I;
Craig Topper353eda42014-04-24 06:44:33 +0000236 if (CR.second == Callee && CR.first == nullptr) {
Chris Lattner081375b2009-08-31 03:15:49 +0000237 Callee->DropRef();
238 *I = CalledFunctions.back();
239 CalledFunctions.pop_back();
Duncan Sands3a813a52008-10-03 07:36:09 +0000240 return;
241 }
242 }
243}
244
Chris Lattnere0987212009-09-15 05:40:35 +0000245/// replaceCallEdge - This method replaces the edge in the node for the
246/// specified call site with a new one. Note that this method takes linear
247/// time, so it should be used sparingly.
248void CallGraphNode::replaceCallEdge(CallSite CS,
249 CallSite NewCS, CallGraphNode *NewNode){
250 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
251 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
252 if (I->first == CS.getInstruction()) {
253 I->second->DropRef();
254 I->first = NewCS.getInstruction();
255 I->second = NewNode;
256 NewNode->AddRef();
257 return;
258 }
259 }
260}
261
Chandler Carruth4c660f72016-03-10 11:24:11 +0000262PreservedAnalyses CallGraphPrinterPass::run(Module &M,
263 AnalysisManager<Module> *AM) {
264 AM->getResult<CallGraphAnalysis>(M).print(OS);
265 return PreservedAnalyses::all();
266}
267
Chandler Carruth6378cf52013-11-26 04:19:30 +0000268//===----------------------------------------------------------------------===//
Chandler Carruth5efd5302015-08-16 06:35:19 +0000269// Out-of-line definitions of CallGraphAnalysis class members.
270//
271
Chandler Carruth5efd5302015-08-16 06:35:19 +0000272//===----------------------------------------------------------------------===//
Chandler Carruth6378cf52013-11-26 04:19:30 +0000273// Implementations of the CallGraphWrapperPass class methods.
274//
275
276CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
277 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
278}
279
280CallGraphWrapperPass::~CallGraphWrapperPass() {}
281
282void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
283 AU.setPreservesAll();
284}
285
286bool CallGraphWrapperPass::runOnModule(Module &M) {
287 // All the real work is done in the constructor for the CallGraph.
288 G.reset(new CallGraph(M));
289 return false;
290}
291
292INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
293 false, true)
294
295char CallGraphWrapperPass::ID = 0;
296
David Blaikieb61064e2014-07-19 01:05:11 +0000297void CallGraphWrapperPass::releaseMemory() { G.reset(); }
Chandler Carruth6378cf52013-11-26 04:19:30 +0000298
299void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
300 if (!G) {
301 OS << "No call graph has been built!\n";
302 return;
303 }
304
305 // Just delegate.
306 G->print(OS);
307}
308
Davide Italiano6f93df82015-11-23 02:58:42 +0000309LLVM_DUMP_METHOD
Craig Toppere73658d2014-04-28 04:05:08 +0000310void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000311
312namespace {
313struct CallGraphPrinterLegacyPass : public ModulePass {
314 static char ID; // Pass ID, replacement for typeid
315 CallGraphPrinterLegacyPass() : ModulePass(ID) {
316 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
317 }
318
319 void getAnalysisUsage(AnalysisUsage &AU) const override {
320 AU.setPreservesAll();
321 AU.addRequiredTransitive<CallGraphWrapperPass>();
322 }
323 bool runOnModule(Module &M) override {
324 getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
325 return false;
326 }
327};
328}
329
330char CallGraphPrinterLegacyPass::ID = 0;
331
332INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
333 "Print a call graph", true, true)
334INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
335INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
336 "Print a call graph", true, true)