LLVM API Documentation

CallGraph.h
Go to the documentation of this file.
00001 //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 /// \file
00010 ///
00011 /// This file provides interfaces used to build and manipulate a call graph,
00012 /// which is a very useful tool for interprocedural optimization.
00013 ///
00014 /// Every function in a module is represented as a node in the call graph.  The
00015 /// callgraph node keeps track of which functions are called by the function
00016 /// corresponding to the node.
00017 ///
00018 /// A call graph may contain nodes where the function that they correspond to
00019 /// is null.  These 'external' nodes are used to represent control flow that is
00020 /// not represented (or analyzable) in the module.  In particular, this
00021 /// analysis builds one external node such that:
00022 ///   1. All functions in the module without internal linkage will have edges
00023 ///      from this external node, indicating that they could be called by
00024 ///      functions outside of the module.
00025 ///   2. All functions whose address is used for something more than a direct
00026 ///      call, for example being stored into a memory location will also have
00027 ///      an edge from this external node.  Since they may be called by an
00028 ///      unknown caller later, they must be tracked as such.
00029 ///
00030 /// There is a second external node added for calls that leave this module.
00031 /// Functions have a call edge to the external node iff:
00032 ///   1. The function is external, reflecting the fact that they could call
00033 ///      anything without internal linkage or that has its address taken.
00034 ///   2. The function contains an indirect function call.
00035 ///
00036 /// As an extension in the future, there may be multiple nodes with a null
00037 /// function.  These will be used when we can prove (through pointer analysis)
00038 /// that an indirect call site can call only a specific set of functions.
00039 ///
00040 /// Because of these properties, the CallGraph captures a conservative superset
00041 /// of all of the caller-callee relationships, which is useful for
00042 /// transformations.
00043 ///
00044 /// The CallGraph class also attempts to figure out what the root of the
00045 /// CallGraph is, which it currently does by looking for a function named
00046 /// 'main'. If no function named 'main' is found, the external node is used as
00047 /// the entry node, reflecting the fact that any function without internal
00048 /// linkage could be called into (which is common for libraries).
00049 ///
00050 //===----------------------------------------------------------------------===//
00051 
00052 #ifndef LLVM_ANALYSIS_CALLGRAPH_H
00053 #define LLVM_ANALYSIS_CALLGRAPH_H
00054 
00055 #include "llvm/ADT/GraphTraits.h"
00056 #include "llvm/ADT/STLExtras.h"
00057 #include "llvm/IR/CallSite.h"
00058 #include "llvm/IR/Function.h"
00059 #include "llvm/IR/ValueHandle.h"
00060 #include "llvm/Pass.h"
00061 #include <map>
00062 
00063 namespace llvm {
00064 
00065 class Function;
00066 class Module;
00067 class CallGraphNode;
00068 
00069 /// \brief The basic data container for the call graph of a \c Module of IR.
00070 ///
00071 /// This class exposes both the interface to the call graph for a module of IR.
00072 ///
00073 /// The core call graph itself can also be updated to reflect changes to the IR.
00074 class CallGraph {
00075   Module &M;
00076 
00077   typedef std::map<const Function *, CallGraphNode *> FunctionMapTy;
00078 
00079   /// \brief A map from \c Function* to \c CallGraphNode*.
00080   FunctionMapTy FunctionMap;
00081 
00082   /// \brief Root is root of the call graph, or the external node if a 'main'
00083   /// function couldn't be found.
00084   CallGraphNode *Root;
00085 
00086   /// \brief This node has edges to all external functions and those internal
00087   /// functions that have their address taken.
00088   CallGraphNode *ExternalCallingNode;
00089 
00090   /// \brief This node has edges to it from all functions making indirect calls
00091   /// or calling an external function.
00092   CallGraphNode *CallsExternalNode;
00093 
00094   /// \brief Replace the function represented by this node by another.
00095   ///
00096   /// This does not rescan the body of the function, so it is suitable when
00097   /// splicing the body of one function to another while also updating all
00098   /// callers from the old function to the new.
00099   void spliceFunction(const Function *From, const Function *To);
00100 
00101   /// \brief Add a function to the call graph, and link the node to all of the
00102   /// functions that it calls.
00103   void addToCallGraph(Function *F);
00104 
00105 public:
00106   CallGraph(Module &M);
00107   ~CallGraph();
00108 
00109   void print(raw_ostream &OS) const;
00110   void dump() const;
00111 
00112   typedef FunctionMapTy::iterator iterator;
00113   typedef FunctionMapTy::const_iterator const_iterator;
00114 
00115   /// \brief Returns the module the call graph corresponds to.
00116   Module &getModule() const { return M; }
00117 
00118   inline iterator begin() { return FunctionMap.begin(); }
00119   inline iterator end() { return FunctionMap.end(); }
00120   inline const_iterator begin() const { return FunctionMap.begin(); }
00121   inline const_iterator end() const { return FunctionMap.end(); }
00122 
00123   /// \brief Returns the call graph node for the provided function.
00124   inline const CallGraphNode *operator[](const Function *F) const {
00125     const_iterator I = FunctionMap.find(F);
00126     assert(I != FunctionMap.end() && "Function not in callgraph!");
00127     return I->second;
00128   }
00129 
00130   /// \brief Returns the call graph node for the provided function.
00131   inline CallGraphNode *operator[](const Function *F) {
00132     const_iterator I = FunctionMap.find(F);
00133     assert(I != FunctionMap.end() && "Function not in callgraph!");
00134     return I->second;
00135   }
00136 
00137   /// \brief Returns the \c CallGraphNode which is used to represent
00138   /// undetermined calls into the callgraph.
00139   CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
00140 
00141   CallGraphNode *getCallsExternalNode() const { return CallsExternalNode; }
00142 
00143   //===---------------------------------------------------------------------
00144   // Functions to keep a call graph up to date with a function that has been
00145   // modified.
00146   //
00147 
00148   /// \brief Unlink the function from this module, returning it.
00149   ///
00150   /// Because this removes the function from the module, the call graph node is
00151   /// destroyed.  This is only valid if the function does not call any other
00152   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
00153   /// this is to dropAllReferences before calling this.
00154   Function *removeFunctionFromModule(CallGraphNode *CGN);
00155 
00156   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
00157   /// \c F if one does not already exist.
00158   CallGraphNode *getOrInsertFunction(const Function *F);
00159 };
00160 
00161 /// \brief A node in the call graph for a module.
00162 ///
00163 /// Typically represents a function in the call graph. There are also special
00164 /// "null" nodes used to represent theoretical entries in the call graph.
00165 class CallGraphNode {
00166 public:
00167   /// \brief A pair of the calling instruction (a call or invoke)
00168   /// and the call graph node being called.
00169   typedef std::pair<WeakVH, CallGraphNode *> CallRecord;
00170 
00171 public:
00172   typedef std::vector<CallRecord> CalledFunctionsVector;
00173 
00174   /// \brief Creates a node for the specified function.
00175   inline CallGraphNode(Function *F) : F(F), NumReferences(0) {}
00176 
00177   ~CallGraphNode() {
00178     assert(NumReferences == 0 && "Node deleted while references remain");
00179   }
00180 
00181   typedef std::vector<CallRecord>::iterator iterator;
00182   typedef std::vector<CallRecord>::const_iterator const_iterator;
00183 
00184   /// \brief Returns the function that this call graph node represents.
00185   Function *getFunction() const { return F; }
00186 
00187   inline iterator begin() { return CalledFunctions.begin(); }
00188   inline iterator end() { return CalledFunctions.end(); }
00189   inline const_iterator begin() const { return CalledFunctions.begin(); }
00190   inline const_iterator end() const { return CalledFunctions.end(); }
00191   inline bool empty() const { return CalledFunctions.empty(); }
00192   inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
00193 
00194   /// \brief Returns the number of other CallGraphNodes in this CallGraph that
00195   /// reference this node in their callee list.
00196   unsigned getNumReferences() const { return NumReferences; }
00197 
00198   /// \brief Returns the i'th called function.
00199   CallGraphNode *operator[](unsigned i) const {
00200     assert(i < CalledFunctions.size() && "Invalid index");
00201     return CalledFunctions[i].second;
00202   }
00203 
00204   /// \brief Print out this call graph node.
00205   void dump() const;
00206   void print(raw_ostream &OS) const;
00207 
00208   //===---------------------------------------------------------------------
00209   // Methods to keep a call graph up to date with a function that has been
00210   // modified
00211   //
00212 
00213   /// \brief Removes all edges from this CallGraphNode to any functions it
00214   /// calls.
00215   void removeAllCalledFunctions() {
00216     while (!CalledFunctions.empty()) {
00217       CalledFunctions.back().second->DropRef();
00218       CalledFunctions.pop_back();
00219     }
00220   }
00221 
00222   /// \brief Moves all the callee information from N to this node.
00223   void stealCalledFunctionsFrom(CallGraphNode *N) {
00224     assert(CalledFunctions.empty() &&
00225            "Cannot steal callsite information if I already have some");
00226     std::swap(CalledFunctions, N->CalledFunctions);
00227   }
00228 
00229   /// \brief Adds a function to the list of functions called by this one.
00230   void addCalledFunction(CallSite CS, CallGraphNode *M) {
00231     assert(!CS.getInstruction() || !CS.getCalledFunction() ||
00232            !CS.getCalledFunction()->isIntrinsic());
00233     CalledFunctions.push_back(std::make_pair(CS.getInstruction(), M));
00234     M->AddRef();
00235   }
00236 
00237   void removeCallEdge(iterator I) {
00238     I->second->DropRef();
00239     *I = CalledFunctions.back();
00240     CalledFunctions.pop_back();
00241   }
00242 
00243   /// \brief Removes the edge in the node for the specified call site.
00244   ///
00245   /// Note that this method takes linear time, so it should be used sparingly.
00246   void removeCallEdgeFor(CallSite CS);
00247 
00248   /// \brief Removes all call edges from this node to the specified callee
00249   /// function.
00250   ///
00251   /// This takes more time to execute than removeCallEdgeTo, so it should not
00252   /// be used unless necessary.
00253   void removeAnyCallEdgeTo(CallGraphNode *Callee);
00254 
00255   /// \brief Removes one edge associated with a null callsite from this node to
00256   /// the specified callee function.
00257   void removeOneAbstractEdgeTo(CallGraphNode *Callee);
00258 
00259   /// \brief Replaces the edge in the node for the specified call site with a
00260   /// new one.
00261   ///
00262   /// Note that this method takes linear time, so it should be used sparingly.
00263   void replaceCallEdge(CallSite CS, CallSite NewCS, CallGraphNode *NewNode);
00264 
00265 private:
00266   friend class CallGraph;
00267 
00268   AssertingVH<Function> F;
00269 
00270   std::vector<CallRecord> CalledFunctions;
00271 
00272   /// \brief The number of times that this CallGraphNode occurs in the
00273   /// CalledFunctions array of this or other CallGraphNodes.
00274   unsigned NumReferences;
00275 
00276   CallGraphNode(const CallGraphNode &) LLVM_DELETED_FUNCTION;
00277   void operator=(const CallGraphNode &) LLVM_DELETED_FUNCTION;
00278 
00279   void DropRef() { --NumReferences; }
00280   void AddRef() { ++NumReferences; }
00281 
00282   /// \brief A special function that should only be used by the CallGraph class.
00283   void allReferencesDropped() { NumReferences = 0; }
00284 };
00285 
00286 /// \brief An analysis pass to compute the \c CallGraph for a \c Module.
00287 ///
00288 /// This class implements the concept of an analysis pass used by the \c
00289 /// ModuleAnalysisManager to run an analysis over a module and cache the
00290 /// resulting data.
00291 class CallGraphAnalysis {
00292 public:
00293   /// \brief A formulaic typedef to inform clients of the result type.
00294   typedef CallGraph Result;
00295 
00296   static void *ID() { return (void *)&PassID; }
00297 
00298   /// \brief Compute the \c CallGraph for the module \c M.
00299   ///
00300   /// The real work here is done in the \c CallGraph constructor.
00301   CallGraph run(Module *M) { return CallGraph(*M); }
00302 
00303 private:
00304   static char PassID;
00305 };
00306 
00307 /// \brief The \c ModulePass which wraps up a \c CallGraph and the logic to
00308 /// build it.
00309 ///
00310 /// This class exposes both the interface to the call graph container and the
00311 /// module pass which runs over a module of IR and produces the call graph. The
00312 /// call graph interface is entirelly a wrapper around a \c CallGraph object
00313 /// which is stored internally for each module.
00314 class CallGraphWrapperPass : public ModulePass {
00315   std::unique_ptr<CallGraph> G;
00316 
00317 public:
00318   static char ID; // Class identification, replacement for typeinfo
00319 
00320   CallGraphWrapperPass();
00321   virtual ~CallGraphWrapperPass();
00322 
00323   /// \brief The internal \c CallGraph around which the rest of this interface
00324   /// is wrapped.
00325   const CallGraph &getCallGraph() const { return *G; }
00326   CallGraph &getCallGraph() { return *G; }
00327 
00328   typedef CallGraph::iterator iterator;
00329   typedef CallGraph::const_iterator const_iterator;
00330 
00331   /// \brief Returns the module the call graph corresponds to.
00332   Module &getModule() const { return G->getModule(); }
00333 
00334   inline iterator begin() { return G->begin(); }
00335   inline iterator end() { return G->end(); }
00336   inline const_iterator begin() const { return G->begin(); }
00337   inline const_iterator end() const { return G->end(); }
00338 
00339   /// \brief Returns the call graph node for the provided function.
00340   inline const CallGraphNode *operator[](const Function *F) const {
00341     return (*G)[F];
00342   }
00343 
00344   /// \brief Returns the call graph node for the provided function.
00345   inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
00346 
00347   /// \brief Returns the \c CallGraphNode which is used to represent
00348   /// undetermined calls into the callgraph.
00349   CallGraphNode *getExternalCallingNode() const {
00350     return G->getExternalCallingNode();
00351   }
00352 
00353   CallGraphNode *getCallsExternalNode() const {
00354     return G->getCallsExternalNode();
00355   }
00356 
00357   //===---------------------------------------------------------------------
00358   // Functions to keep a call graph up to date with a function that has been
00359   // modified.
00360   //
00361 
00362   /// \brief Unlink the function from this module, returning it.
00363   ///
00364   /// Because this removes the function from the module, the call graph node is
00365   /// destroyed.  This is only valid if the function does not call any other
00366   /// functions (ie, there are no edges in it's CGN).  The easiest way to do
00367   /// this is to dropAllReferences before calling this.
00368   Function *removeFunctionFromModule(CallGraphNode *CGN) {
00369     return G->removeFunctionFromModule(CGN);
00370   }
00371 
00372   /// \brief Similar to operator[], but this will insert a new CallGraphNode for
00373   /// \c F if one does not already exist.
00374   CallGraphNode *getOrInsertFunction(const Function *F) {
00375     return G->getOrInsertFunction(F);
00376   }
00377 
00378   //===---------------------------------------------------------------------
00379   // Implementation of the ModulePass interface needed here.
00380   //
00381 
00382   void getAnalysisUsage(AnalysisUsage &AU) const override;
00383   bool runOnModule(Module &M) override;
00384   void releaseMemory() override;
00385 
00386   void print(raw_ostream &o, const Module *) const override;
00387   void dump() const;
00388 };
00389 
00390 //===----------------------------------------------------------------------===//
00391 // GraphTraits specializations for call graphs so that they can be treated as
00392 // graphs by the generic graph algorithms.
00393 //
00394 
00395 // Provide graph traits for tranversing call graphs using standard graph
00396 // traversals.
00397 template <> struct GraphTraits<CallGraphNode *> {
00398   typedef CallGraphNode NodeType;
00399 
00400   typedef CallGraphNode::CallRecord CGNPairTy;
00401   typedef std::pointer_to_unary_function<CGNPairTy, CallGraphNode *>
00402   CGNDerefFun;
00403 
00404   static NodeType *getEntryNode(CallGraphNode *CGN) { return CGN; }
00405 
00406   typedef mapped_iterator<NodeType::iterator, CGNDerefFun> ChildIteratorType;
00407 
00408   static inline ChildIteratorType child_begin(NodeType *N) {
00409     return map_iterator(N->begin(), CGNDerefFun(CGNDeref));
00410   }
00411   static inline ChildIteratorType child_end(NodeType *N) {
00412     return map_iterator(N->end(), CGNDerefFun(CGNDeref));
00413   }
00414 
00415   static CallGraphNode *CGNDeref(CGNPairTy P) { return P.second; }
00416 };
00417 
00418 template <> struct GraphTraits<const CallGraphNode *> {
00419   typedef const CallGraphNode NodeType;
00420   typedef NodeType::const_iterator ChildIteratorType;
00421 
00422   static NodeType *getEntryNode(const CallGraphNode *CGN) { return CGN; }
00423   static inline ChildIteratorType child_begin(NodeType *N) {
00424     return N->begin();
00425   }
00426   static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
00427 };
00428 
00429 template <>
00430 struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
00431   static NodeType *getEntryNode(CallGraph *CGN) {
00432     return CGN->getExternalCallingNode(); // Start at the external node!
00433   }
00434   typedef std::pair<const Function *, CallGraphNode *> PairTy;
00435   typedef std::pointer_to_unary_function<PairTy, CallGraphNode &> DerefFun;
00436 
00437   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
00438   typedef mapped_iterator<CallGraph::iterator, DerefFun> nodes_iterator;
00439   static nodes_iterator nodes_begin(CallGraph *CG) {
00440     return map_iterator(CG->begin(), DerefFun(CGdereference));
00441   }
00442   static nodes_iterator nodes_end(CallGraph *CG) {
00443     return map_iterator(CG->end(), DerefFun(CGdereference));
00444   }
00445 
00446   static CallGraphNode &CGdereference(PairTy P) { return *P.second; }
00447 };
00448 
00449 template <>
00450 struct GraphTraits<const CallGraph *> : public GraphTraits<
00451                                             const CallGraphNode *> {
00452   static NodeType *getEntryNode(const CallGraph *CGN) {
00453     return CGN->getExternalCallingNode();
00454   }
00455   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
00456   typedef CallGraph::const_iterator nodes_iterator;
00457   static nodes_iterator nodes_begin(const CallGraph *CG) { return CG->begin(); }
00458   static nodes_iterator nodes_end(const CallGraph *CG) { return CG->end(); }
00459 };
00460 
00461 } // End llvm namespace
00462 
00463 #endif