1 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file provides interfaces used to build and manipulate a call graph,
12 /// which is a very useful tool for interprocedural optimization.
14 /// Every function in a module is represented as a node in the call graph. The
15 /// callgraph node keeps track of which functions the are called by the
16 /// function corresponding to the node.
18 /// A call graph may contain nodes where the function that they correspond to
19 /// is null. These 'external' nodes are used to represent control flow that is
20 /// not represented (or analyzable) in the module. In particular, this
21 /// analysis builds one external node such that:
22 /// 1. All functions in the module without internal linkage will have edges
23 /// from this external node, indicating that they could be called by
24 /// functions outside of the module.
25 /// 2. All functions whose address is used for something more than a direct
26 /// call, for example being stored into a memory location will also have
27 /// an edge from this external node. Since they may be called by an
28 /// unknown caller later, they must be tracked as such.
30 /// There is a second external node added for calls that leave this module.
31 /// Functions have a call edge to the external node iff:
32 /// 1. The function is external, reflecting the fact that they could call
33 /// anything without internal linkage or that has its address taken.
34 /// 2. The function contains an indirect function call.
36 /// As an extension in the future, there may be multiple nodes with a null
37 /// function. These will be used when we can prove (through pointer analysis)
38 /// that an indirect call site can call only a specific set of functions.
40 /// Because of these properties, the CallGraph captures a conservative superset
41 /// of all of the caller-callee relationships, which is useful for
44 /// The CallGraph class also attempts to figure out what the root of the
45 /// CallGraph is, which it currently does by looking for a function named
46 /// 'main'. If no function named 'main' is found, the external node is used as
47 /// the entry node, reflecting the fact that any function without internal
48 /// linkage could be called into (which is common for libraries).
50 //===----------------------------------------------------------------------===//
52 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
53 #define LLVM_ANALYSIS_CALLGRAPH_H
55 #include "llvm/ADT/GraphTraits.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/Pass.h"
59 #include "llvm/Support/CallSite.h"
60 #include "llvm/Support/IncludeFile.h"
61 #include "llvm/Support/ValueHandle.h"
70 /// \brief The basic data container for the call graph and the \c ModulePass
71 /// which produces it.
73 /// This class exposes both the interface to the call graph container and the
74 /// module pass which runs over a module of IR and produces the call graph.
76 /// The core call graph itself can also be updated to reflect changes to the IR.
77 class CallGraph : public ModulePass {
80 typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
82 /// \brief A map from \c Function* to \c CallGraphNode*.
83 FunctionMapTy FunctionMap;
85 /// \brief Root is root of the call graph, or the external node if a 'main'
86 /// function couldn't be found.
89 /// \brief This node has edges to all external functions and those internal
90 /// functions that have their address taken.
91 CallGraphNode *ExternalCallingNode;
93 /// \brief This node has edges to it from all functions making indirect calls
94 /// or calling an external function.
95 CallGraphNode *CallsExternalNode;
97 /// \brief Replace the function represented by this node by another.
99 /// This does not rescan the body of the function, so it is suitable when
100 /// splicing the body of one function to another while also updating all
101 /// callers from the old function to the new.
102 void spliceFunction(const Function *From, const Function *To);
104 /// \brief Add a function to the call graph, and link the node to all of the
105 /// functions that it calls.
106 void addToCallGraph(Function *F);
109 static char ID; // Class identification, replacement for typeinfo
111 typedef FunctionMapTy::iterator iterator;
112 typedef FunctionMapTy::const_iterator const_iterator;
114 /// \brief Returns the module the call graph corresponds to.
115 Module &getModule() const { return *M; }
117 inline iterator begin() { return FunctionMap.begin(); }
118 inline iterator end() { return FunctionMap.end(); }
119 inline const_iterator begin() const { return FunctionMap.begin(); }
120 inline const_iterator end() const { return FunctionMap.end(); }
122 /// \brief Returns the call graph node for the provided function.
123 inline const CallGraphNode *operator[](const Function *F) const {
124 const_iterator I = FunctionMap.find(F);
125 assert(I != FunctionMap.end() && "Function not in callgraph!");
129 /// \brief Returns the call graph node for the provided function.
130 inline CallGraphNode *operator[](const Function *F) {
131 const_iterator I = FunctionMap.find(F);
132 assert(I != FunctionMap.end() && "Function not in callgraph!");
136 /// \brief Returns the \c CallGraphNode which is used to represent
137 /// undetermined calls into the callgraph.
138 CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
140 CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
142 /// \brief Returns the root/main method in the module, or some other root
143 /// node, such as the externalcallingnode.
144 CallGraphNode *getRoot() { return Root; }
145 const CallGraphNode *getRoot() const { return Root; }
147 //===---------------------------------------------------------------------
148 // Functions to keep a call graph up to date with a function that has been
152 /// \brief Unlink the function from this module, returning it.
154 /// Because this removes the function from the module, the call graph node is
155 /// destroyed. This is only valid if the function does not call any other
156 /// functions (ie, there are no edges in it's CGN). The easiest way to do
157 /// this is to dropAllReferences before calling this.
158 Function *removeFunctionFromModule(CallGraphNode *CGN);
160 /// \brief Similar to operator[], but this will insert a new CallGraphNode for
161 /// \c F if one does not already exist.
162 CallGraphNode *getOrInsertFunction(const Function *F);
165 virtual ~CallGraph() { releaseMemory(); }
167 //===---------------------------------------------------------------------
168 // Implementation of the ModulePass interface needed here.
171 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
172 virtual bool runOnModule(Module &M);
173 virtual void releaseMemory();
175 void print(raw_ostream &o, const Module *) const;
179 /// \brief A node in the call graph for a module.
181 /// Typically represents a function in the call graph. There are also special
182 /// "null" nodes used to represent theoretical entries in the call graph.
183 class CallGraphNode {
184 friend class CallGraph;
186 AssertingVH<Function> F;
189 /// \brief A pair of the calling instruction (a call or invoke)
190 /// and the call graph node being called.
191 typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
194 std::vector<CallRecord> CalledFunctions;
196 /// \brief The number of times that this CallGraphNode occurs in the
197 /// CalledFunctions array of this or other CallGraphNodes.
198 unsigned NumReferences;
200 CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
201 void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
203 void DropRef() { --NumReferences; }
204 void AddRef() { ++NumReferences; }
207 typedef std::vector<CallRecord> CalledFunctionsVector;
209 /// \brief Creates a node for the specified function.
210 inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
213 assert(NumReferences == 0 && "Node deleted while references remain");
216 typedef std::vector<CallRecord>::iterator iterator;
217 typedef std::vector<CallRecord>::const_iterator const_iterator;
219 /// \brief Returns the function that this call graph node represents.
220 Function *getFunction() const { return F; }
222 inline iterator begin() { return CalledFunctions.begin(); }
223 inline iterator end() { return CalledFunctions.end(); }
224 inline const_iterator begin() const { return CalledFunctions.begin(); }
225 inline const_iterator end() const { return CalledFunctions.end(); }
226 inline bool empty() const { return CalledFunctions.empty(); }
227 inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
229 /// \brief Returns the number of other CallGraphNodes in this CallGraph that
230 /// reference this node in their callee list.
231 unsigned getNumReferences() const { return NumReferences; }
233 /// \brief Returns the i'th called function.
234 CallGraphNode *operator[](unsigned i) const {
235 assert(i < CalledFunctions.size() && "Invalid index");
236 return CalledFunctions[i].second;
239 /// \brief Print out this call graph node.
241 void print(raw_ostream &OS) const;
243 //===---------------------------------------------------------------------
244 // Methods to keep a call graph up to date with a function that has been
248 /// \brief Removes all edges from this CallGraphNode to any functions it
250 void removeAllCalledFunctions() {
251 while (!CalledFunctions.empty()) {
252 CalledFunctions.back().second->DropRef();
253 CalledFunctions.pop_back();
257 /// \brief Moves all the callee information from N to this node.
258 void stealCalledFunctionsFrom(CallGraphNode *N) {
259 assert(CalledFunctions.empty() &&
260 "Cannot steal callsite information if I already have some");
261 std::swap(CalledFunctions, N->CalledFunctions);
264 /// \brief Adds a function to the list of functions called by this one.
265 void addCalledFunction(CallSite CS, CallGraphNode *M) {
266 assert(!CS.getInstruction() || !CS.getCalledFunction() ||
267 !CS.getCalledFunction()->isIntrinsic());
268 CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
272 void removeCallEdge(iterator I) {
273 I->second->DropRef();
274 *I = CalledFunctions.back();
275 CalledFunctions.pop_back();
278 /// \brief Removes the edge in the node for the specified call site.
280 /// Note that this method takes linear time, so it should be used sparingly.
281 void removeCallEdgeFor(CallSite CS);
283 /// \brief Removes all call edges from this node to the specified callee
286 /// This takes more time to execute than removeCallEdgeTo, so it should not
287 /// be used unless necessary.
288 void removeAnyCallEdgeTo(CallGraphNode *Callee);
290 /// \brief Removes one edge associated with a null callsite from this node to
291 /// the specified callee function.
292 void removeOneAbstractEdgeTo(CallGraphNode *Callee);
294 /// \brief Replaces the edge in the node for the specified call site with a
297 /// Note that this method takes linear time, so it should be used sparingly.
298 void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
300 /// \brief A special function that should only be used by the CallGraph class.
302 // FIXME: Make this private?
303 void allReferencesDropped() { NumReferences = 0; }
306 //===----------------------------------------------------------------------===//
307 // GraphTraits specializations for call graphs so that they can be treated as
308 // graphs by the generic graph algorithms.
311 // Provide graph traits for tranversing call graphs using standard graph
313 template <> struct GraphTraits<CallGraphNode *> {
314 typedef CallGraphNode NodeType;
316 typedef CallGraphNode::CallRecord CGNPairTy;
317 typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
320 static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
322 typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
324 static inline ChildIteratorType child_begin(NodeType *N) {
325 return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
327 static inline ChildIteratorType child_end(NodeType *N) {
328 return map_iterator(N->end(), CGNDerefFun(CGNDeref));
331 static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
334 template <> struct GraphTraits<const CallGraphNode *> {
335 typedef const CallGraphNode NodeType;
336 typedef NodeType::const_iterator ChildIteratorType;
338 static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
339 static inline ChildIteratorType child_begin(NodeType *N) {
342 static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
346 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
347 static NodeType *getEntryNode(CallGraph *CGN) {
348 return CGN->getExternalCallingNode(); // Start at the external node!
350 typedef std::pair<const Function *, CallGraphNode *> PairTy;
351 typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun;
353 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
354 typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
355 static nodes_iterator nodes_begin(CallGraph *CG) {
356 return map_iterator(CG->begin(), DerefFun(CGdereference));
358 static nodes_iterator nodes_end(CallGraph *CG) {
359 return map_iterator(CG->end(), DerefFun(CGdereference));
362 static CallGraphNode &CGdereference(PairTy P) { return *P.second; }
366 struct GraphTraits<const CallGraph *> : public GraphTraits<
367 const CallGraphNode *> {
368 static NodeType *getEntryNode(const CallGraph *CGN) {
369 return CGN->getExternalCallingNode();
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(); }
377 } // End llvm namespace
379 // Make sure that any clients of this file link in CallGraph.cpp
380 FORCE_DEFINING_FILE_TO_BE_LINKED(CallGraph)