Added LLVM project notice to the top of every C++ source file.
[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/Module.h"
50 #include "llvm/iOther.h"
51 #include "llvm/iTerminators.h"
52 #include "Support/STLExtras.h"
53 #include <algorithm>
54
55 static RegisterAnalysis<CallGraph> X("callgraph", "Call Graph Construction");
56
57 // getNodeFor - Return the node for the specified function or create one if it
58 // does not already exist.
59 //
60 CallGraphNode *CallGraph::getNodeFor(Function *F) {
61   CallGraphNode *&CGN = FunctionMap[F];
62   if (CGN) return CGN;
63
64   assert((!F || F->getParent() == Mod) && "Function not in current module!");
65   return CGN = new CallGraphNode(F);
66 }
67
68 // addToCallGraph - Add a function to the call graph, and link the node to all
69 // of the functions that it calls.
70 //
71 void CallGraph::addToCallGraph(Function *F) {
72   CallGraphNode *Node = getNodeFor(F);
73
74   // If this function has external linkage, anything could call it...
75   if (!F->hasInternalLinkage()) {
76     ExternalNode->addCalledFunction(Node);
77
78     // Found the entry point?
79     if (F->getName() == "main") {
80       if (Root)
81         Root = ExternalNode;  // Found multiple external mains?  Don't pick one.
82       else
83         Root = Node;          // Found a main, keep track of it!
84     }
85   }
86   
87   // If this function is not defined in this translation unit, it could call
88   // anything.
89   if (F->isExternal())
90     Node->addCalledFunction(ExternalNode);
91
92   // Loop over all of the users of the function... looking for callers...
93   //
94   for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; ++I) {
95     User *U = *I;
96     if (CallInst *CI = dyn_cast<CallInst>(U))
97       getNodeFor(CI->getParent()->getParent())->addCalledFunction(Node);
98     else if (InvokeInst *II = dyn_cast<InvokeInst>(U))
99       getNodeFor(II->getParent()->getParent())->addCalledFunction(Node);
100     else                         // Can't classify the user!
101       ExternalNode->addCalledFunction(Node);
102   }
103
104   // Look for an indirect function call...
105   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
106     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
107       Instruction &I = *II;
108
109       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
110         if (CI->getCalledFunction() == 0)
111           Node->addCalledFunction(ExternalNode);
112       } else if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
113         if (II->getCalledFunction() == 0)
114           Node->addCalledFunction(ExternalNode);
115       }
116     }
117 }
118
119 bool CallGraph::run(Module &M) {
120   destroy();
121
122   Mod = &M;
123   ExternalNode = getNodeFor(0);
124   Root = 0;
125
126   // Add every function to the call graph...
127   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
128     addToCallGraph(I);
129
130   // If we didn't find a main function, use the external call graph node
131   if (Root == 0) Root = ExternalNode;
132   
133   return false;
134 }
135
136 void CallGraph::destroy() {
137   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
138        I != E; ++I)
139     delete I->second;
140   FunctionMap.clear();
141 }
142
143 static void WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {
144   if (CGN->getFunction())
145     o << "Call graph node for function: '"
146       << CGN->getFunction()->getName() <<"'\n";
147   else
148     o << "Call graph node <<null function: 0x" << CGN << ">>:\n";
149
150   for (unsigned i = 0; i < CGN->size(); ++i)
151     if ((*CGN)[i]->getFunction())
152       o << "  Calls function '" << (*CGN)[i]->getFunction()->getName() << "'\n";
153     else
154       o << "  Calls external node\n";
155   o << "\n";
156 }
157
158 void CallGraph::print(std::ostream &o, const Module *M) const {
159   o << "CallGraph Root is: ";
160   if (getRoot()->getFunction())
161     o << getRoot()->getFunction()->getName() << "\n";
162   else
163     o << "<<null function: 0x" << getRoot() << ">>\n";
164   
165   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
166     WriteToOutput(I->second, o);
167 }
168
169
170 //===----------------------------------------------------------------------===//
171 // Implementations of public modification methods
172 //
173
174 // Functions to keep a call graph up to date with a function that has been
175 // modified
176 //
177 void CallGraph::addFunctionToModule(Function *Meth) {
178   assert(0 && "not implemented");
179   abort();
180 }
181
182 // removeFunctionFromModule - Unlink the function from this module, returning
183 // it.  Because this removes the function from the module, the call graph node
184 // is destroyed.  This is only valid if the function does not call any other
185 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
186 // is to dropAllReferences before calling this.
187 //
188 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
189   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
190          "graph if it references other functions!");
191   Function *F = CGN->getFunction(); // Get the function for the call graph node
192   delete CGN;                       // Delete the call graph node for this func
193   FunctionMap.erase(F);             // Remove the call graph node from the map
194
195   Mod->getFunctionList().remove(F);
196   return F;
197 }
198