[PM] Sink a trailing comment to be a doxygen comment.
[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 *M;
78
79   typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
80
81   /// \brief A map from \c Function* to \c CallGraphNode*.
82   FunctionMapTy FunctionMap;
83
84   /// \brief Root is root of the call graph, or the external node if a 'main'
85   /// function couldn't be found.
86   CallGraphNode *Root;
87
88   /// \brief This node has edges to all external functions and those internal
89   /// functions that have their address taken.
90   CallGraphNode *ExternalCallingNode;
91
92   /// \brief This node has edges to it from all functions making indirect calls
93   /// or calling an external function.
94   CallGraphNode *CallsExternalNode;
95
96   /// \brief Replace the function represented by this node by another.
97   ///
98   /// This does not rescan the body of the function, so it is suitable when
99   /// splicing the body of one function to another while also updating all
100   /// callers from the old function to the new.
101   void spliceFunction(const Function *From, const Function *To);
102
103   /// \brief Add a function to the call graph, and link the node to all of the
104   /// functions that it calls.
105   void addToCallGraph(Function *F);
106
107 public:
108   static char ID; // Class identification, replacement for typeinfo
109
110   typedef FunctionMapTy::iterator iterator;
111   typedef FunctionMapTy::const_iterator const_iterator;
112
113   /// \brief Returns the module the call graph corresponds to.
114   Module &getModule() const { return *M; }
115
116   inline       iterator begin()       { return FunctionMap.begin(); }
117   inline       iterator end()         { return FunctionMap.end();   }
118   inline const_iterator begin() const { return FunctionMap.begin(); }
119   inline const_iterator end()   const { return FunctionMap.end();   }
120
121   /// \brief Returns the call graph node for the provided function.
122   inline const CallGraphNode *operator[](const Function *F) const {
123     const_iterator I = FunctionMap.find(F);
124     assert(I != FunctionMap.end() && "Function not in callgraph!");
125     return I->second;
126   }
127
128   /// \brief Returns the call graph node for the provided function.
129   inline CallGraphNode *operator[](const Function *F) {
130     const_iterator I = FunctionMap.find(F);
131     assert(I != FunctionMap.end() && "Function not in callgraph!");
132     return I->second;
133   }
134
135   /// \brief Returns the \c CallGraphNode which is used to represent
136   /// undetermined calls into the callgraph.
137   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
138
139   CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
140
141   /// \brief Returns the root/main method in the module, or some other root
142   /// node, such as the externalcallingnode.
143   CallGraphNode *getRoot() { return Root; }
144   const CallGraphNode *getRoot() const { return Root; }
145
146   //===---------------------------------------------------------------------
147   // Functions to keep a call graph up to date with a function that has been
148   // modified.
149   //
150
151   /// \brief Unlink the function from this module, returning it.
152   ///
153   /// Because this removes the function from the module, the call graph node is
154   /// destroyed.  This is only valid if the function does not call any other
155   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
156   /// this is to dropAllReferences before calling this.
157   Function *removeFunctionFromModule(CallGraphNode *CGN);
158
159   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
160   /// \c F if one does not already exist.
161   CallGraphNode *getOrInsertFunction(const Function *F);
162
163   CallGraph();
164   virtual ~CallGraph() { releaseMemory(); }
165
166   //===---------------------------------------------------------------------
167   // Implementation of the ModulePass interface needed here.
168   //
169
170   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
171   virtual bool runOnModule(Module &M);
172   virtual void releaseMemory();
173
174   void print(raw_ostream &o, const Module *) const;
175   void dump() const;
176 };
177
178 /// \brief A node in the call graph for a module.
179 ///
180 /// Typically represents a function in the call graph. There are also special
181 /// "null" nodes used to represent theoretical entries in the call graph.
182 class CallGraphNode {
183   friend class CallGraph;
184
185   AssertingVH<Function> F;
186
187 public:
188   /// \brief A pair of the calling instruction (a call or invoke)
189   /// and the call graph node being called.
190   typedef std::pair<WeakVH, CallGraphNode*> CallRecord;
191
192 private:
193   std::vector<CallRecord> CalledFunctions;
194
195   /// \brief The number of times that this CallGraphNode occurs in the
196   /// CalledFunctions array of this or other CallGraphNodes.
197   unsigned NumReferences;
198
199   CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
200   void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
201
202   void DropRef() { --NumReferences; }
203   void AddRef() { ++NumReferences; }
204
205 public:
206   typedef std::vector<CallRecord> CalledFunctionsVector;
207
208   /// \brief Creates a node for the specified function.
209   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
210
211   ~CallGraphNode() {
212     assert(NumReferences == 0 && "Node deleted while references remain");
213   }
214
215   typedef std::vector<CallRecord>::iterator iterator;
216   typedef std::vector<CallRecord>::const_iterator const_iterator;
217
218   /// \brief Returns the function that this call graph node represents.
219   Function *getFunction() const { return F; }
220
221   inline iterator begin() { return CalledFunctions.begin(); }
222   inline iterator end()   { return CalledFunctions.end();   }
223   inline const_iterator begin() const { return CalledFunctions.begin(); }
224   inline const_iterator end()   const { return CalledFunctions.end();   }
225   inline bool empty() const { return CalledFunctions.empty(); }
226   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
227
228   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
229   /// reference this node in their callee list.
230   unsigned getNumReferences() const { return NumReferences; }
231
232   /// \brief Returns the i'th called function.
233   CallGraphNode *operator[](unsigned i) const {
234     assert(i < CalledFunctions.size() && "Invalid index");
235     return CalledFunctions[i].second;
236   }
237
238   /// \brief Print out this call graph node.
239   void dump() const;
240   void print(raw_ostream &OS) const;
241
242   //===---------------------------------------------------------------------
243   // Methods to keep a call graph up to date with a function that has been
244   // modified
245   //
246
247   /// \brief Removes all edges from this CallGraphNode to any functions it
248   /// calls.
249   void removeAllCalledFunctions() {
250     while (!CalledFunctions.empty()) {
251       CalledFunctions.back().second->DropRef();
252       CalledFunctions.pop_back();
253     }
254   }
255
256   /// \brief Moves all the callee information from N to this node.
257   void stealCalledFunctionsFrom(CallGraphNode *N) {
258     assert(CalledFunctions.empty() &&
259            "Cannot steal callsite information if I already have some");
260     std::swap(CalledFunctions, N->CalledFunctions);
261   }
262
263   /// \brief Adds a function to the list of functions called by this one.
264   void addCalledFunction(CallSite CS, CallGraphNode *M) {
265     assert(!CS.getInstruction() ||
266            !CS.getCalledFunction() ||
267            !CS.getCalledFunction()->isIntrinsic());
268     CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
269     M->AddRef();
270   }
271
272   void removeCallEdge(iterator I) {
273     I->second->DropRef();
274     *I = CalledFunctions.back();
275     CalledFunctions.pop_back();
276   }
277
278   /// \brief Removes the edge in the node for the specified call site.
279   ///
280   /// Note that this method takes linear time, so it should be used sparingly.
281   void removeCallEdgeFor(CallSite CS);
282
283   /// \brief Removes all call edges from this node to the specified callee
284   /// function.
285   ///
286   /// This takes more time to execute than removeCallEdgeTo, so it should not
287   /// be used unless necessary.
288   void removeAnyCallEdgeTo(CallGraphNode *Callee);
289
290   /// \brief Removes one edge associated with a null callsite from this node to
291   /// the specified callee function.
292   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
293
294   /// \brief Replaces the edge in the node for the specified call site with a
295   /// new one.
296   ///
297   /// Note that this method takes linear time, so it should be used sparingly.
298   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
299
300   /// \brief A special function that should only be used by the CallGraph class.
301   //
302   // FIXME: Make this private?
303   void allReferencesDropped() {
304     NumReferences = 0;
305   }
306 };
307
308 //===----------------------------------------------------------------------===//
309 // GraphTraits specializations for call graphs so that they can be treated as
310 // graphs by the generic graph algorithms.
311 //
312
313 // Provide graph traits for tranversing call graphs using standard graph
314 // traversals.
315 template <> struct GraphTraits<CallGraphNode*> {
316   typedef CallGraphNode NodeType;
317
318   typedef CallGraphNode::CallRecord CGNPairTy;
319   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode*> CGNDerefFun;
320
321   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
322
323   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
324
325   static inline ChildIteratorType child_begin(NodeType *N) {
326     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
327   }
328   static inline ChildIteratorType child_end  (NodeType *N) {
329     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
330   }
331
332   static CallGraphNode *CGNDeref(CGNPairTy P) {
333     return P.second;
334   }
335
336 };
337
338 template <> struct GraphTraits<const CallGraphNode*> {
339   typedef const CallGraphNode NodeType;
340   typedef NodeType::const_iterator ChildIteratorType;
341
342   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
343   static inline ChildIteratorType child_begin(NodeType *N) { return N->begin();}
344   static inline ChildIteratorType child_end  (NodeType *N) { return N->end(); }
345 };
346
347 template<> struct GraphTraits<CallGraph*> : public GraphTraits<CallGraphNode*> {
348   static NodeType *getEntryNode(CallGraph *CGN) {
349     return CGN->getExternalCallingNode();  // Start at the external node!
350   }
351   typedef std::pair<const Function*, CallGraphNode*> PairTy;
352   typedef std::pointer_to_unary_function<PairTy, CallGraphNode&> DerefFun;
353
354   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
355   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
356   static nodes_iterator nodes_begin(CallGraph *CG) {
357     return map_iterator(CG->begin(), DerefFun(CGdereference));
358   }
359   static nodes_iterator nodes_end  (CallGraph *CG) {
360     return map_iterator(CG->end(), DerefFun(CGdereference));
361   }
362
363   static CallGraphNode &CGdereference(PairTy P) {
364     return *P.second;
365   }
366 };
367
368 template<> struct GraphTraits<const CallGraph*> :
369   public GraphTraits<const CallGraphNode*> {
370   static NodeType *getEntryNode(const CallGraph *CGN) {
371     return CGN->getExternalCallingNode();
372   }
373   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
374   typedef CallGraph::const_iterator nodes_iterator;
375   static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
376   static nodes_iterator nodes_end  (const CallGraph *CG) { return CG->end(); }
377 };
378
379 } // End llvm namespace
380
381 // Make sure that any clients of this file link in CallGraph.cpp
382 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)
383
384 #endif