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