blob: 0da678e1611b851683df63a762cfdaa43f8faaa1 [file] [log] [blame]
Chris Lattner8d5a16c2002-03-06 18:00:49 +00001//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner41fbf302001-09-28 00:08:15 +00009
10#include "llvm/Analysis/CallGraph.h"
Eugene Zelenko4114bcf2017-07-24 23:16:33 +000011#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallVector.h"
Nico Weber0f38c602018-04-30 14:59:11 +000013#include "llvm/Config/llvm-config.h"
Chandler Carruth4bbfbdf2014-03-04 11:01:28 +000014#include "llvm/IR/CallSite.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000015#include "llvm/IR/Module.h"
Eugene Zelenko4114bcf2017-07-24 23:16:33 +000016#include "llvm/IR/Function.h"
17#include "llvm/IR/Intrinsics.h"
18#include "llvm/IR/PassManager.h"
19#include "llvm/Pass.h"
20#include "llvm/Support/Compiler.h"
David Greene265c0262009-12-23 20:03:58 +000021#include "llvm/Support/Debug.h"
Chris Lattner45cfe542009-08-23 06:03:38 +000022#include "llvm/Support/raw_ostream.h"
Eugene Zelenko4114bcf2017-07-24 23:16:33 +000023#include <algorithm>
24#include <cassert>
25
Chris Lattnerb81c0212004-04-12 05:36:32 +000026using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000027
Chandler Carruth54fec072013-11-26 04:19:30 +000028//===----------------------------------------------------------------------===//
29// Implementations of the CallGraph class methods.
30//
31
32CallGraph::CallGraph(Module &M)
Peter Collingbourne517aac82017-05-11 23:59:05 +000033 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
David Blaikie75e2b5a2015-08-05 20:55:50 +000034 CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
Chandler Carruth54fec072013-11-26 04:19:30 +000035 // Add every function to the call graph.
Yaron Keren3b50e962015-06-12 05:15:27 +000036 for (Function &F : M)
37 addToCallGraph(&F);
Chandler Carruth54fec072013-11-26 04:19:30 +000038}
39
Chandler Carruth5df12072015-08-16 06:35:19 +000040CallGraph::CallGraph(CallGraph &&Arg)
Peter Collingbourne517aac82017-05-11 23:59:05 +000041 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
Chandler Carruth5df12072015-08-16 06:35:19 +000042 ExternalCallingNode(Arg.ExternalCallingNode),
43 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
44 Arg.FunctionMap.clear();
Chandler Carruth5df12072015-08-16 06:35:19 +000045 Arg.ExternalCallingNode = nullptr;
46}
47
Chandler Carruth54fec072013-11-26 04:19:30 +000048CallGraph::~CallGraph() {
49 // CallsExternalNode is not in the function map, delete it explicitly.
David Blaikie75e2b5a2015-08-05 20:55:50 +000050 if (CallsExternalNode)
51 CallsExternalNode->allReferencesDropped();
Chandler Carruth54fec072013-11-26 04:19:30 +000052
53// Reset all node's use counts to zero before deleting them to prevent an
54// assertion from firing.
55#ifndef NDEBUG
Yaron Keren3b50e962015-06-12 05:15:27 +000056 for (auto &I : FunctionMap)
57 I.second->allReferencesDropped();
Chandler Carruth54fec072013-11-26 04:19:30 +000058#endif
Chris Lattner41fbf302001-09-28 00:08:15 +000059}
60
Rafael Espindolac143c752013-10-31 03:03:55 +000061void CallGraph::addToCallGraph(Function *F) {
62 CallGraphNode *Node = getOrInsertFunction(F);
63
Peter Collingbourne517aac82017-05-11 23:59:05 +000064 // If this function has external linkage or has its address taken, anything
65 // could call it.
66 if (!F->hasLocalLinkage() || F->hasAddressTaken())
Rafael Espindolac143c752013-10-31 03:03:55 +000067 ExternalCallingNode->addCalledFunction(CallSite(), Node);
68
69 // If this function is not defined in this translation unit, it could call
70 // anything.
71 if (F->isDeclaration() && !F->isIntrinsic())
David Blaikie75e2b5a2015-08-05 20:55:50 +000072 Node->addCalledFunction(CallSite(), CallsExternalNode.get());
Rafael Espindolac143c752013-10-31 03:03:55 +000073
74 // Look for calls by this function.
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +000075 for (BasicBlock &BB : *F)
76 for (Instruction &I : BB) {
77 if (auto CS = CallSite(&I)) {
Rafael Espindolac143c752013-10-31 03:03:55 +000078 const Function *Callee = CS.getCalledFunction();
Sanjoy Dasaabacb62015-06-18 19:28:26 +000079 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
Rafael Espindolac143c752013-10-31 03:03:55 +000080 // Indirect calls of intrinsics are not allowed so no need to check.
Sanjoy Dasaabacb62015-06-18 19:28:26 +000081 // We can be more precise here by using TargetArg returned by
82 // Intrinsic::isLeaf.
David Blaikie75e2b5a2015-08-05 20:55:50 +000083 Node->addCalledFunction(CS, CallsExternalNode.get());
Rafael Espindolac143c752013-10-31 03:03:55 +000084 else if (!Callee->isIntrinsic())
85 Node->addCalledFunction(CS, getOrInsertFunction(Callee));
86 }
87 }
88}
89
Chandler Carruth54fec072013-11-26 04:19:30 +000090void CallGraph::print(raw_ostream &OS) const {
Sanjoy Das152f3b52015-06-19 23:20:31 +000091 // Print in a deterministic order by sorting CallGraphNodes by name. We do
92 // this here to avoid slowing down the non-printing fast path.
93
94 SmallVector<CallGraphNode *, 16> Nodes;
95 Nodes.reserve(FunctionMap.size());
96
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +000097 for (const auto &I : *this)
98 Nodes.push_back(I.second.get());
Sanjoy Das152f3b52015-06-19 23:20:31 +000099
Fangrui Song3b35e172018-09-27 02:13:45 +0000100 llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
Sanjoy Das152f3b52015-06-19 23:20:31 +0000101 if (Function *LF = LHS->getFunction())
102 if (Function *RF = RHS->getFunction())
103 return LF->getName() < RF->getName();
104
105 return RHS->getFunction() != nullptr;
106 });
107
108 for (CallGraphNode *CN : Nodes)
109 CN->print(OS);
Chris Lattneraf8a4242004-08-08 03:27:49 +0000110}
111
Aaron Ballman1d03d382017-10-15 14:32:27 +0000112#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun88d20752017-01-28 02:02:38 +0000113LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
114#endif
Chris Lattner25e9cad2001-11-26 18:51:25 +0000115
Chris Lattnerd99d4d72002-07-18 04:43:16 +0000116// removeFunctionFromModule - Unlink the function from this module, returning
117// it. Because this removes the function from the module, the call graph node
118// is destroyed. This is only valid if the function does not call any other
119// functions (ie, there are no edges in it's CGN). The easiest way to do this
Chris Lattner25e9cad2001-11-26 18:51:25 +0000120// is to dropAllReferences before calling this.
121//
Chris Lattnerd99d4d72002-07-18 04:43:16 +0000122Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
Chris Lattner2adb8302009-08-31 02:24:20 +0000123 assert(CGN->empty() && "Cannot remove function from call "
Chris Lattnerd99d4d72002-07-18 04:43:16 +0000124 "graph if it references other functions!");
Chris Lattner5714c972003-08-31 20:36:52 +0000125 Function *F = CGN->getFunction(); // Get the function for the call graph node
Chris Lattner5714c972003-08-31 20:36:52 +0000126 FunctionMap.erase(F); // Remove the call graph node from the map
Chris Lattner25e9cad2001-11-26 18:51:25 +0000127
Chandler Carruth54fec072013-11-26 04:19:30 +0000128 M.getFunctionList().remove(F);
Chris Lattner5714c972003-08-31 20:36:52 +0000129 return F;
Chris Lattner25e9cad2001-11-26 18:51:25 +0000130}
131
Nick Lewycky9ad1cb52011-01-03 03:19:35 +0000132/// spliceFunction - Replace the function represented by this node by another.
133/// This does not rescan the body of the function, so it is suitable when
134/// splicing the body of the old function to the new while also updating all
135/// callers from old to new.
Nick Lewycky9ad1cb52011-01-03 03:19:35 +0000136void CallGraph::spliceFunction(const Function *From, const Function *To) {
137 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
138 assert(!FunctionMap.count(To) &&
139 "Pointing CallGraphNode at a function that already exists");
140 FunctionMapTy::iterator I = FunctionMap.find(From);
141 I->second->F = const_cast<Function*>(To);
David Blaikie75e2b5a2015-08-05 20:55:50 +0000142 FunctionMap[To] = std::move(I->second);
Nick Lewycky9ad1cb52011-01-03 03:19:35 +0000143 FunctionMap.erase(I);
144}
145
Chris Lattnerc54b1c12006-01-14 20:03:00 +0000146// getOrInsertFunction - This method is identical to calling operator[], but
147// it will insert a new CallGraphNode for the specified function if one does
148// not already exist.
149CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
David Blaikie75e2b5a2015-08-05 20:55:50 +0000150 auto &CGN = FunctionMap[F];
Chandler Carruth54fec072013-11-26 04:19:30 +0000151 if (CGN)
David Blaikie75e2b5a2015-08-05 20:55:50 +0000152 return CGN.get();
Chandler Carruth54fec072013-11-26 04:19:30 +0000153
154 assert((!F || F->getParent() == &M) && "Function not in current module!");
David Blaikie75e2b5a2015-08-05 20:55:50 +0000155 CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
156 return CGN.get();
Chris Lattnerc54b1c12006-01-14 20:03:00 +0000157}
158
Chandler Carruth54fec072013-11-26 04:19:30 +0000159//===----------------------------------------------------------------------===//
160// Implementations of the CallGraphNode class methods.
161//
162
Chris Lattner45cfe542009-08-23 06:03:38 +0000163void CallGraphNode::print(raw_ostream &OS) const {
Chris Lattner03839952005-12-22 06:07:52 +0000164 if (Function *F = getFunction())
Chris Lattnerb374b902009-08-31 03:15:49 +0000165 OS << "Call graph node for function: '" << F->getName() << "'";
Chris Lattner03839952005-12-22 06:07:52 +0000166 else
Chris Lattnerb374b902009-08-31 03:15:49 +0000167 OS << "Call graph node <<null function>>";
Fangrui Songaf7b1832018-07-30 19:41:25 +0000168
Chris Lattner62754132010-04-23 18:23:40 +0000169 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
Chris Lattner03839952005-12-22 06:07:52 +0000170
Benjamin Kramer8d0d2b62016-06-26 17:27:42 +0000171 for (const auto &I : *this) {
172 OS << " CS<" << I.first << "> calls ";
173 if (Function *FI = I.second->getFunction())
Chris Lattner62754132010-04-23 18:23:40 +0000174 OS << "function '" << FI->getName() <<"'\n";
175 else
176 OS << "external node\n";
177 }
178 OS << '\n';
Chris Lattner03839952005-12-22 06:07:52 +0000179}
180
Aaron Ballman1d03d382017-10-15 14:32:27 +0000181#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun88d20752017-01-28 02:02:38 +0000182LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
183#endif
Chris Lattner03839952005-12-22 06:07:52 +0000184
Chris Lattner75caee22008-04-13 19:41:25 +0000185/// removeCallEdgeFor - This method removes the edge in the node for the
186/// specified call site. Note that this method takes linear time, so it
187/// should be used sparingly.
188void CallGraphNode::removeCallEdgeFor(CallSite CS) {
Chris Lattnerbe577652009-08-31 07:23:46 +0000189 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
190 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chris Lattnera541b0f2009-09-01 06:31:31 +0000191 if (I->first == CS.getInstruction()) {
Chris Lattnerbe577652009-08-31 07:23:46 +0000192 I->second->DropRef();
193 *I = CalledFunctions.back();
194 CalledFunctions.pop_back();
195 return;
196 }
Chris Lattner75caee22008-04-13 19:41:25 +0000197 }
198}
199
Chris Lattnercd382a32004-09-18 21:34:34 +0000200// removeAnyCallEdgeTo - This method removes any call edges from this node to
201// the specified callee function. This takes more time to execute than
202// removeCallEdgeTo, so it should not be used unless necessary.
203void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
Chris Lattnerfff03c92004-09-19 19:01:06 +0000204 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
Chris Lattnerd85340f2006-07-12 18:29:36 +0000205 if (CalledFunctions[i].second == Callee) {
Chris Lattnerb374b902009-08-31 03:15:49 +0000206 Callee->DropRef();
Chris Lattnerfff03c92004-09-19 19:01:06 +0000207 CalledFunctions[i] = CalledFunctions.back();
208 CalledFunctions.pop_back();
209 --i; --e;
Chris Lattnercd382a32004-09-18 21:34:34 +0000210 }
211}
Reid Spencer4f1bd9e2006-06-07 22:00:26 +0000212
Duncan Sandsa2582da2008-10-03 07:36:09 +0000213/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
214/// from this node to the specified callee function.
215void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
Gabor Greif7f2e3812009-01-17 19:46:01 +0000216 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
217 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
218 CallRecord &CR = *I;
Craig Toppere703fcb2014-04-24 06:44:33 +0000219 if (CR.second == Callee && CR.first == nullptr) {
Chris Lattnerb374b902009-08-31 03:15:49 +0000220 Callee->DropRef();
221 *I = CalledFunctions.back();
222 CalledFunctions.pop_back();
Duncan Sandsa2582da2008-10-03 07:36:09 +0000223 return;
224 }
225 }
226}
227
Chris Lattnera51c39c2009-09-15 05:40:35 +0000228/// replaceCallEdge - This method replaces the edge in the node for the
229/// specified call site with a new one. Note that this method takes linear
230/// time, so it should be used sparingly.
231void CallGraphNode::replaceCallEdge(CallSite CS,
232 CallSite NewCS, CallGraphNode *NewNode){
233 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
234 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
235 if (I->first == CS.getInstruction()) {
236 I->second->DropRef();
237 I->first = NewCS.getInstruction();
238 I->second = NewNode;
239 NewNode->AddRef();
240 return;
241 }
242 }
243}
244
Chandler Carruth53fa0062016-03-10 14:33:10 +0000245// Provide an explicit template instantiation for the static ID.
Chandler Carruth33d56812016-11-23 17:53:26 +0000246AnalysisKey CallGraphAnalysis::Key;
Chandler Carruth53fa0062016-03-10 14:33:10 +0000247
Chandler Carruthf1b2c7b2016-03-10 11:24:11 +0000248PreservedAnalyses CallGraphPrinterPass::run(Module &M,
Sean Silva2fb9a982016-08-09 00:28:38 +0000249 ModuleAnalysisManager &AM) {
Chandler Carruth8e27cb22016-03-11 11:05:24 +0000250 AM.getResult<CallGraphAnalysis>(M).print(OS);
Chandler Carruthf1b2c7b2016-03-10 11:24:11 +0000251 return PreservedAnalyses::all();
252}
253
Chandler Carruth54fec072013-11-26 04:19:30 +0000254//===----------------------------------------------------------------------===//
Chandler Carruth5df12072015-08-16 06:35:19 +0000255// Out-of-line definitions of CallGraphAnalysis class members.
256//
257
Chandler Carruth5df12072015-08-16 06:35:19 +0000258//===----------------------------------------------------------------------===//
Chandler Carruth54fec072013-11-26 04:19:30 +0000259// Implementations of the CallGraphWrapperPass class methods.
260//
261
262CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
263 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
264}
265
Eugene Zelenko4114bcf2017-07-24 23:16:33 +0000266CallGraphWrapperPass::~CallGraphWrapperPass() = default;
Chandler Carruth54fec072013-11-26 04:19:30 +0000267
268void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
269 AU.setPreservesAll();
270}
271
272bool CallGraphWrapperPass::runOnModule(Module &M) {
273 // All the real work is done in the constructor for the CallGraph.
274 G.reset(new CallGraph(M));
275 return false;
276}
277
278INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
279 false, true)
280
281char CallGraphWrapperPass::ID = 0;
282
David Blaikieec31a302014-07-19 01:05:11 +0000283void CallGraphWrapperPass::releaseMemory() { G.reset(); }
Chandler Carruth54fec072013-11-26 04:19:30 +0000284
285void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
286 if (!G) {
287 OS << "No call graph has been built!\n";
288 return;
289 }
290
291 // Just delegate.
292 G->print(OS);
293}
294
Aaron Ballman1d03d382017-10-15 14:32:27 +0000295#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Davide Italianoa7e61b02015-11-23 02:58:42 +0000296LLVM_DUMP_METHOD
Craig Topperc34a25d2014-04-28 04:05:08 +0000297void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
Matthias Braun88d20752017-01-28 02:02:38 +0000298#endif
Chandler Carruth7a06f632016-03-10 11:08:44 +0000299
300namespace {
Eugene Zelenko4114bcf2017-07-24 23:16:33 +0000301
Chandler Carruth7a06f632016-03-10 11:08:44 +0000302struct CallGraphPrinterLegacyPass : public ModulePass {
303 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko4114bcf2017-07-24 23:16:33 +0000304
Chandler Carruth7a06f632016-03-10 11:08:44 +0000305 CallGraphPrinterLegacyPass() : ModulePass(ID) {
306 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
307 }
308
309 void getAnalysisUsage(AnalysisUsage &AU) const override {
310 AU.setPreservesAll();
311 AU.addRequiredTransitive<CallGraphWrapperPass>();
312 }
Eugene Zelenko4114bcf2017-07-24 23:16:33 +0000313
Chandler Carruth7a06f632016-03-10 11:08:44 +0000314 bool runOnModule(Module &M) override {
315 getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
316 return false;
317 }
318};
Eugene Zelenko4114bcf2017-07-24 23:16:33 +0000319
320} // end anonymous namespace
Chandler Carruth7a06f632016-03-10 11:08:44 +0000321
322char CallGraphPrinterLegacyPass::ID = 0;
323
324INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
325 "Print a call graph", true, true)
326INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
327INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
328 "Print a call graph", true, true)