CallGraph.cpp revision 192913e281a0e9b97275fa1b84da96b02397323e
1//===- CallGraph.cpp - Build a Module's call graph ------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the CallGraph class and provides the BasicCallGraph
11// default implementation.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/CallGraph.h"
16#include "llvm/Module.h"
17#include "llvm/Instructions.h"
18#include "llvm/Support/CallSite.h"
19#include <iostream>
20using namespace llvm;
21
22void llvm::BasicCallGraphStub() {}
23
24static bool isOnlyADirectCall(Function *F, CallSite CS) {
25  if (!CS.getInstruction()) return false;
26  for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
27    if (*I == F) return false;
28  return true;
29}
30
31namespace {
32
33//===----------------------------------------------------------------------===//
34// BasicCallGraph class definition
35//
36class BasicCallGraph : public CallGraph, public ModulePass {
37  // Root is root of the call graph, or the external node if a 'main' function
38  // couldn't be found.
39  //
40  CallGraphNode *Root;
41
42  // ExternalCallingNode - This node has edges to all external functions and
43  // those internal functions that have their address taken.
44  CallGraphNode *ExternalCallingNode;
45
46  // CallsExternalNode - This node has edges to it from all functions making
47  // indirect calls or calling an external function.
48  CallGraphNode *CallsExternalNode;
49
50public:
51  BasicCallGraph() : Root(0), ExternalCallingNode(0), CallsExternalNode(0) {}
52  ~BasicCallGraph() { destroy(); }
53
54  // runOnModule - Compute the call graph for the specified module.
55  virtual bool runOnModule(Module &M) {
56    destroy();
57    CallGraph::initialize(M);
58
59    ExternalCallingNode = getOrInsertFunction(0);
60    CallsExternalNode = new CallGraphNode(0);
61    Root = 0;
62
63    // Add every function to the call graph...
64    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
65      addToCallGraph(I);
66
67    // If we didn't find a main function, use the external call graph node
68    if (Root == 0) Root = ExternalCallingNode;
69
70    return false;
71  }
72
73  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74    AU.setPreservesAll();
75  }
76
77  virtual void print(std::ostream &o, const Module *M) const {
78    o << "CallGraph Root is: ";
79    if (Function *F = getRoot()->getFunction())
80      o << F->getName() << "\n";
81    else
82      o << "<<null function: 0x" << getRoot() << ">>\n";
83
84    CallGraph::print(o, M);
85  }
86
87  virtual void releaseMemory() {
88    destroy();
89  }
90
91  /// dump - Print out this call graph.
92  ///
93  inline void dump() const {
94    print(std::cerr, Mod);
95  }
96
97  CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
98  CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
99
100  // getRoot - Return the root of the call graph, which is either main, or if
101  // main cannot be found, the external node.
102  //
103  CallGraphNode *getRoot()             { return Root; }
104  const CallGraphNode *getRoot() const { return Root; }
105
106private:
107  //===---------------------------------------------------------------------
108  // Implementation of CallGraph construction
109  //
110
111  // addToCallGraph - Add a function to the call graph, and link the node to all
112  // of the functions that it calls.
113  //
114  void addToCallGraph(Function *F) {
115    CallGraphNode *Node = getOrInsertFunction(F);
116
117    // If this function has external linkage, anything could call it...
118    if (!F->hasInternalLinkage()) {
119      ExternalCallingNode->addCalledFunction(Node);
120
121      // Found the entry point?
122      if (F->getName() == "main") {
123        if (Root)    // Found multiple external mains?  Don't pick one.
124          Root = ExternalCallingNode;
125        else
126          Root = Node;          // Found a main, keep track of it!
127      }
128    }
129
130    // If this function is not defined in this translation unit, it could call
131    // anything.
132    if (F->isExternal() && !F->getIntrinsicID())
133      Node->addCalledFunction(CallsExternalNode);
134
135    // Loop over all of the users of the function... looking for callers...
136    //
137    bool isUsedExternally = false;
138    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I){
139      if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
140        if (isOnlyADirectCall(F, CallSite::get(Inst)))
141          getOrInsertFunction(Inst->getParent()->getParent())
142              ->addCalledFunction(Node);
143        else
144          isUsedExternally = true;
145      } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*I)) {
146        for (Value::use_iterator I = GV->use_begin(), E = GV->use_end();
147             I != E; ++I)
148          if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
149          if (isOnlyADirectCall(F, CallSite::get(Inst)))
150            getOrInsertFunction(Inst->getParent()->getParent())
151                ->addCalledFunction(Node);
152          else
153            isUsedExternally = true;
154          } else {
155            isUsedExternally = true;
156          }
157      } else {                        // Can't classify the user!
158        isUsedExternally = true;
159      }
160    }
161    if (isUsedExternally)
162      ExternalCallingNode->addCalledFunction(Node);
163
164  // Look for an indirect function call...
165    for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
166      for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
167           II != IE; ++II) {
168      CallSite CS = CallSite::get(II);
169      if (CS.getInstruction() && !CS.getCalledFunction())
170        Node->addCalledFunction(CallsExternalNode);
171      }
172  }
173
174  //
175  // destroy - Release memory for the call graph
176  virtual void destroy() {
177    if (!CallsExternalNode) {
178      delete CallsExternalNode;
179      CallsExternalNode = 0;
180    }
181  }
182};
183
184RegisterAnalysisGroup<CallGraph> X("Call Graph");
185RegisterOpt<BasicCallGraph> Y("basiccg", "Basic CallGraph Construction");
186RegisterAnalysisGroup<CallGraph, BasicCallGraph, true> Z;
187
188} //End anonymous namespace
189
190void CallGraph::initialize(Module &M) {
191  destroy();
192  Mod = &M;
193}
194
195void CallGraph::destroy() {
196  if(!FunctionMap.size()) {
197    for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
198        I != E; ++I)
199      delete I->second;
200    FunctionMap.clear();
201  }
202}
203
204void CallGraph::print(std::ostream &OS, const Module *M) const {
205  for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
206    I->second->print(OS);
207}
208
209void CallGraph::dump() const {
210  print(std::cerr, 0);
211}
212
213//===----------------------------------------------------------------------===//
214// Implementations of public modification methods
215//
216
217// removeFunctionFromModule - Unlink the function from this module, returning
218// it.  Because this removes the function from the module, the call graph node
219// is destroyed.  This is only valid if the function does not call any other
220// functions (ie, there are no edges in it's CGN).  The easiest way to do this
221// is to dropAllReferences before calling this.
222//
223Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
224  assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
225         "graph if it references other functions!");
226  Function *F = CGN->getFunction(); // Get the function for the call graph node
227  delete CGN;                       // Delete the call graph node for this func
228  FunctionMap.erase(F);             // Remove the call graph node from the map
229
230  Mod->getFunctionList().remove(F);
231  return F;
232}
233
234// changeFunction - This method changes the function associated with this
235// CallGraphNode, for use by transformations that need to change the prototype
236// of a Function (thus they must create a new Function and move the old code
237// over).
238void CallGraph::changeFunction(Function *OldF, Function *NewF) {
239  iterator I = FunctionMap.find(OldF);
240  CallGraphNode *&New = FunctionMap[NewF];
241  assert(I != FunctionMap.end() && I->second && !New &&
242         "OldF didn't exist in CG or NewF already does!");
243  New = I->second;
244  New->F = NewF;
245  FunctionMap.erase(I);
246}
247
248// getOrInsertFunction - This method is identical to calling operator[], but
249// it will insert a new CallGraphNode for the specified function if one does
250// not already exist.
251CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
252  CallGraphNode *&CGN = FunctionMap[F];
253  if (CGN) return CGN;
254
255  assert((!F || F->getParent() == Mod) && "Function not in current module!");
256  return CGN = new CallGraphNode(const_cast<Function*>(F));
257}
258
259
260
261int CallGraph::stub; // to ensure linkage of this file.
262
263void CallGraphNode::print(std::ostream &OS) const {
264  if (Function *F = getFunction())
265    OS << "Call graph node for function: '" << F->getName() <<"'\n";
266  else
267    OS << "Call graph node <<null function: 0x" << this << ">>:\n";
268
269  for (const_iterator I = begin(), E = end(); I != E; ++I)
270    if ((*I)->getFunction())
271      OS << "  Calls function '" << (*I)->getFunction()->getName() << "'\n";
272  else
273    OS << "  Calls external node\n";
274  OS << "\n";
275}
276
277void CallGraphNode::dump() const { print(std::cerr); }
278
279void CallGraphNode::removeCallEdgeTo(CallGraphNode *Callee) {
280  for (unsigned i = CalledFunctions.size(); ; --i) {
281    assert(i && "Cannot find callee to remove!");
282    if (CalledFunctions[i-1] == Callee) {
283      CalledFunctions.erase(CalledFunctions.begin()+i-1);
284      return;
285    }
286  }
287}
288
289// removeAnyCallEdgeTo - This method removes any call edges from this node to
290// the specified callee function.  This takes more time to execute than
291// removeCallEdgeTo, so it should not be used unless necessary.
292void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
293  for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
294    if (CalledFunctions[i] == Callee) {
295      CalledFunctions[i] = CalledFunctions.back();
296      CalledFunctions.pop_back();
297      --i; --e;
298    }
299}
300