blob: 70aeb1a688ee0c0afb3f1580652c34b3f4dfbb1d [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukman01808ca2005-04-21 21:13:18 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattnerbbf3ae82001-09-28 00:08:15 +00008
9#include "llvm/Analysis/CallGraph.h"
Eugene Zelenko48666a62017-07-24 23:16:33 +000010#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallVector.h"
Nico Weber432a3882018-04-30 14:59:11 +000012#include "llvm/Config/llvm-config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000013#include "llvm/IR/Module.h"
Eugene Zelenko48666a62017-07-24 23:16:33 +000014#include "llvm/IR/Function.h"
15#include "llvm/IR/Intrinsics.h"
16#include "llvm/IR/PassManager.h"
17#include "llvm/Pass.h"
18#include "llvm/Support/Compiler.h"
David Greeneba44b3e2009-12-23 20:03:58 +000019#include "llvm/Support/Debug.h"
Chris Lattner13626022009-08-23 06:03:38 +000020#include "llvm/Support/raw_ostream.h"
Eugene Zelenko48666a62017-07-24 23:16:33 +000021#include <algorithm>
22#include <cassert>
23
Chris Lattner8b6db182004-04-12 05:36:32 +000024using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000025
Chandler Carruth6378cf52013-11-26 04:19:30 +000026//===----------------------------------------------------------------------===//
27// Implementations of the CallGraph class methods.
28//
29
30CallGraph::CallGraph(Module &M)
Peter Collingbournef3e9f122017-05-11 23:59:05 +000031 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
Jonas Devlieghere0eaee542019-08-15 15:54:37 +000032 CallsExternalNode(std::make_unique<CallGraphNode>(nullptr)) {
Chandler Carruth6378cf52013-11-26 04:19:30 +000033 // Add every function to the call graph.
Yaron Keren26ceb082015-06-12 05:15:27 +000034 for (Function &F : M)
35 addToCallGraph(&F);
Chandler Carruth6378cf52013-11-26 04:19:30 +000036}
37
Chandler Carruth5efd5302015-08-16 06:35:19 +000038CallGraph::CallGraph(CallGraph &&Arg)
Peter Collingbournef3e9f122017-05-11 23:59:05 +000039 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
Chandler Carruth5efd5302015-08-16 06:35:19 +000040 ExternalCallingNode(Arg.ExternalCallingNode),
41 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
42 Arg.FunctionMap.clear();
Chandler Carruth5efd5302015-08-16 06:35:19 +000043 Arg.ExternalCallingNode = nullptr;
44}
45
Chandler Carruth6378cf52013-11-26 04:19:30 +000046CallGraph::~CallGraph() {
47 // CallsExternalNode is not in the function map, delete it explicitly.
David Blaikiea5d7de92015-08-05 20:55:50 +000048 if (CallsExternalNode)
49 CallsExternalNode->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000050
51// Reset all node's use counts to zero before deleting them to prevent an
52// assertion from firing.
53#ifndef NDEBUG
Yaron Keren26ceb082015-06-12 05:15:27 +000054 for (auto &I : FunctionMap)
55 I.second->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000056#endif
Chris Lattnerbbf3ae82001-09-28 00:08:15 +000057}
58
Rafael Espindola6554e5a2013-10-31 03:03:55 +000059void CallGraph::addToCallGraph(Function *F) {
60 CallGraphNode *Node = getOrInsertFunction(F);
61
Peter Collingbournef3e9f122017-05-11 23:59:05 +000062 // If this function has external linkage or has its address taken, anything
63 // could call it.
64 if (!F->hasLocalLinkage() || F->hasAddressTaken())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000065 ExternalCallingNode->addCalledFunction(nullptr, Node);
Rafael Espindola6554e5a2013-10-31 03:03:55 +000066
67 // If this function is not defined in this translation unit, it could call
68 // anything.
69 if (F->isDeclaration() && !F->isIntrinsic())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000070 Node->addCalledFunction(nullptr, CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000071
72 // Look for calls by this function.
Benjamin Krameraa209152016-06-26 17:27:42 +000073 for (BasicBlock &BB : *F)
74 for (Instruction &I : BB) {
Chandler Carruthce3f75d2019-04-19 05:59:42 +000075 if (auto *Call = dyn_cast<CallBase>(&I)) {
76 const Function *Callee = Call->getCalledFunction();
Benjamin Kramer31a47f92019-08-16 10:59:18 +000077 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
Rafael Espindola6554e5a2013-10-31 03:03:55 +000078 // Indirect calls of intrinsics are not allowed so no need to check.
Sanjoy Dasc65d43e2015-06-18 19:28:26 +000079 // We can be more precise here by using TargetArg returned by
80 // Intrinsic::isLeaf.
Chandler Carruthce3f75d2019-04-19 05:59:42 +000081 Node->addCalledFunction(Call, CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000082 else if (!Callee->isIntrinsic())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000083 Node->addCalledFunction(Call, getOrInsertFunction(Callee));
Rafael Espindola6554e5a2013-10-31 03:03:55 +000084 }
85 }
86}
87
Chandler Carruth6378cf52013-11-26 04:19:30 +000088void CallGraph::print(raw_ostream &OS) const {
Sanjoy Das18c9dd32015-06-19 23:20:31 +000089 // Print in a deterministic order by sorting CallGraphNodes by name. We do
90 // this here to avoid slowing down the non-printing fast path.
91
92 SmallVector<CallGraphNode *, 16> Nodes;
93 Nodes.reserve(FunctionMap.size());
94
Benjamin Krameraa209152016-06-26 17:27:42 +000095 for (const auto &I : *this)
96 Nodes.push_back(I.second.get());
Sanjoy Das18c9dd32015-06-19 23:20:31 +000097
Fangrui Song0cac7262018-09-27 02:13:45 +000098 llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
Sanjoy Das18c9dd32015-06-19 23:20:31 +000099 if (Function *LF = LHS->getFunction())
100 if (Function *RF = RHS->getFunction())
101 return LF->getName() < RF->getName();
102
103 return RHS->getFunction() != nullptr;
104 });
105
106 for (CallGraphNode *CN : Nodes)
107 CN->print(OS);
Chris Lattner6b5411022004-08-08 03:27:49 +0000108}
109
Aaron Ballman615eb472017-10-15 14:32:27 +0000110#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000111LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
112#endif
Chris Lattner03946cd2001-11-26 18:51:25 +0000113
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000114// removeFunctionFromModule - Unlink the function from this module, returning
115// it. Because this removes the function from the module, the call graph node
116// is destroyed. This is only valid if the function does not call any other
117// functions (ie, there are no edges in it's CGN). The easiest way to do this
Chris Lattner03946cd2001-11-26 18:51:25 +0000118// is to dropAllReferences before calling this.
119//
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000120Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
Chris Lattner4275cf22009-08-31 02:24:20 +0000121 assert(CGN->empty() && "Cannot remove function from call "
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000122 "graph if it references other functions!");
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000123 Function *F = CGN->getFunction(); // Get the function for the call graph node
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000124 FunctionMap.erase(F); // Remove the call graph node from the map
Chris Lattner03946cd2001-11-26 18:51:25 +0000125
Chandler Carruth6378cf52013-11-26 04:19:30 +0000126 M.getFunctionList().remove(F);
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000127 return F;
Chris Lattner03946cd2001-11-26 18:51:25 +0000128}
129
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000130/// spliceFunction - Replace the function represented by this node by another.
131/// This does not rescan the body of the function, so it is suitable when
132/// splicing the body of the old function to the new while also updating all
133/// callers from old to new.
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000134void CallGraph::spliceFunction(const Function *From, const Function *To) {
135 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
136 assert(!FunctionMap.count(To) &&
137 "Pointing CallGraphNode at a function that already exists");
138 FunctionMapTy::iterator I = FunctionMap.find(From);
139 I->second->F = const_cast<Function*>(To);
David Blaikiea5d7de92015-08-05 20:55:50 +0000140 FunctionMap[To] = std::move(I->second);
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000141 FunctionMap.erase(I);
142}
143
Chris Lattner00ca8d22006-01-14 20:03:00 +0000144// getOrInsertFunction - This method is identical to calling operator[], but
145// it will insert a new CallGraphNode for the specified function if one does
146// not already exist.
147CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
David Blaikiea5d7de92015-08-05 20:55:50 +0000148 auto &CGN = FunctionMap[F];
Chandler Carruth6378cf52013-11-26 04:19:30 +0000149 if (CGN)
David Blaikiea5d7de92015-08-05 20:55:50 +0000150 return CGN.get();
Chandler Carruth6378cf52013-11-26 04:19:30 +0000151
152 assert((!F || F->getParent() == &M) && "Function not in current module!");
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000153 CGN = std::make_unique<CallGraphNode>(const_cast<Function *>(F));
David Blaikiea5d7de92015-08-05 20:55:50 +0000154 return CGN.get();
Chris Lattner00ca8d22006-01-14 20:03:00 +0000155}
156
Chandler Carruth6378cf52013-11-26 04:19:30 +0000157//===----------------------------------------------------------------------===//
158// Implementations of the CallGraphNode class methods.
159//
160
Chris Lattner13626022009-08-23 06:03:38 +0000161void CallGraphNode::print(raw_ostream &OS) const {
Chris Lattnerbe1987772005-12-22 06:07:52 +0000162 if (Function *F = getFunction())
Chris Lattner081375b2009-08-31 03:15:49 +0000163 OS << "Call graph node for function: '" << F->getName() << "'";
Chris Lattnerbe1987772005-12-22 06:07:52 +0000164 else
Chris Lattner081375b2009-08-31 03:15:49 +0000165 OS << "Call graph node <<null function>>";
Fangrui Songf78650a2018-07-30 19:41:25 +0000166
Chris Lattner8c562542010-04-23 18:23:40 +0000167 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000168
Benjamin Krameraa209152016-06-26 17:27:42 +0000169 for (const auto &I : *this) {
170 OS << " CS<" << I.first << "> calls ";
171 if (Function *FI = I.second->getFunction())
Chris Lattner8c562542010-04-23 18:23:40 +0000172 OS << "function '" << FI->getName() <<"'\n";
173 else
Benjamin Kramer31a47f92019-08-16 10:59:18 +0000174 OS << "external node\n";
Chris Lattner8c562542010-04-23 18:23:40 +0000175 }
176 OS << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000177}
178
Aaron Ballman615eb472017-10-15 14:32:27 +0000179#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000180LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
181#endif
Chris Lattnerbe1987772005-12-22 06:07:52 +0000182
Chris Lattnercc9709c2008-04-13 19:41:25 +0000183/// removeCallEdgeFor - This method removes the edge in the node for the
184/// specified call site. Note that this method takes linear time, so it
185/// should be used sparingly.
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000186void CallGraphNode::removeCallEdgeFor(CallBase &Call) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000187 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
188 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000189 if (I->first == &Call) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000190 I->second->DropRef();
191 *I = CalledFunctions.back();
192 CalledFunctions.pop_back();
193 return;
194 }
Chris Lattnercc9709c2008-04-13 19:41:25 +0000195 }
196}
197
Chris Lattner824a2182004-09-18 21:34:34 +0000198// removeAnyCallEdgeTo - This method removes any call edges from this node to
199// the specified callee function. This takes more time to execute than
200// removeCallEdgeTo, so it should not be used unless necessary.
201void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000202 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000203 if (CalledFunctions[i].second == Callee) {
Chris Lattner081375b2009-08-31 03:15:49 +0000204 Callee->DropRef();
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000205 CalledFunctions[i] = CalledFunctions.back();
206 CalledFunctions.pop_back();
207 --i; --e;
Chris Lattner824a2182004-09-18 21:34:34 +0000208 }
209}
Reid Spencerbe535662006-06-07 22:00:26 +0000210
Duncan Sands3a813a52008-10-03 07:36:09 +0000211/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
212/// from this node to the specified callee function.
213void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
Gabor Greif20b722f2009-01-17 19:46:01 +0000214 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
215 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
216 CallRecord &CR = *I;
Craig Topper353eda42014-04-24 06:44:33 +0000217 if (CR.second == Callee && CR.first == nullptr) {
Chris Lattner081375b2009-08-31 03:15:49 +0000218 Callee->DropRef();
219 *I = CalledFunctions.back();
220 CalledFunctions.pop_back();
Duncan Sands3a813a52008-10-03 07:36:09 +0000221 return;
222 }
223 }
224}
225
Chris Lattnere0987212009-09-15 05:40:35 +0000226/// replaceCallEdge - This method replaces the edge in the node for the
227/// specified call site with a new one. Note that this method takes linear
228/// time, so it should be used sparingly.
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000229void CallGraphNode::replaceCallEdge(CallBase &Call, CallBase &NewCall,
230 CallGraphNode *NewNode) {
Chris Lattnere0987212009-09-15 05:40:35 +0000231 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
232 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000233 if (I->first == &Call) {
Chris Lattnere0987212009-09-15 05:40:35 +0000234 I->second->DropRef();
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000235 I->first = &NewCall;
Chris Lattnere0987212009-09-15 05:40:35 +0000236 I->second = NewNode;
237 NewNode->AddRef();
238 return;
239 }
240 }
241}
242
Chandler Carruthcf3f4f22016-03-10 14:33:10 +0000243// Provide an explicit template instantiation for the static ID.
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000244AnalysisKey CallGraphAnalysis::Key;
Chandler Carruthcf3f4f22016-03-10 14:33:10 +0000245
Chandler Carruth4c660f72016-03-10 11:24:11 +0000246PreservedAnalyses CallGraphPrinterPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000247 ModuleAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000248 AM.getResult<CallGraphAnalysis>(M).print(OS);
Chandler Carruth4c660f72016-03-10 11:24:11 +0000249 return PreservedAnalyses::all();
250}
251
Chandler Carruth6378cf52013-11-26 04:19:30 +0000252//===----------------------------------------------------------------------===//
Chandler Carruth5efd5302015-08-16 06:35:19 +0000253// Out-of-line definitions of CallGraphAnalysis class members.
254//
255
Chandler Carruth5efd5302015-08-16 06:35:19 +0000256//===----------------------------------------------------------------------===//
Chandler Carruth6378cf52013-11-26 04:19:30 +0000257// Implementations of the CallGraphWrapperPass class methods.
258//
259
260CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
261 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
262}
263
Eugene Zelenko48666a62017-07-24 23:16:33 +0000264CallGraphWrapperPass::~CallGraphWrapperPass() = default;
Chandler Carruth6378cf52013-11-26 04:19:30 +0000265
266void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
267 AU.setPreservesAll();
268}
269
270bool CallGraphWrapperPass::runOnModule(Module &M) {
271 // All the real work is done in the constructor for the CallGraph.
272 G.reset(new CallGraph(M));
273 return false;
274}
275
276INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
277 false, true)
278
279char CallGraphWrapperPass::ID = 0;
280
David Blaikieb61064e2014-07-19 01:05:11 +0000281void CallGraphWrapperPass::releaseMemory() { G.reset(); }
Chandler Carruth6378cf52013-11-26 04:19:30 +0000282
283void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
284 if (!G) {
285 OS << "No call graph has been built!\n";
286 return;
287 }
288
289 // Just delegate.
290 G->print(OS);
291}
292
Aaron Ballman615eb472017-10-15 14:32:27 +0000293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Davide Italiano6f93df82015-11-23 02:58:42 +0000294LLVM_DUMP_METHOD
Craig Toppere73658d2014-04-28 04:05:08 +0000295void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
Matthias Braun8c209aa2017-01-28 02:02:38 +0000296#endif
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000297
298namespace {
Eugene Zelenko48666a62017-07-24 23:16:33 +0000299
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000300struct CallGraphPrinterLegacyPass : public ModulePass {
301 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko48666a62017-07-24 23:16:33 +0000302
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000303 CallGraphPrinterLegacyPass() : ModulePass(ID) {
304 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
305 }
306
307 void getAnalysisUsage(AnalysisUsage &AU) const override {
308 AU.setPreservesAll();
309 AU.addRequiredTransitive<CallGraphWrapperPass>();
310 }
Eugene Zelenko48666a62017-07-24 23:16:33 +0000311
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000312 bool runOnModule(Module &M) override {
313 getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
314 return false;
315 }
316};
Eugene Zelenko48666a62017-07-24 23:16:33 +0000317
318} // end anonymous namespace
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000319
320char CallGraphPrinterLegacyPass::ID = 0;
321
322INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
323 "Print a call graph", true, true)
324INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
325INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
326 "Print a call graph", true, true)