[PM] Reformat this file with clang-format. Mostly fixes inconsistent
[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() || !CS.getCalledFunction() ||
266            !CS.getCalledFunction()->isIntrinsic());
267     CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
268     M->AddRef();
269   }
270
271   void removeCallEdge(iterator I) {
272     I->second->DropRef();
273     *I = CalledFunctions.back();
274     CalledFunctions.pop_back();
275   }
276
277   /// \brief Removes the edge in the node for the specified call site.
278   ///
279   /// Note that this method takes linear time, so it should be used sparingly.
280   void removeCallEdgeFor(CallSite CS);
281
282   /// \brief Removes all call edges from this node to the specified callee
283   /// function.
284   ///
285   /// This takes more time to execute than removeCallEdgeTo, so it should not
286   /// be used unless necessary.
287   void removeAnyCallEdgeTo(CallGraphNode *Callee);
288
289   /// \brief Removes one edge associated with a null callsite from this node to
290   /// the specified callee function.
291   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
292
293   /// \brief Replaces the edge in the node for the specified call site with a
294   /// new one.
295   ///
296   /// Note that this method takes linear time, so it should be used sparingly.
297   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
298
299   /// \brief A special function that should only be used by the CallGraph class.
300   //
301   // FIXME: Make this private?
302   void allReferencesDropped() { NumReferences = 0; }
303 };
304
305 //===----------------------------------------------------------------------===//
306 // GraphTraits specializations for call graphs so that they can be treated as
307 // graphs by the generic graph algorithms.
308 //
309
310 // Provide graph traits for tranversing call graphs using standard graph
311 // traversals.
312 template <> struct GraphTraits<CallGraphNode *> {
313   typedef CallGraphNode NodeType;
314
315   typedef CallGraphNode::CallRecord CGNPairTy;
316   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
317   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) { return P.second; }
331 };
332
333 template <> struct GraphTraits<const CallGraphNode *> {
334   typedef const CallGraphNode NodeType;
335   typedef NodeType::const_iterator ChildIteratorType;
336
337   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
338   static inline ChildIteratorType child_begin(NodeType *N) {
339     return N->begin();
340   }
341   static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
342 };
343
344 template <>
345 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) { return *P.second; }
362 };
363
364 template <>
365 struct GraphTraits<const CallGraph *> : public GraphTraits<
366                                             const CallGraphNode *> {
367   static NodeType *getEntryNode(const CallGraph *CGN) {
368     return CGN->getExternalCallingNode();
369   }
370   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
371   typedef CallGraph::const_iterator nodes_iterator;
372   static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
373   static nodes_iterator nodes_end(const CallGraph *CG) { return CG->end(); }
374 };
375
376 } // End llvm namespace
377
378 // Make sure that any clients of this file link in CallGraph.cpp
379 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)
380
381 #endif