LLVM  9.0.0svn
CallGraph.cpp
Go to the documentation of this file.
1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/Config/llvm-config.h"
13 #include "llvm/IR/CallSite.h"
14 #include "llvm/IR/Module.h"
15 #include "llvm/IR/Function.h"
16 #include "llvm/IR/Intrinsics.h"
17 #include "llvm/IR/PassManager.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
22 #include <algorithm>
23 #include <cassert>
24 
25 using namespace llvm;
26 
27 //===----------------------------------------------------------------------===//
28 // Implementations of the CallGraph class methods.
29 //
30 
32  : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)),
33  CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
34  // Add every function to the call graph.
35  for (Function &F : M)
36  addToCallGraph(&F);
37 }
38 
40  : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)),
41  ExternalCallingNode(Arg.ExternalCallingNode),
42  CallsExternalNode(std::move(Arg.CallsExternalNode)) {
43  Arg.FunctionMap.clear();
44  Arg.ExternalCallingNode = nullptr;
45 }
46 
48  // CallsExternalNode is not in the function map, delete it explicitly.
49  if (CallsExternalNode)
50  CallsExternalNode->allReferencesDropped();
51 
52 // Reset all node's use counts to zero before deleting them to prevent an
53 // assertion from firing.
54 #ifndef NDEBUG
55  for (auto &I : FunctionMap)
56  I.second->allReferencesDropped();
57 #endif
58 }
59 
60 void CallGraph::addToCallGraph(Function *F) {
62 
63  // If this function has external linkage or has its address taken, anything
64  // could call it.
65  if (!F->hasLocalLinkage() || F->hasAddressTaken())
66  ExternalCallingNode->addCalledFunction(CallSite(), Node);
67 
68  // If this function is not defined in this translation unit, it could call
69  // anything.
70  if (F->isDeclaration() && !F->isIntrinsic())
71  Node->addCalledFunction(CallSite(), CallsExternalNode.get());
72 
73  // Look for calls by this function.
74  for (BasicBlock &BB : *F)
75  for (Instruction &I : BB) {
76  if (auto CS = CallSite(&I)) {
77  const Function *Callee = CS.getCalledFunction();
78  if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
79  // Indirect calls of intrinsics are not allowed so no need to check.
80  // We can be more precise here by using TargetArg returned by
81  // Intrinsic::isLeaf.
82  Node->addCalledFunction(CS, CallsExternalNode.get());
83  else if (!Callee->isIntrinsic())
84  Node->addCalledFunction(CS, getOrInsertFunction(Callee));
85  }
86  }
87 }
88 
89 void CallGraph::print(raw_ostream &OS) const {
90  // Print in a deterministic order by sorting CallGraphNodes by name. We do
91  // this here to avoid slowing down the non-printing fast path.
92 
94  Nodes.reserve(FunctionMap.size());
95 
96  for (const auto &I : *this)
97  Nodes.push_back(I.second.get());
98 
99  llvm::sort(Nodes, [](CallGraphNode *LHS, CallGraphNode *RHS) {
100  if (Function *LF = LHS->getFunction())
101  if (Function *RF = RHS->getFunction())
102  return LF->getName() < RF->getName();
103 
104  return RHS->getFunction() != nullptr;
105  });
106 
107  for (CallGraphNode *CN : Nodes)
108  CN->print(OS);
109 }
110 
111 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
113 #endif
114 
115 // removeFunctionFromModule - Unlink the function from this module, returning
116 // it. Because this removes the function from the module, the call graph node
117 // is destroyed. This is only valid if the function does not call any other
118 // functions (ie, there are no edges in it's CGN). The easiest way to do this
119 // is to dropAllReferences before calling this.
120 //
122  assert(CGN->empty() && "Cannot remove function from call "
123  "graph if it references other functions!");
124  Function *F = CGN->getFunction(); // Get the function for the call graph node
125  FunctionMap.erase(F); // Remove the call graph node from the map
126 
127  M.getFunctionList().remove(F);
128  return F;
129 }
130 
131 /// spliceFunction - Replace the function represented by this node by another.
132 /// This does not rescan the body of the function, so it is suitable when
133 /// splicing the body of the old function to the new while also updating all
134 /// callers from old to new.
135 void CallGraph::spliceFunction(const Function *From, const Function *To) {
136  assert(FunctionMap.count(From) && "No CallGraphNode for function!");
137  assert(!FunctionMap.count(To) &&
138  "Pointing CallGraphNode at a function that already exists");
139  FunctionMapTy::iterator I = FunctionMap.find(From);
140  I->second->F = const_cast<Function*>(To);
141  FunctionMap[To] = std::move(I->second);
142  FunctionMap.erase(I);
143 }
144 
145 // getOrInsertFunction - This method is identical to calling operator[], but
146 // it will insert a new CallGraphNode for the specified function if one does
147 // not already exist.
149  auto &CGN = FunctionMap[F];
150  if (CGN)
151  return CGN.get();
152 
153  assert((!F || F->getParent() == &M) && "Function not in current module!");
154  CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
155  return CGN.get();
156 }
157 
158 //===----------------------------------------------------------------------===//
159 // Implementations of the CallGraphNode class methods.
160 //
161 
163  if (Function *F = getFunction())
164  OS << "Call graph node for function: '" << F->getName() << "'";
165  else
166  OS << "Call graph node <<null function>>";
167 
168  OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
169 
170  for (const auto &I : *this) {
171  OS << " CS<" << I.first << "> calls ";
172  if (Function *FI = I.second->getFunction())
173  OS << "function '" << FI->getName() <<"'\n";
174  else
175  OS << "external node\n";
176  }
177  OS << '\n';
178 }
179 
180 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
182 #endif
183 
184 /// removeCallEdgeFor - This method removes the edge in the node for the
185 /// specified call site. Note that this method takes linear time, so it
186 /// should be used sparingly.
188  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
189  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
190  if (I->first == CS.getInstruction()) {
191  I->second->DropRef();
192  *I = CalledFunctions.back();
193  CalledFunctions.pop_back();
194  return;
195  }
196  }
197 }
198 
199 // removeAnyCallEdgeTo - This method removes any call edges from this node to
200 // the specified callee function. This takes more time to execute than
201 // removeCallEdgeTo, so it should not be used unless necessary.
203  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
204  if (CalledFunctions[i].second == Callee) {
205  Callee->DropRef();
206  CalledFunctions[i] = CalledFunctions.back();
207  CalledFunctions.pop_back();
208  --i; --e;
209  }
210 }
211 
212 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
213 /// from this node to the specified callee function.
215  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
216  assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
217  CallRecord &CR = *I;
218  if (CR.second == Callee && CR.first == nullptr) {
219  Callee->DropRef();
220  *I = CalledFunctions.back();
221  CalledFunctions.pop_back();
222  return;
223  }
224  }
225 }
226 
227 /// replaceCallEdge - This method replaces the edge in the node for the
228 /// specified call site with a new one. Note that this method takes linear
229 /// time, so it should be used sparingly.
231  CallSite NewCS, CallGraphNode *NewNode){
232  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
233  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
234  if (I->first == CS.getInstruction()) {
235  I->second->DropRef();
236  I->first = NewCS.getInstruction();
237  I->second = NewNode;
238  NewNode->AddRef();
239  return;
240  }
241  }
242 }
243 
244 // Provide an explicit template instantiation for the static ID.
245 AnalysisKey CallGraphAnalysis::Key;
246 
248  ModuleAnalysisManager &AM) {
249  AM.getResult<CallGraphAnalysis>(M).print(OS);
250  return PreservedAnalyses::all();
251 }
252 
253 //===----------------------------------------------------------------------===//
254 // Out-of-line definitions of CallGraphAnalysis class members.
255 //
256 
257 //===----------------------------------------------------------------------===//
258 // Implementations of the CallGraphWrapperPass class methods.
259 //
260 
263 }
264 
266 
268  AU.setPreservesAll();
269 }
270 
272  // All the real work is done in the constructor for the CallGraph.
273  G.reset(new CallGraph(M));
274  return false;
275 }
276 
277 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
278  false, true)
279 
280 char CallGraphWrapperPass::ID = 0;
281 
282 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
283 
285  if (!G) {
286  OS << "No call graph has been built!\n";
287  return;
288  }
289 
290  // Just delegate.
291  G->print(OS);
292 }
293 
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
296 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
297 #endif
298 
299 namespace {
300 
301 struct CallGraphPrinterLegacyPass : public ModulePass {
302  static char ID; // Pass ID, replacement for typeid
303 
304  CallGraphPrinterLegacyPass() : ModulePass(ID) {
306  }
307 
308  void getAnalysisUsage(AnalysisUsage &AU) const override {
309  AU.setPreservesAll();
311  }
312 
313  bool runOnModule(Module &M) override {
314  getAnalysis<CallGraphWrapperPass>().print(errs(), &M);
315  return false;
316  }
317 };
318 
319 } // end anonymous namespace
320 
322 
323 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph",
324  "Print a call graph", true, true)
326 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph",
327  "Print a call graph", true, true)
bool isIntrinsic() const
isIntrinsic - Returns true if the function&#39;s name starts with "llvm.".
Definition: Function.h:198
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasLocalLinkage() const
Definition: GlobalValue.h:435
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:769
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:464
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
unsigned second
F(f)
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1348
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
Definition: CallGraph.cpp:271
void reserve(size_type N)
Definition: SmallVector.h:369
A node in the call graph for a module.
Definition: CallGraph.h:164
void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function...
Definition: CallGraph.cpp:214
void addCalledFunction(CallSite CS, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:232
print callgraph
Definition: CallGraph.cpp:326
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Definition: BitVector.h:937
void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode)
Replaces the edge in the node for the specified call site with a new one.
Definition: CallGraph.cpp:230
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:162
ModulePass(char &pid)
Definition: Pass.h:226
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
Definition: CallGraph.cpp:121
InstrTy * getInstruction() const
Definition: CallSite.h:96
void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:181
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
static Function * getFunction(Constant *C)
Definition: Evaluator.cpp:220
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void initializeCallGraphPrinterLegacyPassPass(PassRegistry &)
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Removes all call edges from this node to the specified callee function.
Definition: CallGraph.cpp:202
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition: CallGraph.h:323
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:1001
const FunctionListType & getFunctionList() const
Get the Module&#39;s list of functions (constant).
Definition: Module.h:533
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void initializeCallGraphWrapperPassPass(PassRegistry &)
Represent the analysis usage information of a pass.
CallGraph(Module &M)
Definition: CallGraph.cpp:31
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:33
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1115
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:187
BlockVerifier::State From
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
Module.h This file contains the declarations for the Module class.
bool empty() const
Definition: CallGraph.h:193
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
Definition: CallGraph.cpp:247
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:193
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
amdgpu Simplify well known AMD library false FunctionCallee Callee
INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph", "Print a call graph", true, true) INITIALIZE_PASS_END(CallGraphPrinterLegacyPass
void setPreservesAll()
Set by analyses that do not transform their input at all.
An analysis pass to compute the CallGraph for a Module.
Definition: CallGraph.h:291
pointer remove(iterator &IT)
Definition: ilist.h:249
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:73
print Print a call true
Definition: CallGraph.cpp:326
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
std::pair< WeakTrackingVH, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called...
Definition: CallGraph.h:168
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:224
AnalysisUsage & addRequiredTransitive()
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:205
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
Definition: Function.cpp:1257
print Print a call graph
Definition: CallGraph.cpp:326
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:565
CallGraphNode * getOrInsertFunction(const Function *F)
Similar to operator[], but this will insert a new CallGraphNode for F if one does not already exist...
Definition: CallGraph.cpp:148
void removeCallEdgeFor(CallSite CS)
Removes the edge in the node for the specified call site.
Definition: CallGraph.cpp:187
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
A container for analyses that lazily runs them and caches their results.
void dump() const
Definition: CallGraph.cpp:112
This header defines various interfaces for pass management in LLVM.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:267
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:284
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:89