* s/method/function
[oota-llvm.git] / lib / Analysis / IPA / CallGraph.cpp
1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
2 //
3 // This interface is used to build and manipulate a call graph, which is a very 
4 // useful tool for interprocedural optimization.
5 //
6 // Every function in a module is represented as a node in the call graph.  The
7 // callgraph node keeps track of which functions the are called by the function
8 // corresponding to the node.
9 //
10 // A call graph will contain nodes where the function that they correspond to is
11 // null.  This 'external' node is used to represent control flow that is not
12 // represented (or analyzable) in the module.  As such, the external node will
13 // have edges to functions with the following properties:
14 //   1. All functions in the module without internal linkage, since they could
15 //      be called by functions outside of the our analysis capability.
16 //   2. All functions whose address is used for something more than a direct
17 //      call, for example being stored into a memory location.  Since they may
18 //      be called by an unknown caller later, they must be tracked as such.
19 //
20 // Similarly, functions have a call edge to the external node iff:
21 //   1. The function is external, reflecting the fact that they could call
22 //      anything without internal linkage or that has its address taken.
23 //   2. The function contains an indirect function call.
24 //
25 // As an extension in the future, there may be multiple nodes with a null
26 // function.  These will be used when we can prove (through pointer analysis)
27 // that an indirect call site can call only a specific set of functions.
28 //
29 // Because of these properties, the CallGraph captures a conservative superset
30 // of all of the caller-callee relationships, which is useful for
31 // transformations.
32 //
33 // The CallGraph class also attempts to figure out what the root of the
34 // CallGraph is, which is currently does by looking for a function named 'main'.
35 // If no function named 'main' is found, the external node is used as the entry
36 // node, reflecting the fact that any function without internal linkage could
37 // be called into (which is common for libraries).
38 //
39 //===----------------------------------------------------------------------===//
40
41 #include "llvm/Analysis/CallGraph.h"
42 #include "llvm/Module.h"
43 #include "llvm/Function.h"
44 #include "llvm/BasicBlock.h"
45 #include "llvm/iOther.h"
46 #include "llvm/iTerminators.h"
47 #include "Support/STLExtras.h"
48 #include <algorithm>
49 #include <iostream>
50
51 AnalysisID CallGraph::ID(AnalysisID::create<CallGraph>());
52
53 // getNodeFor - Return the node for the specified function or create one if it
54 // does not already exist.
55 //
56 CallGraphNode *CallGraph::getNodeFor(Function *F) {
57   CallGraphNode *&CGN = FunctionMap[F];
58   if (CGN) return CGN;
59
60   assert((!F || F->getParent() == Mod) && "Function not in current module!");
61   return CGN = new CallGraphNode(F);
62 }
63
64 // addToCallGraph - Add a function to the call graph, and link the node to all
65 // of the functions that it calls.
66 //
67 void CallGraph::addToCallGraph(Function *M) {
68   CallGraphNode *Node = getNodeFor(M);
69
70   // If this function has external linkage, 
71   if (!M->hasInternalLinkage()) {
72     ExternalNode->addCalledFunction(Node);
73
74     // Found the entry point?
75     if (M->getName() == "main") {
76       if (Root)
77         Root = ExternalNode;  // Found multiple external mains?  Don't pick one.
78       else
79         Root = Node;          // Found a main, keep track of it!
80     }
81   } else if (M->isExternal()) { // Not defined in this xlation unit?
82     Node->addCalledFunction(ExternalNode);  // It could call anything...
83   }
84
85   // Loop over all of the users of the function... looking for callers...
86   //
87   for (Value::use_iterator I = M->use_begin(), E = M->use_end(); I != E; ++I) {
88     User *U = *I;
89     if (CallInst *CI = dyn_cast<CallInst>(U))
90       getNodeFor(CI->getParent()->getParent())->addCalledFunction(Node);
91     else if (InvokeInst *II = dyn_cast<InvokeInst>(U))
92       getNodeFor(II->getParent()->getParent())->addCalledFunction(Node);
93     else                         // Can't classify the user!
94       ExternalNode->addCalledFunction(Node);
95   }
96
97   // Look for an indirect function call...
98   for (Function::iterator BB = M->begin(), BBE = M->end(); BB != BBE; ++BB)
99     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE; ++II){
100       Instruction &I = *II;
101
102       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
103         if (CI->getCalledFunction() == 0)
104           Node->addCalledFunction(ExternalNode);
105       } else if (InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
106         if (II->getCalledFunction() == 0)
107           Node->addCalledFunction(ExternalNode);
108       }
109     }
110 }
111
112 bool CallGraph::run(Module &M) {
113   destroy();
114
115   Mod = &M;
116   ExternalNode = getNodeFor(0);
117   Root = 0;
118
119   // Add every function to the call graph...
120   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
121     addToCallGraph(I);
122
123   // If we didn't find a main function, use the external call graph node
124   if (Root == 0) Root = ExternalNode;
125   
126   return false;
127 }
128
129 void CallGraph::destroy() {
130   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
131        I != E; ++I)
132     delete I->second;
133   FunctionMap.clear();
134 }
135
136
137 void WriteToOutput(const CallGraphNode *CGN, std::ostream &o) {
138   if (CGN->getFunction())
139     o << "Call graph node for function: '"
140       << CGN->getFunction()->getName() <<"'\n";
141   else
142     o << "Call graph node null function:\n";
143
144   for (unsigned i = 0; i < CGN->size(); ++i)
145     if ((*CGN)[i]->getFunction())
146       o << "  Calls function '" << (*CGN)[i]->getFunction()->getName() << "'\n";
147     else
148       o << "  Calls external node\n";
149   o << "\n";
150 }
151
152 void WriteToOutput(const CallGraph &CG, std::ostream &o) {
153   o << "CallGraph Root is:\n" << CG.getRoot();
154
155   for (CallGraph::const_iterator I = CG.begin(), E = CG.end(); I != E; ++I)
156     o << I->second;
157 }
158
159
160 //===----------------------------------------------------------------------===//
161 // Implementations of public modification methods
162 //
163
164 // Functions to keep a call graph up to date with a function that has been
165 // modified
166 //
167 void CallGraph::addFunctionToModule(Function *Meth) {
168   assert(0 && "not implemented");
169   abort();
170 }
171
172 // removeFunctionFromModule - Unlink the function from this module, returning
173 // it.  Because this removes the function from the module, the call graph node
174 // is destroyed.  This is only valid if the function does not call any other
175 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
176 // is to dropAllReferences before calling this.
177 //
178 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
179   assert(CGN->CalledFunctions.empty() && "Cannot remove function from call "
180          "graph if it references other functions!");
181   Function *M = CGN->getFunction(); // Get the function for the call graph node
182   delete CGN;                       // Delete the call graph node for this func
183   FunctionMap.erase(M);             // Remove the call graph node from the map
184
185   Mod->getFunctionList().remove(M);
186   return M;
187 }
188