6c18d0d1a6442d6bee39534d4a4998d79f798eda
[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/IR/Instructions.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/Module.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       initializeBasicCallGraphPass(*PassRegistry::getPassRegistry());
48     }
49   ~BasicCallGraph() {
50     destroy();
51   }
52
53   // runOnModule - Compute the call graph for the specified module.
54   virtual bool runOnModule(Module &M) {
55     CallGraph::initialize(M);
56     
57     ExternalCallingNode = getOrInsertFunction(0);
58     assert(!CallsExternalNode);
59     CallsExternalNode = new CallGraphNode(0);
60     Root = 0;
61   
62     // Add every function to the call graph.
63     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
64       addToCallGraph(I);
65   
66     // If we didn't find a main function, use the external call graph node
67     if (Root == 0) Root = ExternalCallingNode;
68     
69     return false;
70   }
71
72   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73     AU.setPreservesAll();
74   }
75
76   virtual void print(raw_ostream &OS, const Module *) const {
77     OS << "CallGraph Root is: ";
78     if (Function *F = getRoot()->getFunction())
79       OS << F->getName() << "\n";
80     else {
81       OS << "<<null function: 0x" << getRoot() << ">>\n";
82     }
83     
84     CallGraph::print(OS, 0);
85   }
86
87   virtual void releaseMemory() {
88     destroy();
89   }
90   
91   /// getAdjustedAnalysisPointer - This method is used when a pass implements
92   /// an analysis interface through multiple inheritance.  If needed, it should
93   /// override this to adjust the this pointer as needed for the specified pass
94   /// info.
95   virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
96     if (PI == &CallGraph::ID)
97       return (CallGraph*)this;
98     return this;
99   }
100   
101   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
102   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
103
104   // getRoot - Return the root of the call graph, which is either main, or if
105   // main cannot be found, the external node.
106   //
107   CallGraphNode *getRoot()             { return Root; }
108   const CallGraphNode *getRoot() const { return Root; }
109
110 private:
111   //===---------------------------------------------------------------------
112   // Implementation of CallGraph construction
113   //
114
115   // addToCallGraph - Add a function to the call graph, and link the node to all
116   // of the functions that it calls.
117   //
118   void addToCallGraph(Function *F) {
119     CallGraphNode *Node = getOrInsertFunction(F);
120
121     // If this function has external linkage, anything could call it.
122     if (!F->hasLocalLinkage()) {
123       ExternalCallingNode->addCalledFunction(CallSite(), Node);
124
125       // Found the entry point?
126       if (F->getName() == "main") {
127         if (Root)    // Found multiple external mains?  Don't pick one.
128           Root = ExternalCallingNode;
129         else
130           Root = Node;          // Found a main, keep track of it!
131       }
132     }
133
134     // If this function has its address taken, anything could call it.
135     if (F->hasAddressTaken())
136       ExternalCallingNode->addCalledFunction(CallSite(), Node);
137
138     // If this function is not defined in this translation unit, it could call
139     // anything.
140     if (F->isDeclaration() && !F->isIntrinsic())
141       Node->addCalledFunction(CallSite(), CallsExternalNode);
142
143     // Look for calls by this function.
144     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
145       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
146            II != IE; ++II) {
147         CallSite CS(cast<Value>(II));
148         if (CS) {
149           const Function *Callee = CS.getCalledFunction();
150           if (!Callee)
151             // Indirect calls of intrinsics are not allowed so no need to check.
152             Node->addCalledFunction(CS, CallsExternalNode);
153           else if (!Callee->isIntrinsic())
154             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
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 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
207 void CallGraph::dump() const {
208   print(dbgs(), 0);
209 }
210 #endif
211
212 //===----------------------------------------------------------------------===//
213 // Implementations of public modification methods
214 //
215
216 // removeFunctionFromModule - Unlink the function from this module, returning
217 // it.  Because this removes the function from the module, the call graph node
218 // is destroyed.  This is only valid if the function does not call any other
219 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
220 // is to dropAllReferences before calling this.
221 //
222 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
223   assert(CGN->empty() && "Cannot remove function from call "
224          "graph if it references other functions!");
225   Function *F = CGN->getFunction(); // Get the function for the call graph node
226   delete CGN;                       // Delete the call graph node for this func
227   FunctionMap.erase(F);             // Remove the call graph node from the map
228
229   Mod->getFunctionList().remove(F);
230   return F;
231 }
232
233 /// spliceFunction - Replace the function represented by this node by another.
234 /// This does not rescan the body of the function, so it is suitable when
235 /// splicing the body of the old function to the new while also updating all
236 /// callers from old to new.
237 ///
238 void CallGraph::spliceFunction(const Function *From, const Function *To) {
239   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
240   assert(!FunctionMap.count(To) &&
241          "Pointing CallGraphNode at a function that already exists");
242   FunctionMapTy::iterator I = FunctionMap.find(From);
243   I->second->F = const_cast<Function*>(To);
244   FunctionMap[To] = I->second;
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.
251 CallGraphNode *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 void CallGraphNode::print(raw_ostream &OS) const {
260   if (Function *F = getFunction())
261     OS << "Call graph node for function: '" << F->getName() << "'";
262   else
263     OS << "Call graph node <<null function>>";
264   
265   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
266
267   for (const_iterator I = begin(), E = end(); I != E; ++I) {
268     OS << "  CS<" << I->first << "> calls ";
269     if (Function *FI = I->second->getFunction())
270       OS << "function '" << FI->getName() <<"'\n";
271     else
272       OS << "external node\n";
273   }
274   OS << '\n';
275 }
276
277 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
278 void CallGraphNode::dump() const { print(dbgs()); }
279 #endif
280
281 /// removeCallEdgeFor - This method removes the edge in the node for the
282 /// specified call site.  Note that this method takes linear time, so it
283 /// should be used sparingly.
284 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
285   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
286     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
287     if (I->first == CS.getInstruction()) {
288       I->second->DropRef();
289       *I = CalledFunctions.back();
290       CalledFunctions.pop_back();
291       return;
292     }
293   }
294 }
295
296 // removeAnyCallEdgeTo - This method removes any call edges from this node to
297 // the specified callee function.  This takes more time to execute than
298 // removeCallEdgeTo, so it should not be used unless necessary.
299 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
300   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
301     if (CalledFunctions[i].second == Callee) {
302       Callee->DropRef();
303       CalledFunctions[i] = CalledFunctions.back();
304       CalledFunctions.pop_back();
305       --i; --e;
306     }
307 }
308
309 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
310 /// from this node to the specified callee function.
311 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
312   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
313     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
314     CallRecord &CR = *I;
315     if (CR.second == Callee && CR.first == 0) {
316       Callee->DropRef();
317       *I = CalledFunctions.back();
318       CalledFunctions.pop_back();
319       return;
320     }
321   }
322 }
323
324 /// replaceCallEdge - This method replaces the edge in the node for the
325 /// specified call site with a new one.  Note that this method takes linear
326 /// time, so it should be used sparingly.
327 void CallGraphNode::replaceCallEdge(CallSite CS,
328                                     CallSite NewCS, CallGraphNode *NewNode){
329   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
330     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
331     if (I->first == CS.getInstruction()) {
332       I->second->DropRef();
333       I->first = NewCS.getInstruction();
334       I->second = NewNode;
335       NewNode->AddRef();
336       return;
337     }
338   }
339 }
340
341 // Enuse that users of CallGraph.h also link with this file
342 DEFINING_FILE_FOR(CallGraph)