4d15a48d4e18baa1a1098a129a5e867d86a46b7a
[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/Compiler.h"
21 #include "llvm/Support/Streams.h"
22 #include <ostream>
23 using namespace llvm;
24
25 namespace {
26
27 //===----------------------------------------------------------------------===//
28 // BasicCallGraph class definition
29 //
30 class VISIBILITY_HIDDEN BasicCallGraph : public CallGraph, public ModulePass {
31   // Root is root of the call graph, or the external node if a 'main' function
32   // couldn't be found.
33   //
34   CallGraphNode *Root;
35
36   // ExternalCallingNode - This node has edges to all external functions and
37   // those internal functions that have their address taken.
38   CallGraphNode *ExternalCallingNode;
39
40   // CallsExternalNode - This node has edges to it from all functions making
41   // indirect calls or calling an external function.
42   CallGraphNode *CallsExternalNode;
43
44 public:
45   static char ID; // Class identification, replacement for typeinfo
46   BasicCallGraph() : ModulePass(&ID), Root(0), 
47     ExternalCallingNode(0), CallsExternalNode(0) {}
48
49   // runOnModule - Compute the call graph for the specified module.
50   virtual bool runOnModule(Module &M) {
51     CallGraph::initialize(M);
52     
53     ExternalCallingNode = getOrInsertFunction(0);
54     CallsExternalNode = new CallGraphNode(0);
55     Root = 0;
56   
57     // Add every function to the call graph...
58     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
59       addToCallGraph(I);
60   
61     // If we didn't find a main function, use the external call graph node
62     if (Root == 0) Root = ExternalCallingNode;
63     
64     return false;
65   }
66
67   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68     AU.setPreservesAll();
69   }
70
71   void print(std::ostream *o, const Module *M) const {
72     if (o) print(*o, M);
73   }
74
75   virtual void print(std::ostream &o, const Module *M) const {
76     o << "CallGraph Root is: ";
77     if (Function *F = getRoot()->getFunction())
78       o << F->getNameStr() << "\n";
79     else
80       o << "<<null function: 0x" << getRoot() << ">>\n";
81     
82     CallGraph::print(o, M);
83   }
84
85   virtual void releaseMemory() {
86     destroy();
87   }
88   
89   /// dump - Print out this call graph.
90   ///
91   inline void dump() const {
92     print(cerr, Mod);
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       if ((!isa<CallInst>(I) && !isa<InvokeInst>(I))
131           || !CallSite(cast<Instruction>(I)).isCallee(I)) {
132         // Not a call, or being used as a parameter rather than as the callee.
133         ExternalCallingNode->addCalledFunction(CallSite(), Node);
134         break;
135       }
136
137     // If this function is not defined in this translation unit, it could call
138     // anything.
139     if (F->isDeclaration() && !F->isIntrinsic())
140       Node->addCalledFunction(CallSite(), CallsExternalNode);
141
142     // Look for calls by this function.
143     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
144       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
145            II != IE; ++II) {
146         CallSite CS = CallSite::get(II);
147         if (CS.getInstruction() && !isa<DbgInfoIntrinsic>(II)) {
148           const Function *Callee = CS.getCalledFunction();
149           if (Callee)
150             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
151           else
152             Node->addCalledFunction(CS, CallsExternalNode);
153         }
154       }
155   }
156
157   //
158   // destroy - Release memory for the call graph
159   virtual void destroy() {
160     /// CallsExternalNode is not in the function map, delete it explicitly.
161     delete CallsExternalNode;
162     CallsExternalNode = 0;
163     CallGraph::destroy();
164   }
165 };
166
167 } //End anonymous namespace
168
169 static RegisterAnalysisGroup<CallGraph> X("Call Graph");
170 static RegisterPass<BasicCallGraph>
171 Y("basiccg", "Basic CallGraph Construction", false, true);
172 static RegisterAnalysisGroup<CallGraph, true> Z(Y);
173
174 char CallGraph::ID = 0;
175 char BasicCallGraph::ID = 0;
176
177 void CallGraph::initialize(Module &M) {
178   Mod = &M;
179 }
180
181 void CallGraph::destroy() {
182   if (!FunctionMap.empty()) {
183     for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
184         I != E; ++I)
185       delete I->second;
186     FunctionMap.clear();
187   }
188 }
189
190 void CallGraph::print(std::ostream &OS, const Module *M) const {
191   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
192     I->second->print(OS);
193 }
194
195 void CallGraph::dump() const {
196   print(cerr, 0);
197 }
198
199 //===----------------------------------------------------------------------===//
200 // Implementations of public modification methods
201 //
202
203 // removeFunctionFromModule - Unlink the function from this module, returning
204 // it.  Because this removes the function from the module, the call graph node
205 // is destroyed.  This is only valid if the function does not call any other
206 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
207 // is to dropAllReferences before calling this.
208 //
209 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
210   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
211          "graph if it references other functions!");
212   Function *F = CGN->getFunction(); // Get the function for the call graph node
213   delete CGN;                       // Delete the call graph node for this func
214   FunctionMap.erase(F);             // Remove the call graph node from the map
215
216   Mod->getFunctionList().remove(F);
217   return F;
218 }
219
220 // changeFunction - This method changes the function associated with this
221 // CallGraphNode, for use by transformations that need to change the prototype
222 // of a Function (thus they must create a new Function and move the old code
223 // over).
224 void CallGraph::changeFunction(Function *OldF, Function *NewF) {
225   iterator I = FunctionMap.find(OldF);
226   CallGraphNode *&New = FunctionMap[NewF];
227   assert(I != FunctionMap.end() && I->second && !New &&
228          "OldF didn't exist in CG or NewF already does!");
229   New = I->second;
230   New->F = NewF;
231   FunctionMap.erase(I);
232 }
233
234 // getOrInsertFunction - This method is identical to calling operator[], but
235 // it will insert a new CallGraphNode for the specified function if one does
236 // not already exist.
237 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
238   CallGraphNode *&CGN = FunctionMap[F];
239   if (CGN) return CGN;
240   
241   assert((!F || F->getParent() == Mod) && "Function not in current module!");
242   return CGN = new CallGraphNode(const_cast<Function*>(F));
243 }
244
245 void CallGraphNode::print(std::ostream &OS) const {
246   if (Function *F = getFunction())
247     OS << "Call graph node for function: '" << F->getNameStr() <<"'\n";
248   else
249     OS << "Call graph node <<null function: 0x" << this << ">>:\n";
250
251   for (const_iterator I = begin(), E = end(); I != E; ++I)
252     if (Function *FI = I->second->getFunction())
253       OS << "  Calls function '" << FI->getNameStr() <<"'\n";
254   else
255     OS << "  Calls external node\n";
256   OS << "\n";
257 }
258
259 void CallGraphNode::dump() const { print(cerr); }
260
261 /// removeCallEdgeFor - This method removes the edge in the node for the
262 /// specified call site.  Note that this method takes linear time, so it
263 /// should be used sparingly.
264 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
265   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
266     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
267     if (I->first == CS) {
268       CalledFunctions.erase(I);
269       return;
270     }
271   }
272 }
273
274
275 // removeAnyCallEdgeTo - This method removes any call edges from this node to
276 // the specified callee function.  This takes more time to execute than
277 // removeCallEdgeTo, so it should not be used unless necessary.
278 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
279   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
280     if (CalledFunctions[i].second == Callee) {
281       CalledFunctions[i] = CalledFunctions.back();
282       CalledFunctions.pop_back();
283       --i; --e;
284     }
285 }
286
287 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
288 /// from this node to the specified callee function.
289 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
290   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
291     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
292     CallRecord &CR = *I;
293     if (CR.second == Callee && !CR.first.getInstruction()) {
294       CalledFunctions.erase(I);
295       return;
296     }
297   }
298 }
299
300 /// replaceCallSite - Make the edge in the node for Old CallSite be for
301 /// New CallSite instead.  Note that this method takes linear time, so it
302 /// should be used sparingly.
303 void CallGraphNode::replaceCallSite(CallSite Old, CallSite New) {
304   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
305     assert(I != CalledFunctions.end() && "Cannot find callsite to replace!");
306     if (I->first == Old) {
307       I->first = New;
308       return;
309     }
310   }
311 }
312
313 // Enuse that users of CallGraph.h also link with this file
314 DEFINING_FILE_FOR(CallGraph)