blob: a7bb16299a5ebb48790a95d19d48849adbd6a316 [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)),
Mark Lacey626ed222019-08-15 17:47:53 +000040 DummyNodeMap(std::move(Arg.DummyNodeMap)),
Chandler Carruth5efd5302015-08-16 06:35:19 +000041 ExternalCallingNode(Arg.ExternalCallingNode),
42 CallsExternalNode(std::move(Arg.CallsExternalNode)) {
43 Arg.FunctionMap.clear();
Chandler Carruth5efd5302015-08-16 06:35:19 +000044 Arg.ExternalCallingNode = nullptr;
45}
46
Chandler Carruth6378cf52013-11-26 04:19:30 +000047CallGraph::~CallGraph() {
48 // CallsExternalNode is not in the function map, delete it explicitly.
David Blaikiea5d7de92015-08-05 20:55:50 +000049 if (CallsExternalNode)
50 CallsExternalNode->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000051
52// Reset all node's use counts to zero before deleting them to prevent an
53// assertion from firing.
54#ifndef NDEBUG
Yaron Keren26ceb082015-06-12 05:15:27 +000055 for (auto &I : FunctionMap)
56 I.second->allReferencesDropped();
Mark Lacey626ed222019-08-15 17:47:53 +000057 for (auto &N : DummyNodeMap)
58 N.second->allReferencesDropped();
Chandler Carruth6378cf52013-11-26 04:19:30 +000059#endif
Chris Lattnerbbf3ae82001-09-28 00:08:15 +000060}
61
Rafael Espindola6554e5a2013-10-31 03:03:55 +000062void CallGraph::addToCallGraph(Function *F) {
63 CallGraphNode *Node = getOrInsertFunction(F);
64
Peter Collingbournef3e9f122017-05-11 23:59:05 +000065 // If this function has external linkage or has its address taken, anything
66 // could call it.
67 if (!F->hasLocalLinkage() || F->hasAddressTaken())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000068 ExternalCallingNode->addCalledFunction(nullptr, Node);
Rafael Espindola6554e5a2013-10-31 03:03:55 +000069
70 // If this function is not defined in this translation unit, it could call
71 // anything.
72 if (F->isDeclaration() && !F->isIntrinsic())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000073 Node->addCalledFunction(nullptr, CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000074
75 // Look for calls by this function.
Benjamin Krameraa209152016-06-26 17:27:42 +000076 for (BasicBlock &BB : *F)
77 for (Instruction &I : BB) {
Chandler Carruthce3f75d2019-04-19 05:59:42 +000078 if (auto *Call = dyn_cast<CallBase>(&I)) {
79 const Function *Callee = Call->getCalledFunction();
Mark Lacey626ed222019-08-15 17:47:53 +000080 MDNode *CalleesMD = I.getMetadata(LLVMContext::MD_callees);
81 if (!Callee && CalleesMD)
82 // If an indirect call site has !callees metadata indicating its
83 // possible callees, we add an edge from the call site to a dummy
84 // node. When we construct the dummy node, we add edges from it to
85 // the functions indicated in the !callees metadata.
86 Node->addCalledFunction(Call, getOrInsertNodeForCalleesMD(CalleesMD));
87 else if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
Rafael Espindola6554e5a2013-10-31 03:03:55 +000088 // Indirect calls of intrinsics are not allowed so no need to check.
Sanjoy Dasc65d43e2015-06-18 19:28:26 +000089 // We can be more precise here by using TargetArg returned by
90 // Intrinsic::isLeaf.
Chandler Carruthce3f75d2019-04-19 05:59:42 +000091 Node->addCalledFunction(Call, CallsExternalNode.get());
Rafael Espindola6554e5a2013-10-31 03:03:55 +000092 else if (!Callee->isIntrinsic())
Chandler Carruthce3f75d2019-04-19 05:59:42 +000093 Node->addCalledFunction(Call, getOrInsertFunction(Callee));
Rafael Espindola6554e5a2013-10-31 03:03:55 +000094 }
95 }
96}
97
Chandler Carruth6378cf52013-11-26 04:19:30 +000098void CallGraph::print(raw_ostream &OS) const {
Sanjoy Das18c9dd32015-06-19 23:20:31 +000099 // Print in a deterministic order by sorting CallGraphNodes by name. We do
100 // this here to avoid slowing down the non-printing fast path.
101
102 SmallVector<CallGraphNode *, 16> Nodes;
103 Nodes.reserve(FunctionMap.size());
104
Benjamin Krameraa209152016-06-26 17:27:42 +0000105 for (const auto &I : *this)
106 Nodes.push_back(I.second.get());
Sanjoy Das18c9dd32015-06-19 23:20:31 +0000107
Fangrui Song0cac7262018-09-27 02:13:45 +0000108 llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
Sanjoy Das18c9dd32015-06-19 23:20:31 +0000109 if (Function *LF = LHS->getFunction())
110 if (Function *RF = RHS->getFunction())
111 return LF->getName() < RF->getName();
112
113 return RHS->getFunction() != nullptr;
114 });
115
116 for (CallGraphNode *CN : Nodes)
117 CN->print(OS);
Mark Lacey626ed222019-08-15 17:47:53 +0000118
119 // The iteration order of the DummyNodeMap is deterministic, so we don't need
120 // to sort the nodes. Just print them.
121 for (auto &Entry : DummyNodeMap)
122 Entry.second->print(OS);
Chris Lattner6b5411022004-08-08 03:27:49 +0000123}
124
Aaron Ballman615eb472017-10-15 14:32:27 +0000125#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000126LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); }
127#endif
Chris Lattner03946cd2001-11-26 18:51:25 +0000128
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000129// removeFunctionFromModule - Unlink the function from this module, returning
130// it. Because this removes the function from the module, the call graph node
131// is destroyed. This is only valid if the function does not call any other
132// functions (ie, there are no edges in it's CGN). The easiest way to do this
Chris Lattner03946cd2001-11-26 18:51:25 +0000133// is to dropAllReferences before calling this.
134//
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000135Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
Chris Lattner4275cf22009-08-31 02:24:20 +0000136 assert(CGN->empty() && "Cannot remove function from call "
Chris Lattner79b0c7d2002-07-18 04:43:16 +0000137 "graph if it references other functions!");
Mark Lacey626ed222019-08-15 17:47:53 +0000138
139 // If any dummy node references the node for the given function, we first
140 // need to remove those edges.
141 for (auto &Entry : DummyNodeMap)
142 Entry.second->removeAnyCallEdgeTo(CGN);
143
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000144 Function *F = CGN->getFunction(); // Get the function for the call graph node
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000145 FunctionMap.erase(F); // Remove the call graph node from the map
Chris Lattner03946cd2001-11-26 18:51:25 +0000146
Chandler Carruth6378cf52013-11-26 04:19:30 +0000147 M.getFunctionList().remove(F);
Chris Lattner6f5e18d2003-08-31 20:36:52 +0000148 return F;
Chris Lattner03946cd2001-11-26 18:51:25 +0000149}
150
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000151/// spliceFunction - Replace the function represented by this node by another.
152/// This does not rescan the body of the function, so it is suitable when
153/// splicing the body of the old function to the new while also updating all
154/// callers from old to new.
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000155void CallGraph::spliceFunction(const Function *From, const Function *To) {
156 assert(FunctionMap.count(From) && "No CallGraphNode for function!");
157 assert(!FunctionMap.count(To) &&
158 "Pointing CallGraphNode at a function that already exists");
159 FunctionMapTy::iterator I = FunctionMap.find(From);
160 I->second->F = const_cast<Function*>(To);
David Blaikiea5d7de92015-08-05 20:55:50 +0000161 FunctionMap[To] = std::move(I->second);
Nick Lewycky0f87ca72011-01-03 03:19:35 +0000162 FunctionMap.erase(I);
163}
164
Chris Lattner00ca8d22006-01-14 20:03:00 +0000165// getOrInsertFunction - This method is identical to calling operator[], but
166// it will insert a new CallGraphNode for the specified function if one does
167// not already exist.
168CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
David Blaikiea5d7de92015-08-05 20:55:50 +0000169 auto &CGN = FunctionMap[F];
Chandler Carruth6378cf52013-11-26 04:19:30 +0000170 if (CGN)
David Blaikiea5d7de92015-08-05 20:55:50 +0000171 return CGN.get();
Chandler Carruth6378cf52013-11-26 04:19:30 +0000172
173 assert((!F || F->getParent() == &M) && "Function not in current module!");
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000174 CGN = std::make_unique<CallGraphNode>(const_cast<Function *>(F));
David Blaikiea5d7de92015-08-05 20:55:50 +0000175 return CGN.get();
Chris Lattner00ca8d22006-01-14 20:03:00 +0000176}
177
Mark Lacey626ed222019-08-15 17:47:53 +0000178CallGraphNode *CallGraph::getOrInsertNodeForCalleesMD(MDNode *Callees) {
179 auto &CGN = DummyNodeMap[Callees];
180 if (CGN)
181 return CGN.get();
182 CGN = llvm::make_unique<CallGraphNode>(nullptr);
183 for (const MDOperand &Op : Callees->operands())
184 if (auto *MDConstant = mdconst::extract_or_null<Constant>(Op)) {
185 auto *F = cast<Function>(MDConstant);
186
187 assert(!F->isIntrinsic());
188 CGN->addCalledFunction(nullptr, getOrInsertFunction(F));
189 }
190 return CGN.get();
191}
192
Chandler Carruth6378cf52013-11-26 04:19:30 +0000193//===----------------------------------------------------------------------===//
194// Implementations of the CallGraphNode class methods.
195//
196
Chris Lattner13626022009-08-23 06:03:38 +0000197void CallGraphNode::print(raw_ostream &OS) const {
Chris Lattnerbe1987772005-12-22 06:07:52 +0000198 if (Function *F = getFunction())
Chris Lattner081375b2009-08-31 03:15:49 +0000199 OS << "Call graph node for function: '" << F->getName() << "'";
Chris Lattnerbe1987772005-12-22 06:07:52 +0000200 else
Chris Lattner081375b2009-08-31 03:15:49 +0000201 OS << "Call graph node <<null function>>";
Fangrui Songf78650a2018-07-30 19:41:25 +0000202
Chris Lattner8c562542010-04-23 18:23:40 +0000203 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000204
Benjamin Krameraa209152016-06-26 17:27:42 +0000205 for (const auto &I : *this) {
206 OS << " CS<" << I.first << "> calls ";
207 if (Function *FI = I.second->getFunction())
Chris Lattner8c562542010-04-23 18:23:40 +0000208 OS << "function '" << FI->getName() <<"'\n";
209 else
Mark Lacey626ed222019-08-15 17:47:53 +0000210 OS << "<<null function>><<" << I.second << ">>\n";
Chris Lattner8c562542010-04-23 18:23:40 +0000211 }
212 OS << '\n';
Chris Lattnerbe1987772005-12-22 06:07:52 +0000213}
214
Aaron Ballman615eb472017-10-15 14:32:27 +0000215#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000216LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); }
217#endif
Chris Lattnerbe1987772005-12-22 06:07:52 +0000218
Chris Lattnercc9709c2008-04-13 19:41:25 +0000219/// removeCallEdgeFor - This method removes the edge in the node for the
220/// specified call site. Note that this method takes linear time, so it
221/// should be used sparingly.
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000222void CallGraphNode::removeCallEdgeFor(CallBase &Call) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000223 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
224 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000225 if (I->first == &Call) {
Chris Lattnereedcd842009-08-31 07:23:46 +0000226 I->second->DropRef();
227 *I = CalledFunctions.back();
228 CalledFunctions.pop_back();
229 return;
230 }
Chris Lattnercc9709c2008-04-13 19:41:25 +0000231 }
232}
233
Chris Lattner824a2182004-09-18 21:34:34 +0000234// removeAnyCallEdgeTo - This method removes any call edges from this node to
235// the specified callee function. This takes more time to execute than
236// removeCallEdgeTo, so it should not be used unless necessary.
237void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000238 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
Chris Lattner5de3b8b2006-07-12 18:29:36 +0000239 if (CalledFunctions[i].second == Callee) {
Chris Lattner081375b2009-08-31 03:15:49 +0000240 Callee->DropRef();
Chris Lattnerd6d99df2004-09-19 19:01:06 +0000241 CalledFunctions[i] = CalledFunctions.back();
242 CalledFunctions.pop_back();
243 --i; --e;
Chris Lattner824a2182004-09-18 21:34:34 +0000244 }
245}
Reid Spencerbe535662006-06-07 22:00:26 +0000246
Duncan Sands3a813a52008-10-03 07:36:09 +0000247/// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
248/// from this node to the specified callee function.
249void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
Gabor Greif20b722f2009-01-17 19:46:01 +0000250 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
251 assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
252 CallRecord &CR = *I;
Craig Topper353eda42014-04-24 06:44:33 +0000253 if (CR.second == Callee && CR.first == nullptr) {
Chris Lattner081375b2009-08-31 03:15:49 +0000254 Callee->DropRef();
255 *I = CalledFunctions.back();
256 CalledFunctions.pop_back();
Duncan Sands3a813a52008-10-03 07:36:09 +0000257 return;
258 }
259 }
260}
261
Chris Lattnere0987212009-09-15 05:40:35 +0000262/// replaceCallEdge - This method replaces the edge in the node for the
263/// specified call site with a new one. Note that this method takes linear
264/// time, so it should be used sparingly.
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000265void CallGraphNode::replaceCallEdge(CallBase &Call, CallBase &NewCall,
266 CallGraphNode *NewNode) {
Chris Lattnere0987212009-09-15 05:40:35 +0000267 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
268 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000269 if (I->first == &Call) {
Chris Lattnere0987212009-09-15 05:40:35 +0000270 I->second->DropRef();
Chandler Carruthce3f75d2019-04-19 05:59:42 +0000271 I->first = &NewCall;
Chris Lattnere0987212009-09-15 05:40:35 +0000272 I->second = NewNode;
273 NewNode->AddRef();
274 return;
275 }
276 }
277}
278
Chandler Carruthcf3f4f22016-03-10 14:33:10 +0000279// Provide an explicit template instantiation for the static ID.
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000280AnalysisKey CallGraphAnalysis::Key;
Chandler Carruthcf3f4f22016-03-10 14:33:10 +0000281
Chandler Carruth4c660f72016-03-10 11:24:11 +0000282PreservedAnalyses CallGraphPrinterPass::run(Module &M,
Sean Silvafd03ac62016-08-09 00:28:38 +0000283 ModuleAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000284 AM.getResult<CallGraphAnalysis>(M).print(OS);
Chandler Carruth4c660f72016-03-10 11:24:11 +0000285 return PreservedAnalyses::all();
286}
287
Chandler Carruth6378cf52013-11-26 04:19:30 +0000288//===----------------------------------------------------------------------===//
Chandler Carruth5efd5302015-08-16 06:35:19 +0000289// Out-of-line definitions of CallGraphAnalysis class members.
290//
291
Chandler Carruth5efd5302015-08-16 06:35:19 +0000292//===----------------------------------------------------------------------===//
Chandler Carruth6378cf52013-11-26 04:19:30 +0000293// Implementations of the CallGraphWrapperPass class methods.
294//
295
296CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
297 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
298}
299
Eugene Zelenko48666a62017-07-24 23:16:33 +0000300CallGraphWrapperPass::~CallGraphWrapperPass() = default;
Chandler Carruth6378cf52013-11-26 04:19:30 +0000301
302void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
303 AU.setPreservesAll();
304}
305
306bool CallGraphWrapperPass::runOnModule(Module &M) {
307 // All the real work is done in the constructor for the CallGraph.
308 G.reset(new CallGraph(M));
309 return false;
310}
311
312INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
313 false, true)
314
315char CallGraphWrapperPass::ID = 0;
316
David Blaikieb61064e2014-07-19 01:05:11 +0000317void CallGraphWrapperPass::releaseMemory() { G.reset(); }
Chandler Carruth6378cf52013-11-26 04:19:30 +0000318
319void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
320 if (!G) {
321 OS << "No call graph has been built!\n";
322 return;
323 }
324
325 // Just delegate.
326 G->print(OS);
327}
328
Aaron Ballman615eb472017-10-15 14:32:27 +0000329#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Davide Italiano6f93df82015-11-23 02:58:42 +0000330LLVM_DUMP_METHOD
Craig Toppere73658d2014-04-28 04:05:08 +0000331void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
Matthias Braun8c209aa2017-01-28 02:02:38 +0000332#endif
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000333
334namespace {
Eugene Zelenko48666a62017-07-24 23:16:33 +0000335
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000336struct CallGraphPrinterLegacyPass : public ModulePass {
337 static char ID; // Pass ID, replacement for typeid
Eugene Zelenko48666a62017-07-24 23:16:33 +0000338
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000339 CallGraphPrinterLegacyPass() : ModulePass(ID) {
340 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
341 }
342
343 void getAnalysisUsage(AnalysisUsage &AU) const override {
344 AU.setPreservesAll();
345 AU.addRequiredTransitive<CallGraphWrapperPass>();
346 }
Eugene Zelenko48666a62017-07-24 23:16:33 +0000347
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000348 bool runOnModule(Module &M) override {
349 getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
350 return false;
351 }
352};
Eugene Zelenko48666a62017-07-24 23:16:33 +0000353
354} // end anonymous namespace
Chandler Carruth1ecd7402016-03-10 11:08:44 +0000355
356char CallGraphPrinterLegacyPass::ID = 0;
357
358INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
359 "Print a call graph", true, true)
360INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
361INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
362 "Print a call graph", true, true)