223464988ce20b660db44efcf2cf50732bb79456
[oota-llvm.git] / lib / Analysis / IPA / CallGraph.cpp
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 //
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/IntrinsicInst.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 using namespace llvm;
23
24 namespace {
25
26 //===----------------------------------------------------------------------===//
27 // BasicCallGraph class definition
28 //
29 class BasicCallGraph : public ModulePass, public CallGraph {
30   // Root is root of the call graph, or the external node if a 'main' function
31   // couldn't be found.
32   //
33   CallGraphNode *Root;
34
35   // ExternalCallingNode - This node has edges to all external functions and
36   // those internal functions that have their address taken.
37   CallGraphNode *ExternalCallingNode;
38
39   // CallsExternalNode - This node has edges to it from all functions making
40   // indirect calls or calling an external function.
41   CallGraphNode *CallsExternalNode;
42
43 public:
44   static char ID; // Class identification, replacement for typeinfo
45   BasicCallGraph() : ModulePass(ID), Root(0), 
46     ExternalCallingNode(0), CallsExternalNode(0) {}
47
48   // runOnModule - Compute the call graph for the specified module.
49   virtual bool runOnModule(Module &M) {
50     CallGraph::initialize(M);
51     
52     ExternalCallingNode = getOrInsertFunction(0);
53     CallsExternalNode = new CallGraphNode(0);
54     Root = 0;
55   
56     // Add every function to the call graph.
57     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
58       addToCallGraph(I);
59   
60     // If we didn't find a main function, use the external call graph node
61     if (Root == 0) Root = ExternalCallingNode;
62     
63     return false;
64   }
65
66   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67     AU.setPreservesAll();
68   }
69
70   virtual void print(raw_ostream &OS, const Module *) const {
71     OS << "CallGraph Root is: ";
72     if (Function *F = getRoot()->getFunction())
73       OS << F->getName() << "\n";
74     else {
75       OS << "<<null function: 0x" << getRoot() << ">>\n";
76     }
77     
78     CallGraph::print(OS, 0);
79   }
80
81   virtual void releaseMemory() {
82     destroy();
83   }
84   
85   /// getAdjustedAnalysisPointer - This method is used when a pass implements
86   /// an analysis interface through multiple inheritance.  If needed, it should
87   /// override this to adjust the this pointer as needed for the specified pass
88   /// info.
89   virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
90     if (PI == &CallGraph::ID)
91       return (CallGraph*)this;
92     return this;
93   }
94   
95   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
96   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
97
98   // getRoot - Return the root of the call graph, which is either main, or if
99   // main cannot be found, the external node.
100   //
101   CallGraphNode *getRoot()             { return Root; }
102   const CallGraphNode *getRoot() const { return Root; }
103
104 private:
105   //===---------------------------------------------------------------------
106   // Implementation of CallGraph construction
107   //
108
109   // addToCallGraph - Add a function to the call graph, and link the node to all
110   // of the functions that it calls.
111   //
112   void addToCallGraph(Function *F) {
113     CallGraphNode *Node = getOrInsertFunction(F);
114
115     // If this function has external linkage, anything could call it.
116     if (!F->hasLocalLinkage()) {
117       ExternalCallingNode->addCalledFunction(CallSite(), Node);
118
119       // Found the entry point?
120       if (F->getName() == "main") {
121         if (Root)    // Found multiple external mains?  Don't pick one.
122           Root = ExternalCallingNode;
123         else
124           Root = Node;          // Found a main, keep track of it!
125       }
126     }
127
128     // Loop over all of the users of the function, looking for non-call uses.
129     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I){
130       User *U = *I;
131       if ((!isa<CallInst>(U) && !isa<InvokeInst>(U))
132           || !CallSite(cast<Instruction>(U)).isCallee(I)) {
133         // Not a call, or being used as a parameter rather than as the callee.
134         ExternalCallingNode->addCalledFunction(CallSite(), Node);
135         break;
136       }
137     }
138
139     // If this function is not defined in this translation unit, it could call
140     // anything.
141     if (F->isDeclaration() && !F->isIntrinsic())
142       Node->addCalledFunction(CallSite(), CallsExternalNode);
143
144     // Look for calls by this function.
145     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
146       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
147            II != IE; ++II) {
148         CallSite CS(cast<Value>(II));
149         if (CS && !isa<DbgInfoIntrinsic>(II)) {
150           const Function *Callee = CS.getCalledFunction();
151           if (Callee)
152             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
153           else
154             Node->addCalledFunction(CS, CallsExternalNode);
155         }
156       }
157   }
158
159   //
160   // destroy - Release memory for the call graph
161   virtual void destroy() {
162     /// CallsExternalNode is not in the function map, delete it explicitly.
163     if (CallsExternalNode) {
164       CallsExternalNode->allReferencesDropped();
165       delete CallsExternalNode;
166       CallsExternalNode = 0;
167     }
168     CallGraph::destroy();
169   }
170 };
171
172 } //End anonymous namespace
173
174 INITIALIZE_ANALYSIS_GROUP(CallGraph, "Call Graph", BasicCallGraph)
175 INITIALIZE_AG_PASS(BasicCallGraph, CallGraph, "basiccg",
176                    "Basic CallGraph Construction", false, true, true)
177
178 char CallGraph::ID = 0;
179 char BasicCallGraph::ID = 0;
180
181 void CallGraph::initialize(Module &M) {
182   Mod = &M;
183 }
184
185 void CallGraph::destroy() {
186   if (FunctionMap.empty()) return;
187   
188   // Reset all node's use counts to zero before deleting them to prevent an
189   // assertion from firing.
190 #ifndef NDEBUG
191   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
192        I != E; ++I)
193     I->second->allReferencesDropped();
194 #endif
195   
196   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
197       I != E; ++I)
198     delete I->second;
199   FunctionMap.clear();
200 }
201
202 void CallGraph::print(raw_ostream &OS, Module*) const {
203   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
204     I->second->print(OS);
205 }
206 void CallGraph::dump() const {
207   print(dbgs(), 0);
208 }
209
210 //===----------------------------------------------------------------------===//
211 // Implementations of public modification methods
212 //
213
214 // removeFunctionFromModule - Unlink the function from this module, returning
215 // it.  Because this removes the function from the module, the call graph node
216 // is destroyed.  This is only valid if the function does not call any other
217 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
218 // is to dropAllReferences before calling this.
219 //
220 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
221   assert(CGN->empty() && "Cannot remove function from call "
222          "graph if it references other functions!");
223   Function *F = CGN->getFunction(); // Get the function for the call graph node
224   delete CGN;                       // Delete the call graph node for this func
225   FunctionMap.erase(F);             // Remove the call graph node from the map
226
227   Mod->getFunctionList().remove(F);
228   return F;
229 }
230
231 // getOrInsertFunction - This method is identical to calling operator[], but
232 // it will insert a new CallGraphNode for the specified function if one does
233 // not already exist.
234 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
235   CallGraphNode *&CGN = FunctionMap[F];
236   if (CGN) return CGN;
237   
238   assert((!F || F->getParent() == Mod) && "Function not in current module!");
239   return CGN = new CallGraphNode(const_cast<Function*>(F));
240 }
241
242 void CallGraphNode::print(raw_ostream &OS) const {
243   if (Function *F = getFunction())
244     OS << "Call graph node for function: '" << F->getName() << "'";
245   else
246     OS << "Call graph node <<null function>>";
247   
248   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
249
250   for (const_iterator I = begin(), E = end(); I != E; ++I) {
251     OS << "  CS<" << I->first << "> calls ";
252     if (Function *FI = I->second->getFunction())
253       OS << "function '" << FI->getName() <<"'\n";
254     else
255       OS << "external node\n";
256   }
257   OS << '\n';
258 }
259
260 void CallGraphNode::dump() const { print(dbgs()); }
261
262 /// removeCallEdgeFor - This method removes the edge in the node for the
263 /// specified call site.  Note that this method takes linear time, so it
264 /// should be used sparingly.
265 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
266   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
267     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
268     if (I->first == CS.getInstruction()) {
269       I->second->DropRef();
270       *I = CalledFunctions.back();
271       CalledFunctions.pop_back();
272       return;
273     }
274   }
275 }
276
277
278 // removeAnyCallEdgeTo - This method removes any call edges from this node to
279 // the specified callee function.  This takes more time to execute than
280 // removeCallEdgeTo, so it should not be used unless necessary.
281 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
282   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
283     if (CalledFunctions[i].second == Callee) {
284       Callee->DropRef();
285       CalledFunctions[i] = CalledFunctions.back();
286       CalledFunctions.pop_back();
287       --i; --e;
288     }
289 }
290
291 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
292 /// from this node to the specified callee function.
293 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
294   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
295     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
296     CallRecord &CR = *I;
297     if (CR.second == Callee && CR.first == 0) {
298       Callee->DropRef();
299       *I = CalledFunctions.back();
300       CalledFunctions.pop_back();
301       return;
302     }
303   }
304 }
305
306 /// replaceCallEdge - This method replaces the edge in the node for the
307 /// specified call site with a new one.  Note that this method takes linear
308 /// time, so it should be used sparingly.
309 void CallGraphNode::replaceCallEdge(CallSite CS,
310                                     CallSite NewCS, CallGraphNode *NewNode){
311   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
312     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
313     if (I->first == CS.getInstruction()) {
314       I->second->DropRef();
315       I->first = NewCS.getInstruction();
316       I->second = NewNode;
317       NewNode->AddRef();
318       return;
319     }
320   }
321 }
322
323 // Enuse that users of CallGraph.h also link with this file
324 DEFINING_FILE_FOR(CallGraph)