LLVM  3.7.0
CallGraph.cpp
Go to the documentation of this file.
1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "llvm/IR/CallSite.h"
12 #include "llvm/IR/Instructions.h"
13 #include "llvm/IR/IntrinsicInst.h"
14 #include "llvm/IR/Module.h"
15 #include "llvm/Support/Debug.h"
17 using namespace llvm;
18 
19 //===----------------------------------------------------------------------===//
20 // Implementations of the CallGraph class methods.
21 //
22 
24  : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
25  CallsExternalNode(new CallGraphNode(nullptr)) {
26  // Add every function to the call graph.
27  for (Function &F : M)
28  addToCallGraph(&F);
29 
30  // If we didn't find a main function, use the external call graph node
31  if (!Root)
32  Root = ExternalCallingNode;
33 }
34 
36  // CallsExternalNode is not in the function map, delete it explicitly.
37  CallsExternalNode->allReferencesDropped();
38  delete CallsExternalNode;
39 
40 // Reset all node's use counts to zero before deleting them to prevent an
41 // assertion from firing.
42 #ifndef NDEBUG
43  for (auto &I : FunctionMap)
44  I.second->allReferencesDropped();
45 #endif
46  for (auto &I : FunctionMap)
47  delete I.second;
48 }
49 
50 void CallGraph::addToCallGraph(Function *F) {
52 
53  // If this function has external linkage, anything could call it.
54  if (!F->hasLocalLinkage()) {
55  ExternalCallingNode->addCalledFunction(CallSite(), Node);
56 
57  // Found the entry point?
58  if (F->getName() == "main") {
59  if (Root) // Found multiple external mains? Don't pick one.
60  Root = ExternalCallingNode;
61  else
62  Root = Node; // Found a main, keep track of it!
63  }
64  }
65 
66  // If this function has its address taken, anything could call it.
67  if (F->hasAddressTaken())
68  ExternalCallingNode->addCalledFunction(CallSite(), Node);
69 
70  // If this function is not defined in this translation unit, it could call
71  // anything.
72  if (F->isDeclaration() && !F->isIntrinsic())
73  Node->addCalledFunction(CallSite(), CallsExternalNode);
74 
75  // Look for calls by this function.
76  for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
77  for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
78  ++II) {
79  CallSite CS(cast<Value>(II));
80  if (CS) {
81  const Function *Callee = CS.getCalledFunction();
82  if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
83  // Indirect calls of intrinsics are not allowed so no need to check.
84  // We can be more precise here by using TargetArg returned by
85  // Intrinsic::isLeaf.
86  Node->addCalledFunction(CS, CallsExternalNode);
87  else if (!Callee->isIntrinsic())
89  }
90  }
91 }
92 
93 void CallGraph::print(raw_ostream &OS) const {
94  OS << "CallGraph Root is: ";
95  if (Function *F = Root->getFunction())
96  OS << F->getName() << "\n";
97  else {
98  OS << "<<null function: 0x" << Root << ">>\n";
99  }
100 
101  // Print in a deterministic order by sorting CallGraphNodes by name. We do
102  // this here to avoid slowing down the non-printing fast path.
103 
105  Nodes.reserve(FunctionMap.size());
106 
107  for (auto I = begin(), E = end(); I != E; ++I)
108  Nodes.push_back(I->second);
109 
110  std::sort(Nodes.begin(), Nodes.end(),
111  [](CallGraphNode *LHS, CallGraphNode *RHS) {
112  if (Function *LF = LHS->getFunction())
113  if (Function *RF = RHS->getFunction())
114  return LF->getName() < RF->getName();
115 
116  return RHS->getFunction() != nullptr;
117  });
118 
119  for (CallGraphNode *CN : Nodes)
120  CN->print(OS);
121 }
122 
123 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
124 void CallGraph::dump() const { print(dbgs()); }
125 #endif
126 
127 // removeFunctionFromModule - Unlink the function from this module, returning
128 // it. Because this removes the function from the module, the call graph node
129 // is destroyed. This is only valid if the function does not call any other
130 // functions (ie, there are no edges in it's CGN). The easiest way to do this
131 // is to dropAllReferences before calling this.
132 //
134  assert(CGN->empty() && "Cannot remove function from call "
135  "graph if it references other functions!");
136  Function *F = CGN->getFunction(); // Get the function for the call graph node
137  delete CGN; // Delete the call graph node for this func
138  FunctionMap.erase(F); // Remove the call graph node from the map
139 
140  M.getFunctionList().remove(F);
141  return F;
142 }
143 
144 /// spliceFunction - Replace the function represented by this node by another.
145 /// This does not rescan the body of the function, so it is suitable when
146 /// splicing the body of the old function to the new while also updating all
147 /// callers from old to new.
148 ///
149 void CallGraph::spliceFunction(const Function *From, const Function *To) {
150  assert(FunctionMap.count(From) && "No CallGraphNode for function!");
151  assert(!FunctionMap.count(To) &&
152  "Pointing CallGraphNode at a function that already exists");
153  FunctionMapTy::iterator I = FunctionMap.find(From);
154  I->second->F = const_cast<Function*>(To);
155  FunctionMap[To] = I->second;
156  FunctionMap.erase(I);
157 }
158 
159 // getOrInsertFunction - This method is identical to calling operator[], but
160 // it will insert a new CallGraphNode for the specified function if one does
161 // not already exist.
163  CallGraphNode *&CGN = FunctionMap[F];
164  if (CGN)
165  return CGN;
166 
167  assert((!F || F->getParent() == &M) && "Function not in current module!");
168  return CGN = new CallGraphNode(const_cast<Function*>(F));
169 }
170 
171 //===----------------------------------------------------------------------===//
172 // Implementations of the CallGraphNode class methods.
173 //
174 
176  if (Function *F = getFunction())
177  OS << "Call graph node for function: '" << F->getName() << "'";
178  else
179  OS << "Call graph node <<null function>>";
180 
181  OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n';
182 
183  for (const_iterator I = begin(), E = end(); I != E; ++I) {
184  OS << " CS<" << I->first << "> calls ";
185  if (Function *FI = I->second->getFunction())
186  OS << "function '" << FI->getName() <<"'\n";
187  else
188  OS << "external node\n";
189  }
190  OS << '\n';
191 }
192 
193 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
194 void CallGraphNode::dump() const { print(dbgs()); }
195 #endif
196 
197 /// removeCallEdgeFor - This method removes the edge in the node for the
198 /// specified call site. Note that this method takes linear time, so it
199 /// should be used sparingly.
201  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
202  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
203  if (I->first == CS.getInstruction()) {
204  I->second->DropRef();
205  *I = CalledFunctions.back();
206  CalledFunctions.pop_back();
207  return;
208  }
209  }
210 }
211 
212 // removeAnyCallEdgeTo - This method removes any call edges from this node to
213 // the specified callee function. This takes more time to execute than
214 // removeCallEdgeTo, so it should not be used unless necessary.
216  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
217  if (CalledFunctions[i].second == Callee) {
218  Callee->DropRef();
219  CalledFunctions[i] = CalledFunctions.back();
220  CalledFunctions.pop_back();
221  --i; --e;
222  }
223 }
224 
225 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
226 /// from this node to the specified callee function.
228  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
229  assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
230  CallRecord &CR = *I;
231  if (CR.second == Callee && CR.first == nullptr) {
232  Callee->DropRef();
233  *I = CalledFunctions.back();
234  CalledFunctions.pop_back();
235  return;
236  }
237  }
238 }
239 
240 /// replaceCallEdge - This method replaces the edge in the node for the
241 /// specified call site with a new one. Note that this method takes linear
242 /// time, so it should be used sparingly.
244  CallSite NewCS, CallGraphNode *NewNode){
245  for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
246  assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
247  if (I->first == CS.getInstruction()) {
248  I->second->DropRef();
249  I->first = NewCS.getInstruction();
250  I->second = NewNode;
251  NewNode->AddRef();
252  return;
253  }
254  }
255 }
256 
257 //===----------------------------------------------------------------------===//
258 // Out-of-line definitions of CallGraphAnalysis class members.
259 //
260 
261 char CallGraphAnalysis::PassID;
262 
263 //===----------------------------------------------------------------------===//
264 // Implementations of the CallGraphWrapperPass class methods.
265 //
266 
269 }
270 
272 
274  AU.setPreservesAll();
275 }
276 
278  // All the real work is done in the constructor for the CallGraph.
279  G.reset(new CallGraph(M));
280  return false;
281 }
282 
283 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
284  false, true)
285 
286 char CallGraphWrapperPass::ID = 0;
287 
288 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
289 
291  if (!G) {
292  OS << "No call graph has been built!\n";
293  return;
294  }
295 
296  // Just delegate.
297  G->print(OS);
298 }
299 
300 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
301 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }
302 #endif
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
iterator end()
Definition: Function.h:459
InstrTy * getInstruction() const
Definition: CallSite.h:82
bool isIntrinsic() const
Definition: Function.h:160
bool empty() const
Definition: CallGraph.h:192
F(f)
bool runOnModule(Module &M) override
runOnModule - Virtual method overriden by subclasses to process the module being operated on...
Definition: CallGraph.cpp:277
void reserve(size_type N)
Definition: SmallVector.h:401
A node in the call graph for a module.
Definition: CallGraph.h:166
void dump() const
Print out this call graph node.
Definition: CallGraph.cpp:194
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
Function * getFunction() const
Returns the function that this call graph node represents.
Definition: CallGraph.h:186
unsigned getNumReferences() const
Returns the number of other CallGraphNodes in this CallGraph that reference this node in their callee...
Definition: CallGraph.h:197
void removeOneAbstractEdgeTo(CallGraphNode *Callee)
Removes one edge associated with a null callsite from this node to the specified callee function...
Definition: CallGraph.cpp:227
void addCalledFunction(CallSite CS, CallGraphNode *M)
Adds a function to the list of functions called by this one.
Definition: CallGraph.h:231
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:93
iterator end()
Definition: CallGraph.h:189
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:243
Function * removeFunctionFromModule(CallGraphNode *CGN)
Unlink the function from this module, returning it.
Definition: CallGraph.cpp:133
#define G(x, y, z)
Definition: MD5.cpp:52
This file provides interfaces used to build and manipulate a call graph, which is a very useful tool ...
iterator begin()
Definition: Function.h:457
void removeAnyCallEdgeTo(CallGraphNode *Callee)
Removes all call edges from this node to the specified callee function.
Definition: CallGraph.cpp:215
The ModulePass which wraps up a CallGraph and the logic to build it.
Definition: CallGraph.h:316
bool isLeaf(ID id)
Returns true if the intrinsic is a leaf, i.e.
Definition: Function.cpp:849
void initializeCallGraphWrapperPassPass(PassRegistry &)
Represent the analysis usage information of a pass.
CallGraph(Module &M)
Definition: CallGraph.cpp:23
~CallGraphWrapperPass() override
Definition: CallGraph.cpp:271
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
Definition: Module.h:519
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Intrinsic::ID getIntrinsicID() const LLVM_READONLY
getIntrinsicID - This method returns the ID number of the specified function, or Intrinsic::not_intri...
Definition: Function.h:159
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
void setPreservesAll()
Set by analyses that do not transform their input at all.
void print(raw_ostream &OS) const
Definition: CallGraph.cpp:175
The basic data container for the call graph of a Module of IR.
Definition: CallGraph.h:75
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:886
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
#define I(x, y, z)
Definition: MD5.cpp:54
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:236
iterator end()
Definition: CallGraph.h:120
bool hasLocalLinkage() const
Definition: GlobalValue.h:280
std::pair< WeakVH, CallGraphNode * > CallRecord
A pair of the calling instruction (a call or invoke) and the call graph node being called...
Definition: CallGraph.h:170
std::vector< CallRecord >::const_iterator const_iterator
Definition: CallGraph.h:183
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:365
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:162
void removeCallEdgeFor(CallSite CS)
Removes the edge in the node for the specified call site.
Definition: CallGraph.cpp:200
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
iterator begin()
Definition: CallGraph.h:188
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: CallGraph.cpp:273
void dump() const
Definition: CallGraph.cpp:124
void print(raw_ostream &o, const Module *) const override
print - Print out the internal state of the pass.
Definition: CallGraph.cpp:290
NodeTy * remove(iterator &IT)
Definition: ilist.h:435
iterator begin()
Definition: CallGraph.h:119