LLVM API Documentation

CallGraph.cpp
Go to the documentation of this file.
00001 //===- CallGraph.cpp - Build a Module's call graph ------------------------===//
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 //
00010 // This file implements the CallGraph class and provides the BasicCallGraph
00011 // default implementation.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Analysis/CallGraph.h"
00016 #include "llvm/IR/Instructions.h"
00017 #include "llvm/IR/IntrinsicInst.h"
00018 #include "llvm/IR/Module.h"
00019 #include "llvm/Support/CallSite.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/raw_ostream.h"
00022 using namespace llvm;
00023 
00024 namespace {
00025 
00026 //===----------------------------------------------------------------------===//
00027 // BasicCallGraph class definition
00028 //
00029 class BasicCallGraph : public ModulePass, public CallGraph {
00030   // Root is root of the call graph, or the external node if a 'main' function
00031   // couldn't be found.
00032   //
00033   CallGraphNode *Root;
00034 
00035   // ExternalCallingNode - This node has edges to all external functions and
00036   // those internal functions that have their address taken.
00037   CallGraphNode *ExternalCallingNode;
00038 
00039   // CallsExternalNode - This node has edges to it from all functions making
00040   // indirect calls or calling an external function.
00041   CallGraphNode *CallsExternalNode;
00042 
00043 public:
00044   static char ID; // Class identification, replacement for typeinfo
00045   BasicCallGraph() : ModulePass(ID), Root(0), 
00046     ExternalCallingNode(0), CallsExternalNode(0) {
00047       initializeBasicCallGraphPass(*PassRegistry::getPassRegistry());
00048     }
00049 
00050   // runOnModule - Compute the call graph for the specified module.
00051   virtual bool runOnModule(Module &M) {
00052     CallGraph::initialize(M);
00053     
00054     ExternalCallingNode = getOrInsertFunction(0);
00055     CallsExternalNode = new CallGraphNode(0);
00056     Root = 0;
00057   
00058     // Add every function to the call graph.
00059     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
00060       addToCallGraph(I);
00061   
00062     // If we didn't find a main function, use the external call graph node
00063     if (Root == 0) Root = ExternalCallingNode;
00064     
00065     return false;
00066   }
00067 
00068   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00069     AU.setPreservesAll();
00070   }
00071 
00072   virtual void print(raw_ostream &OS, const Module *) const {
00073     OS << "CallGraph Root is: ";
00074     if (Function *F = getRoot()->getFunction())
00075       OS << F->getName() << "\n";
00076     else {
00077       OS << "<<null function: 0x" << getRoot() << ">>\n";
00078     }
00079     
00080     CallGraph::print(OS, 0);
00081   }
00082 
00083   virtual void releaseMemory() {
00084     destroy();
00085   }
00086   
00087   /// getAdjustedAnalysisPointer - This method is used when a pass implements
00088   /// an analysis interface through multiple inheritance.  If needed, it should
00089   /// override this to adjust the this pointer as needed for the specified pass
00090   /// info.
00091   virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
00092     if (PI == &CallGraph::ID)
00093       return (CallGraph*)this;
00094     return this;
00095   }
00096   
00097   CallGraphNode* getExternalCallingNode() const { return ExternalCallingNode; }
00098   CallGraphNode* getCallsExternalNode()   const { return CallsExternalNode; }
00099 
00100   // getRoot - Return the root of the call graph, which is either main, or if
00101   // main cannot be found, the external node.
00102   //
00103   CallGraphNode *getRoot()             { return Root; }
00104   const CallGraphNode *getRoot() const { return Root; }
00105 
00106 private:
00107   //===---------------------------------------------------------------------
00108   // Implementation of CallGraph construction
00109   //
00110 
00111   // addToCallGraph - Add a function to the call graph, and link the node to all
00112   // of the functions that it calls.
00113   //
00114   void addToCallGraph(Function *F) {
00115     CallGraphNode *Node = getOrInsertFunction(F);
00116 
00117     // If this function has external linkage, anything could call it.
00118     if (!F->hasLocalLinkage()) {
00119       ExternalCallingNode->addCalledFunction(CallSite(), Node);
00120 
00121       // Found the entry point?
00122       if (F->getName() == "main") {
00123         if (Root)    // Found multiple external mains?  Don't pick one.
00124           Root = ExternalCallingNode;
00125         else
00126           Root = Node;          // Found a main, keep track of it!
00127       }
00128     }
00129 
00130     // If this function has its address taken, anything could call it.
00131     if (F->hasAddressTaken())
00132       ExternalCallingNode->addCalledFunction(CallSite(), Node);
00133 
00134     // If this function is not defined in this translation unit, it could call
00135     // anything.
00136     if (F->isDeclaration() && !F->isIntrinsic())
00137       Node->addCalledFunction(CallSite(), CallsExternalNode);
00138 
00139     // Look for calls by this function.
00140     for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
00141       for (BasicBlock::iterator II = BB->begin(), IE = BB->end();
00142            II != IE; ++II) {
00143         CallSite CS(cast<Value>(II));
00144         if (CS) {
00145           const Function *Callee = CS.getCalledFunction();
00146           if (!Callee)
00147             // Indirect calls of intrinsics are not allowed so no need to check.
00148             Node->addCalledFunction(CS, CallsExternalNode);
00149           else if (!Callee->isIntrinsic())
00150             Node->addCalledFunction(CS, getOrInsertFunction(Callee));
00151         }
00152       }
00153   }
00154 
00155   //
00156   // destroy - Release memory for the call graph
00157   virtual void destroy() {
00158     /// CallsExternalNode is not in the function map, delete it explicitly.
00159     if (CallsExternalNode) {
00160       CallsExternalNode->allReferencesDropped();
00161       delete CallsExternalNode;
00162       CallsExternalNode = 0;
00163     }
00164     CallGraph::destroy();
00165   }
00166 };
00167 
00168 } //End anonymous namespace
00169 
00170 INITIALIZE_ANALYSIS_GROUP(CallGraph, "Call Graph", BasicCallGraph)
00171 INITIALIZE_AG_PASS(BasicCallGraph, CallGraph, "basiccg",
00172                    "Basic CallGraph Construction", false, true, true)
00173 
00174 char CallGraph::ID = 0;
00175 char BasicCallGraph::ID = 0;
00176 
00177 void CallGraph::initialize(Module &M) {
00178   Mod = &M;
00179 }
00180 
00181 void CallGraph::destroy() {
00182   if (FunctionMap.empty()) return;
00183   
00184   // Reset all node's use counts to zero before deleting them to prevent an
00185   // assertion from firing.
00186 #ifndef NDEBUG
00187   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
00188        I != E; ++I)
00189     I->second->allReferencesDropped();
00190 #endif
00191   
00192   for (FunctionMapTy::iterator I = FunctionMap.begin(), E = FunctionMap.end();
00193       I != E; ++I)
00194     delete I->second;
00195   FunctionMap.clear();
00196 }
00197 
00198 void CallGraph::print(raw_ostream &OS, Module*) const {
00199   for (CallGraph::const_iterator I = begin(), E = end(); I != E; ++I)
00200     I->second->print(OS);
00201 }
00202 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00203 void CallGraph::dump() const {
00204   print(dbgs(), 0);
00205 }
00206 #endif
00207 
00208 //===----------------------------------------------------------------------===//
00209 // Implementations of public modification methods
00210 //
00211 
00212 // removeFunctionFromModule - Unlink the function from this module, returning
00213 // it.  Because this removes the function from the module, the call graph node
00214 // is destroyed.  This is only valid if the function does not call any other
00215 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
00216 // is to dropAllReferences before calling this.
00217 //
00218 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
00219   assert(CGN->empty() && "Cannot remove function from call "
00220          "graph if it references other functions!");
00221   Function *F = CGN->getFunction(); // Get the function for the call graph node
00222   delete CGN;                       // Delete the call graph node for this func
00223   FunctionMap.erase(F);             // Remove the call graph node from the map
00224 
00225   Mod->getFunctionList().remove(F);
00226   return F;
00227 }
00228 
00229 /// spliceFunction - Replace the function represented by this node by another.
00230 /// This does not rescan the body of the function, so it is suitable when
00231 /// splicing the body of the old function to the new while also updating all
00232 /// callers from old to new.
00233 ///
00234 void CallGraph::spliceFunction(const Function *From, const Function *To) {
00235   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
00236   assert(!FunctionMap.count(To) &&
00237          "Pointing CallGraphNode at a function that already exists");
00238   FunctionMapTy::iterator I = FunctionMap.find(From);
00239   I->second->F = const_cast<Function*>(To);
00240   FunctionMap[To] = I->second;
00241   FunctionMap.erase(I);
00242 }
00243 
00244 // getOrInsertFunction - This method is identical to calling operator[], but
00245 // it will insert a new CallGraphNode for the specified function if one does
00246 // not already exist.
00247 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
00248   CallGraphNode *&CGN = FunctionMap[F];
00249   if (CGN) return CGN;
00250   
00251   assert((!F || F->getParent() == Mod) && "Function not in current module!");
00252   return CGN = new CallGraphNode(const_cast<Function*>(F));
00253 }
00254 
00255 void CallGraphNode::print(raw_ostream &OS) const {
00256   if (Function *F = getFunction())
00257     OS << "Call graph node for function: '" << F->getName() << "'";
00258   else
00259     OS << "Call graph node <<null function>>";
00260   
00261   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
00262 
00263   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00264     OS << "  CS<" << I->first << "> calls ";
00265     if (Function *FI = I->second->getFunction())
00266       OS << "function '" << FI->getName() <<"'\n";
00267     else
00268       OS << "external node\n";
00269   }
00270   OS << '\n';
00271 }
00272 
00273 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00274 void CallGraphNode::dump() const { print(dbgs()); }
00275 #endif
00276 
00277 /// removeCallEdgeFor - This method removes the edge in the node for the
00278 /// specified call site.  Note that this method takes linear time, so it
00279 /// should be used sparingly.
00280 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
00281   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00282     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00283     if (I->first == CS.getInstruction()) {
00284       I->second->DropRef();
00285       *I = CalledFunctions.back();
00286       CalledFunctions.pop_back();
00287       return;
00288     }
00289   }
00290 }
00291 
00292 // removeAnyCallEdgeTo - This method removes any call edges from this node to
00293 // the specified callee function.  This takes more time to execute than
00294 // removeCallEdgeTo, so it should not be used unless necessary.
00295 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
00296   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
00297     if (CalledFunctions[i].second == Callee) {
00298       Callee->DropRef();
00299       CalledFunctions[i] = CalledFunctions.back();
00300       CalledFunctions.pop_back();
00301       --i; --e;
00302     }
00303 }
00304 
00305 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
00306 /// from this node to the specified callee function.
00307 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
00308   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00309     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
00310     CallRecord &CR = *I;
00311     if (CR.second == Callee && CR.first == 0) {
00312       Callee->DropRef();
00313       *I = CalledFunctions.back();
00314       CalledFunctions.pop_back();
00315       return;
00316     }
00317   }
00318 }
00319 
00320 /// replaceCallEdge - This method replaces the edge in the node for the
00321 /// specified call site with a new one.  Note that this method takes linear
00322 /// time, so it should be used sparingly.
00323 void CallGraphNode::replaceCallEdge(CallSite CS,
00324                                     CallSite NewCS, CallGraphNode *NewNode){
00325   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00326     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00327     if (I->first == CS.getInstruction()) {
00328       I->second->DropRef();
00329       I->first = NewCS.getInstruction();
00330       I->second = NewNode;
00331       NewNode->AddRef();
00332       return;
00333     }
00334   }
00335 }
00336 
00337 // Enuse that users of CallGraph.h also link with this file
00338 DEFINING_FILE_FOR(CallGraph)