[PM] Clean up a bunch of comments, modernize the doxygen, nuke some
[oota-llvm.git] / include / llvm / Analysis / CallGraph.h
1 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
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 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 may contain nodes where the function that they correspond to is
18 // null.  These 'external' nodes are used to represent control flow that is not
19 // represented (or analyzable) in the module.  In particular, this analysis
20 // builds one external node such that:
21 //   1. All functions in the module without internal linkage will have edges
22 //      from this external node, indicating that they could be called by
23 //      functions outside of the module.
24 //   2. All functions whose address is used for something more than a direct
25 //      call, for example being stored into a memory location will also have an
26 //      edge from this external node.  Since they may be called by an unknown
27 //      caller later, they must be tracked as such.
28 //
29 // There is a second external node added for calls that leave this module.
30 // Functions have a call edge to the external node iff:
31 //   1. The function is external, reflecting the fact that they could call
32 //      anything without internal linkage or that has its address taken.
33 //   2. The function contains an indirect function call.
34 //
35 // As an extension in the future, there may be multiple nodes with a null
36 // function.  These will be used when we can prove (through pointer analysis)
37 // that an indirect call site can call only a specific set of functions.
38 //
39 // Because of these properties, the CallGraph captures a conservative superset
40 // of all of the caller-callee relationships, which is useful for
41 // transformations.
42 //
43 // The CallGraph class also attempts to figure out what the root of the
44 // CallGraph is, which it currently does by looking for a function named 'main'.
45 // If no function named 'main' is found, the external node is used as the entry
46 // node, reflecting the fact that any function without internal linkage could
47 // be called into (which is common for libraries).
48 //
49 //===----------------------------------------------------------------------===//
50
51 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
52 #define LLVM_ANALYSIS_CALLGRAPH_H
53
54 #include "llvm/ADT/GraphTraits.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/Pass.h"
58 #include "llvm/Support/CallSite.h"
59 #include "llvm/Support/IncludeFile.h"
60 #include "llvm/Support/ValueHandle.h"
61 #include <map>
62
63 namespace llvm {
64
65 class Function;
66 class Module;
67 class CallGraphNode;
68
69 /// \brief The basic data container for the call graph and the \c ModulePass
70 /// which produces it.
71 ///
72 /// This class exposes both the interface to the call graph container and the
73 /// module pass which runs over a module of IR and produces the call graph.
74 ///
75 /// The core call graph itself can also be updated to reflect changes to the IR.
76 class CallGraph : public ModulePass {
77   Module *Mod;              // The module this call graph represents
78
79   typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
80   FunctionMapTy FunctionMap;    // Map from a function to its node
81
82   /// \brief Root is root of the call graph, or the external node if a 'main'
83   /// function couldn't be found.
84   CallGraphNode *Root;
85
86   /// \brief This node has edges to all external functions and those internal
87   /// functions that have their address taken.
88   CallGraphNode *ExternalCallingNode;
89
90   /// \brief This node has edges to it from all functions making indirect calls
91   /// or calling an external function.
92   CallGraphNode *CallsExternalNode;
93
94   /// \brief Replace the function represented by this node by another.
95   ///
96   /// This does not rescan the body of the function, so it is suitable when
97   /// splicing the body of one function to another while also updating all
98   /// callers from the old function to the new.
99   void spliceFunction(const Function *From, const Function *To);
100
101   /// \brief Add a function to the call graph, and link the node to all of the
102   /// functions that it calls.
103   void addToCallGraph(Function *F);
104
105 public:
106   static char ID; // Class identification, replacement for typeinfo
107
108   typedef FunctionMapTy::iterator iterator;
109   typedef FunctionMapTy::const_iterator const_iterator;
110
111   /// \brief Returns the module the call graph corresponds to.
112   Module &getModule() const { return *Mod; }
113
114   inline       iterator begin()       { return FunctionMap.begin(); }
115   inline       iterator end()         { return FunctionMap.end();   }
116   inline const_iterator begin() const { return FunctionMap.begin(); }
117   inline const_iterator end()   const { return FunctionMap.end();   }
118
119   /// \brief Returns the call graph node for the provided function.
120   inline const CallGraphNode *operator[](const Function *F) const {
121     const_iterator I = FunctionMap.find(F);
122     assert(I != FunctionMap.end() && "Function not in callgraph!");
123     return I->second;
124   }
125
126   /// \brief Returns the call graph node for the provided function.
127   inline CallGraphNode *operator[](const Function *F) {
128     const_iterator I = FunctionMap.find(F);
129     assert(I != FunctionMap.end() && "Function not in callgraph!");
130     return I->second;
131   }
132
133   /// \brief Returns the \c CallGraphNode which is used to represent
134   /// undetermined calls into the callgraph.
135   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
136
137   CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
138
139   /// \brief Returns the root/main method in the module, or some other root
140   /// node, such as the externalcallingnode.
141   CallGraphNode *getRoot() { return Root; }
142   const CallGraphNode *getRoot() const { return Root; }
143
144   //===---------------------------------------------------------------------
145   // Functions to keep a call graph up to date with a function that has been
146   // modified.
147   //
148
149   /// \brief Unlink the function from this module, returning it.
150   ///
151   /// Because this removes the function from the module, the call graph node is
152   /// destroyed.  This is only valid if the function does not call any other
153   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
154   /// this is to dropAllReferences before calling this.
155   Function *removeFunctionFromModule(CallGraphNode *CGN);
156
157   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
158   /// \c F if one does not already exist.
159   CallGraphNode *getOrInsertFunction(const Function *F);
160
161   CallGraph();
162   virtual ~CallGraph() { releaseMemory(); }
163
164   //===---------------------------------------------------------------------
165   // Implementation of the ModulePass interface needed here.
166   //
167
168   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
169   virtual bool runOnModule(Module &M);
170   virtual void releaseMemory();
171
172   void print(raw_ostream &o, const Module *) const;
173   void dump() const;
174 };
175
176 /// \brief A node in the call graph for a module.
177 ///
178 /// Typically represents a function in the call graph. There are also special
179 /// "null" nodes used to represent theoretical entries in the call graph.
180 class CallGraphNode {
181   friend class CallGraph;
182
183   AssertingVH<Function> F;
184
185 public:
186   /// \brief A pair of the calling instruction (a call or invoke)
187   /// and the call graph node being called.
188   typedef std::pair<WeakVH, CallGraphNode*> CallRecord;
189
190 private:
191   std::vector<CallRecord> CalledFunctions;
192
193   /// \brief The number of times that this CallGraphNode occurs in the
194   /// CalledFunctions array of this or other CallGraphNodes.
195   unsigned NumReferences;
196
197   CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
198   void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
199
200   void DropRef() { --NumReferences; }
201   void AddRef() { ++NumReferences; }
202
203 public:
204   typedef std::vector<CallRecord> CalledFunctionsVector;
205
206   /// \brief Creates a node for the specified function.
207   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
208
209   ~CallGraphNode() {
210     assert(NumReferences == 0 && "Node deleted while references remain");
211   }
212
213   typedef std::vector<CallRecord>::iterator iterator;
214   typedef std::vector<CallRecord>::const_iterator const_iterator;
215
216   /// \brief Returns the function that this call graph node represents.
217   Function *getFunction() const { return F; }
218
219   inline iterator begin() { return CalledFunctions.begin(); }
220   inline iterator end()   { return CalledFunctions.end();   }
221   inline const_iterator begin() const { return CalledFunctions.begin(); }
222   inline const_iterator end()   const { return CalledFunctions.end();   }
223   inline bool empty() const { return CalledFunctions.empty(); }
224   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
225
226   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
227   /// reference this node in their callee list.
228   unsigned getNumReferences() const { return NumReferences; }
229
230   /// \brief Returns the i'th called function.
231   CallGraphNode *operator[](unsigned i) const {
232     assert(i < CalledFunctions.size() && "Invalid index");
233     return CalledFunctions[i].second;
234   }
235
236   /// \brief Print out this call graph node.
237   void dump() const;
238   void print(raw_ostream &OS) const;
239
240   //===---------------------------------------------------------------------
241   // Methods to keep a call graph up to date with a function that has been
242   // modified
243   //
244
245   /// \brief Removes all edges from this CallGraphNode to any functions it
246   /// calls.
247   void removeAllCalledFunctions() {
248     while (!CalledFunctions.empty()) {
249       CalledFunctions.back().second->DropRef();
250       CalledFunctions.pop_back();
251     }
252   }
253
254   /// \brief Moves all the callee information from N to this node.
255   void stealCalledFunctionsFrom(CallGraphNode *N) {
256     assert(CalledFunctions.empty() &&
257            "Cannot steal callsite information if I already have some");
258     std::swap(CalledFunctions, N->CalledFunctions);
259   }
260
261   /// \brief Adds a function to the list of functions called by this one.
262   void addCalledFunction(CallSite CS, CallGraphNode *M) {
263     assert(!CS.getInstruction() ||
264            !CS.getCalledFunction() ||
265            !CS.getCalledFunction()->isIntrinsic());
266     CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
267     M->AddRef();
268   }
269
270   void removeCallEdge(iterator I) {
271     I->second->DropRef();
272     *I = CalledFunctions.back();
273     CalledFunctions.pop_back();
274   }
275
276   /// \brief Removes the edge in the node for the specified call site.
277   ///
278   /// Note that this method takes linear time, so it should be used sparingly.
279   void removeCallEdgeFor(CallSite CS);
280
281   /// \brief Removes all call edges from this node to the specified callee
282   /// function.
283   ///
284   /// This takes more time to execute than removeCallEdgeTo, so it should not
285   /// be used unless necessary.
286   void removeAnyCallEdgeTo(CallGraphNode *Callee);
287
288   /// \brief Removes one edge associated with a null callsite from this node to
289   /// the specified callee function.
290   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
291
292   /// \brief Replaces the edge in the node for the specified call site with a
293   /// new one.
294   ///
295   /// Note that this method takes linear time, so it should be used sparingly.
296   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
297
298   /// \brief A special function that should only be used by the CallGraph class.
299   //
300   // FIXME: Make this private?
301   void allReferencesDropped() {
302     NumReferences = 0;
303   }
304 };
305
306 //===----------------------------------------------------------------------===//
307 // GraphTraits specializations for call graphs so that they can be treated as
308 // graphs by the generic graph algorithms.
309 //
310
311 // Provide graph traits for tranversing call graphs using standard graph
312 // traversals.
313 template <> struct GraphTraits<CallGraphNode*> {
314   typedef CallGraphNode NodeType;
315
316   typedef CallGraphNode::CallRecord CGNPairTy;
317   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode*> CGNDerefFun;
318
319   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
320
321   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
322
323   static inline ChildIteratorType child_begin(NodeType *N) {
324     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
325   }
326   static inline ChildIteratorType child_end  (NodeType *N) {
327     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
328   }
329
330   static CallGraphNode *CGNDeref(CGNPairTy P) {
331     return P.second;
332   }
333
334 };
335
336 template <> struct GraphTraits<const CallGraphNode*> {
337   typedef const CallGraphNode NodeType;
338   typedef NodeType::const_iterator ChildIteratorType;
339
340   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
341   static inline ChildIteratorType child_begin(NodeType *N) { return N->begin();}
342   static inline ChildIteratorType child_end  (NodeType *N) { return N->end(); }
343 };
344
345 template<> struct GraphTraits<CallGraph*> : public GraphTraits<CallGraphNode*> {
346   static NodeType *getEntryNode(CallGraph *CGN) {
347     return CGN->getExternalCallingNode();  // Start at the external node!
348   }
349   typedef std::pair<const Function*, CallGraphNode*> PairTy;
350   typedef std::pointer_to_unary_function<PairTy, CallGraphNode&> DerefFun;
351
352   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
353   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
354   static nodes_iterator nodes_begin(CallGraph *CG) {
355     return map_iterator(CG->begin(), DerefFun(CGdereference));
356   }
357   static nodes_iterator nodes_end  (CallGraph *CG) {
358     return map_iterator(CG->end(), DerefFun(CGdereference));
359   }
360
361   static CallGraphNode &CGdereference(PairTy P) {
362     return *P.second;
363   }
364 };
365
366 template<> struct GraphTraits<const CallGraph*> :
367   public GraphTraits<const CallGraphNode*> {
368   static NodeType *getEntryNode(const CallGraph *CGN) {
369     return CGN->getExternalCallingNode();
370   }
371   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
372   typedef CallGraph::const_iterator nodes_iterator;
373   static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
374   static nodes_iterator nodes_end  (const CallGraph *CG) { return CG->end(); }
375 };
376
377 } // End llvm namespace
378
379 // Make sure that any clients of this file link in CallGraph.cpp
380 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)
381
382 #endif