Add more functions
[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 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 interface is used to build and manipulate a call graph, which is a very 
11 // useful tool for interprocedural optimization.
12 //
13 // Every function in a module is represented as a node in the call graph.  The
14 // callgraph node keeps track of which functions the are called by the function
15 // corresponding to the node.
16 //
17 // A call graph will contain nodes where the function that they correspond to is
18 // null.  This 'external' node is used to represent control flow that is not
19 // represented (or analyzable) in the module.  As such, the external node will
20 // have edges to functions with the following properties:
21 //   1. All functions in the module without internal linkage, since they could
22 //      be called by functions outside of the our analysis capability.
23 //   2. All functions whose address is used for something more than a direct
24 //      call, for example being stored into a memory location.  Since they may
25 //      be called by an unknown caller later, they must be tracked as such.
26 //
27 // Similarly, functions have a call edge to the external node iff:
28 //   1. The function is external, reflecting the fact that they could call
29 //      anything without internal linkage or that has its address taken.
30 //   2. The function contains an indirect function call.
31 //
32 // As an extension in the future, there may be multiple nodes with a null
33 // function.  These will be used when we can prove (through pointer analysis)
34 // that an indirect call site can call only a specific set of functions.
35 //
36 // Because of these properties, the CallGraph captures a conservative superset
37 // of all of the caller-callee relationships, which is useful for
38 // transformations.
39 //
40 // The CallGraph class also attempts to figure out what the root of the
41 // CallGraph is, which is currently does by looking for a function named 'main'.
42 // If no function named 'main' is found, the external node is used as the entry
43 // node, reflecting the fact that any function without internal linkage could
44 // be called into (which is common for libraries).
45 //
46 //===----------------------------------------------------------------------===//
47
48 #include "llvm/Analysis/CallGraph.h"
49 #include "llvm/Constants.h"     // Remove when ConstantPointerRefs are gone
50 #include "llvm/Module.h"
51 #include "llvm/iOther.h"
52 #include "llvm/iTerminators.h"
53 #include "llvm/Support/CallSite.h"
54 #include "Support/STLExtras.h"
55
56 static RegisterAnalysis<CallGraph> X("callgraph", "Call Graph Construction");
57
58 static const char * const KnownExternalFunctions[] = {
59   // Low-level system calls
60   "open",
61   "read",
62   "write",
63   "writev",
64   "lseek",
65   "poll",
66   "ioctl",
67
68   // Low-level stdc library functions
69   "abort",
70   "getenv",
71   "putenv",
72   
73   // Standard IO functions
74   "printf",
75   "sprintf",
76   "fopen",
77   "freopen",
78   "fclose",
79   "fwrite",
80   "puts",
81   "fputs",
82   "getc",
83   "ungetc",
84   "putc",
85   "putchar",
86   "fread",
87   "fileno",
88   "ftell",
89   "fflush",
90   "fseek",
91   "fileno",
92   "ferror",
93   "feof",
94   "fdopen",
95   "__fxstat",
96   "setbuf",
97   "setbuffer",
98   "etlinebuf",
99   "setvbuf",
100
101   // Memory functions
102   "malloc",
103   "free",
104   "realloc",
105   "calloc",
106   "memalign",
107   
108   // String functions
109   "atoi",
110   "memmove",
111   "memset",
112   "memchr",
113   "memcmp",
114   "strchr",
115   "strncpy",
116   "strncmp",
117   "strcmp",
118   "__strcoll_l",
119   "__strxfrm_l",
120   "__strftime_l",
121   "__strtol_l",
122   "__strtoul_l",
123   "__strtoll_l",
124   "__strtoull_l",
125   "__strtof_l",
126   "__strtod_l",
127   "__strtold_l",
128
129   // Math functions
130   "exp", "sqrt", "cbrt", "hypot",
131   "log", "log10", "pow",
132   "sin", "cos", "tan",
133   "asin", "acos", "atan", "atan2",
134
135   // Locale functions
136   "__uselocale",
137   "__newlocale",
138   "__freelocale",
139   "__duplocale",
140   "__nl_langinfo_l",
141
142   // gettext functions used by libstdc++
143   "gettext",
144   "dgettext",
145   "dcgettext",
146   "textdomain",
147   "bindtextdomain",
148   
149   // Random stuff
150   "__assert_fail",
151   "__errno_location",
152   "clock", "time",
153   "__main",
154 };
155
156
157 /// ExternalFunctionDoesntCallIntoProgram - This hack is used to indicate to the
158 /// call graph that the specified external function is _KNOWN_ to not call back
159 /// into the program.  This is important, because otherwise functions which call
160 /// "printf" for example, end up in a great big SCC that goes from the function
161 /// through main.
162 ///
163 static bool ExternalFunctionDoesntCallIntoProgram(const std::string &Name) {
164   static std::vector<std::string> Funcs;
165
166   // First time this is called?
167   if (Funcs.empty()) {
168     // Add a whole bunch of functions which are often used...
169     Funcs.insert(Funcs.end(), KnownExternalFunctions,
170                  KnownExternalFunctions+
171               sizeof(KnownExternalFunctions)/sizeof(KnownExternalFunctions[0]));
172     // Sort the list for efficient access
173     std::sort(Funcs.begin(), Funcs.end());
174   }
175
176   if (Name.size() > 7 && !memcmp("__llvm_", Name.c_str(), 7))
177     return true;
178
179   // Binary search for the function name...
180   std::vector<std::string>::iterator I =
181     std::lower_bound(Funcs.begin(), Funcs.end(), Name);
182
183   // Found it?
184   return I != Funcs.end() && *I == Name;
185 }
186
187
188
189 // getNodeFor - Return the node for the specified function or create one if it
190 // does not already exist.
191 //
192 CallGraphNode *CallGraph::getNodeFor(Function *F) {
193   CallGraphNode *&CGN = FunctionMap[F];
194   if (CGN) return CGN;
195
196   assert((!F || F->getParent() == Mod) && "Function not in current module!");
197   return CGN = new CallGraphNode(F);
198 }
199
200 static bool isOnlyADirectCall(Function *F, CallSite CS) {
201   if (!CS.getInstruction()) return false;
202   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); I != E; ++I)
203     if (*I == F) return false;
204   return true;
205 }
206
207 // addToCallGraph - Add a function to the call graph, and link the node to all
208 // of the functions that it calls.
209 //
210 void CallGraph::addToCallGraph(Function *F) {
211   CallGraphNode *Node = getNodeFor(F);
212
213   // If this function has external linkage, anything could call it...
214   if (!F->hasInternalLinkage()) {
215     ExternalNode->addCalledFunction(Node);
216
217     // Found the entry point?
218     if (F->getName() == "main") {
219       if (Root)
220         Root = ExternalNode;  // Found multiple external mains?  Don't pick one.
221       else
222         Root = Node;          // Found a main, keep track of it!
223     }
224   }
225   
226   // If this function is not defined in this translation unit, it could call
227   // anything.
228   if (F->isExternal() && !F->getIntrinsicID() && 
229       !ExternalFunctionDoesntCallIntoProgram(F->getName()))
230     Node->addCalledFunction(ExternalNode);
231
232   // Loop over all of the users of the function... looking for callers...
233   //
234   bool isUsedExternally = false;
235   for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {
236     if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
237       if (isOnlyADirectCall(F, CallSite::get(Inst)))
238         getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
239       else
240         isUsedExternally = true;
241     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I)) {
242       // THIS IS A DISGUSTING HACK.  Brought to you by the power of
243       // ConstantPointerRefs!
244       for (Value::use_iterator I = CPR->use_begin(), E = CPR->use_end();
245            I != E; ++I)
246         if (Instruction *Inst = dyn_cast<Instruction>(*I)) {
247           if (isOnlyADirectCall(F, CallSite::get(Inst)))
248             getNodeFor(Inst->getParent()->getParent())->addCalledFunction(Node);
249           else
250             isUsedExternally = true;
251         } else {
252           isUsedExternally = true;
253         }
254     } else {                        // Can't classify the user!
255       isUsedExternally = true;
256     }
257   }
258   if (isUsedExternally)
259     ExternalNode->addCalledFunction(Node);
260
261   // Look for an indirect function call...
262   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
263     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
264       CallSite CS = CallSite::get(II);
265       if (CS.getInstruction() && !CS.getCalledFunction())
266         Node->addCalledFunction(ExternalNode);
267     }
268 }
269
270 bool CallGraph::run(Module &M) {
271   destroy();
272
273   Mod = &M;
274   ExternalNode = getNodeFor(0);
275   Root = 0;
276
277   // Add every function to the call graph...
278   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
279     addToCallGraph(I);
280
281   // If we didn't find a main function, use the external call graph node
282   if (Root == 0) Root = ExternalNode;
283   
284   return false;
285 }
286
287 void CallGraph::destroy() {
288   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
289        I != E; ++I)
290     delete I->second;
291   FunctionMap.clear();
292 }
293
294 static void WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {
295   if (CGN->getFunction())
296     o << "Call graph node for function: '"
297       << CGN->getFunction()->getName() <<"'\n";
298   else
299     o << "Call graph node <<null function: 0x" << CGN << ">>:\n";
300
301   for (unsigned i = 0; i < CGN->size(); ++i)
302     if ((*CGN)[i]->getFunction())
303       o << "  Calls function '" << (*CGN)[i]->getFunction()->getName() << "'\n";
304     else
305       o << "  Calls external node\n";
306   o << "\n";
307 }
308
309 void CallGraph::print(std::ostream &o, const Module *M) const {
310   o << "CallGraph Root is: ";
311   if (getRoot()->getFunction())
312     o << getRoot()->getFunction()->getName() << "\n";
313   else
314     o << "<<null function: 0x" << getRoot() << ">>\n";
315   
316   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
317     WriteToOutput(I->second, o);
318 }
319
320
321 //===----------------------------------------------------------------------===//
322 // Implementations of public modification methods
323 //
324
325 // Functions to keep a call graph up to date with a function that has been
326 // modified
327 //
328 void CallGraph::addFunctionToModule(Function *Meth) {
329   assert(0 && "not implemented");
330   abort();
331 }
332
333 // removeFunctionFromModule - Unlink the function from this module, returning
334 // it.  Because this removes the function from the module, the call graph node
335 // is destroyed.  This is only valid if the function does not call any other
336 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
337 // is to dropAllReferences before calling this.
338 //
339 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
340   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
341          "graph if it references other functions!");
342   Function *F = CGN->getFunction(); // Get the function for the call graph node
343   delete CGN;                       // Delete the call graph node for this func
344   FunctionMap.erase(F);             // Remove the call graph node from the map
345
346   Mod->getFunctionList().remove(F);
347   return F;
348 }
349
350 void CallGraph::stub() {}