LLVM  mainline
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 #include "llvm/Analysis/CallGraph.h"
00011 #include "llvm/IR/CallSite.h"
00012 #include "llvm/IR/Instructions.h"
00013 #include "llvm/IR/IntrinsicInst.h"
00014 #include "llvm/IR/Module.h"
00015 #include "llvm/Support/Debug.h"
00016 #include "llvm/Support/raw_ostream.h"
00017 using namespace llvm;
00018 
00019 //===----------------------------------------------------------------------===//
00020 // Implementations of the CallGraph class methods.
00021 //
00022 
00023 CallGraph::CallGraph(Module &M)
00024     : M(M), Root(nullptr), ExternalCallingNode(getOrInsertFunction(nullptr)),
00025       CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) {
00026   // Add every function to the call graph.
00027   for (Function &F : M)
00028     addToCallGraph(&F);
00029 
00030   // If we didn't find a main function, use the external call graph node
00031   if (!Root)
00032     Root = ExternalCallingNode;
00033 }
00034 
00035 CallGraph::CallGraph(CallGraph &&Arg)
00036     : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), Root(Arg.Root),
00037       ExternalCallingNode(Arg.ExternalCallingNode),
00038       CallsExternalNode(std::move(Arg.CallsExternalNode)) {
00039   Arg.FunctionMap.clear();
00040   Arg.Root = nullptr;
00041   Arg.ExternalCallingNode = nullptr;
00042 }
00043 
00044 CallGraph::~CallGraph() {
00045   // CallsExternalNode is not in the function map, delete it explicitly.
00046   if (CallsExternalNode)
00047     CallsExternalNode->allReferencesDropped();
00048 
00049 // Reset all node's use counts to zero before deleting them to prevent an
00050 // assertion from firing.
00051 #ifndef NDEBUG
00052   for (auto &I : FunctionMap)
00053     I.second->allReferencesDropped();
00054 #endif
00055 }
00056 
00057 void CallGraph::addToCallGraph(Function *F) {
00058   CallGraphNode *Node = getOrInsertFunction(F);
00059 
00060   // If this function has external linkage, anything could call it.
00061   if (!F->hasLocalLinkage()) {
00062     ExternalCallingNode->addCalledFunction(CallSite(), Node);
00063 
00064     // Found the entry point?
00065     if (F->getName() == "main") {
00066       if (Root) // Found multiple external mains?  Don't pick one.
00067         Root = ExternalCallingNode;
00068       else
00069         Root = Node; // Found a main, keep track of it!
00070     }
00071   }
00072 
00073   // If this function has its address taken, anything could call it.
00074   if (F->hasAddressTaken())
00075     ExternalCallingNode->addCalledFunction(CallSite(), Node);
00076 
00077   // If this function is not defined in this translation unit, it could call
00078   // anything.
00079   if (F->isDeclaration() && !F->isIntrinsic())
00080     Node->addCalledFunction(CallSite(), CallsExternalNode.get());
00081 
00082   // Look for calls by this function.
00083   for (Function::iterator BB = F->begin(), BBE = F->end(); BB != BBE; ++BB)
00084     for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;
00085          ++II) {
00086       CallSite CS(cast<Value>(II));
00087       if (CS) {
00088         const Function *Callee = CS.getCalledFunction();
00089         if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
00090           // Indirect calls of intrinsics are not allowed so no need to check.
00091           // We can be more precise here by using TargetArg returned by
00092           // Intrinsic::isLeaf.
00093           Node->addCalledFunction(CS, CallsExternalNode.get());
00094         else if (!Callee->isIntrinsic())
00095           Node->addCalledFunction(CS, getOrInsertFunction(Callee));
00096       }
00097     }
00098 }
00099 
00100 void CallGraph::print(raw_ostream &OS) const {
00101   OS << "CallGraph Root is: ";
00102   if (Function *F = Root->getFunction())
00103     OS << F->getName() << "\n";
00104   else {
00105     OS << "<<null function: 0x" << Root << ">>\n";
00106   }
00107 
00108   // Print in a deterministic order by sorting CallGraphNodes by name.  We do
00109   // this here to avoid slowing down the non-printing fast path.
00110 
00111   SmallVector<CallGraphNode *, 16> Nodes;
00112   Nodes.reserve(FunctionMap.size());
00113 
00114   for (auto I = begin(), E = end(); I != E; ++I)
00115     Nodes.push_back(I->second.get());
00116 
00117   std::sort(Nodes.begin(), Nodes.end(),
00118             [](CallGraphNode *LHS, CallGraphNode *RHS) {
00119     if (Function *LF = LHS->getFunction())
00120       if (Function *RF = RHS->getFunction())
00121         return LF->getName() < RF->getName();
00122 
00123     return RHS->getFunction() != nullptr;
00124   });
00125 
00126   for (CallGraphNode *CN : Nodes)
00127     CN->print(OS);
00128 }
00129 
00130 LLVM_DUMP_METHOD
00131 void CallGraph::dump() const { print(dbgs()); }
00132 
00133 // removeFunctionFromModule - Unlink the function from this module, returning
00134 // it.  Because this removes the function from the module, the call graph node
00135 // is destroyed.  This is only valid if the function does not call any other
00136 // functions (ie, there are no edges in it's CGN).  The easiest way to do this
00137 // is to dropAllReferences before calling this.
00138 //
00139 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) {
00140   assert(CGN->empty() && "Cannot remove function from call "
00141          "graph if it references other functions!");
00142   Function *F = CGN->getFunction(); // Get the function for the call graph node
00143   FunctionMap.erase(F);             // Remove the call graph node from the map
00144 
00145   M.getFunctionList().remove(F);
00146   return F;
00147 }
00148 
00149 /// spliceFunction - Replace the function represented by this node by another.
00150 /// This does not rescan the body of the function, so it is suitable when
00151 /// splicing the body of the old function to the new while also updating all
00152 /// callers from old to new.
00153 ///
00154 void CallGraph::spliceFunction(const Function *From, const Function *To) {
00155   assert(FunctionMap.count(From) && "No CallGraphNode for function!");
00156   assert(!FunctionMap.count(To) &&
00157          "Pointing CallGraphNode at a function that already exists");
00158   FunctionMapTy::iterator I = FunctionMap.find(From);
00159   I->second->F = const_cast<Function*>(To);
00160   FunctionMap[To] = std::move(I->second);
00161   FunctionMap.erase(I);
00162 }
00163 
00164 // getOrInsertFunction - This method is identical to calling operator[], but
00165 // it will insert a new CallGraphNode for the specified function if one does
00166 // not already exist.
00167 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) {
00168   auto &CGN = FunctionMap[F];
00169   if (CGN)
00170     return CGN.get();
00171 
00172   assert((!F || F->getParent() == &M) && "Function not in current module!");
00173   CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F));
00174   return CGN.get();
00175 }
00176 
00177 //===----------------------------------------------------------------------===//
00178 // Implementations of the CallGraphNode class methods.
00179 //
00180 
00181 void CallGraphNode::print(raw_ostream &OS) const {
00182   if (Function *F = getFunction())
00183     OS << "Call graph node for function: '" << F->getName() << "'";
00184   else
00185     OS << "Call graph node <<null function>>";
00186   
00187   OS << "<<" << this << ">>  #uses=" << getNumReferences() << '\n';
00188 
00189   for (const_iterator I = begin(), E = end(); I != E; ++I) {
00190     OS << "  CS<" << I->first << "> calls ";
00191     if (Function *FI = I->second->getFunction())
00192       OS << "function '" << FI->getName() <<"'\n";
00193     else
00194       OS << "external node\n";
00195   }
00196   OS << '\n';
00197 }
00198 
00199 LLVM_DUMP_METHOD
00200 void CallGraphNode::dump() const { print(dbgs()); }
00201 
00202 /// removeCallEdgeFor - This method removes the edge in the node for the
00203 /// specified call site.  Note that this method takes linear time, so it
00204 /// should be used sparingly.
00205 void CallGraphNode::removeCallEdgeFor(CallSite CS) {
00206   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00207     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00208     if (I->first == CS.getInstruction()) {
00209       I->second->DropRef();
00210       *I = CalledFunctions.back();
00211       CalledFunctions.pop_back();
00212       return;
00213     }
00214   }
00215 }
00216 
00217 // removeAnyCallEdgeTo - This method removes any call edges from this node to
00218 // the specified callee function.  This takes more time to execute than
00219 // removeCallEdgeTo, so it should not be used unless necessary.
00220 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) {
00221   for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i)
00222     if (CalledFunctions[i].second == Callee) {
00223       Callee->DropRef();
00224       CalledFunctions[i] = CalledFunctions.back();
00225       CalledFunctions.pop_back();
00226       --i; --e;
00227     }
00228 }
00229 
00230 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite
00231 /// from this node to the specified callee function.
00232 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) {
00233   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00234     assert(I != CalledFunctions.end() && "Cannot find callee to remove!");
00235     CallRecord &CR = *I;
00236     if (CR.second == Callee && CR.first == nullptr) {
00237       Callee->DropRef();
00238       *I = CalledFunctions.back();
00239       CalledFunctions.pop_back();
00240       return;
00241     }
00242   }
00243 }
00244 
00245 /// replaceCallEdge - This method replaces the edge in the node for the
00246 /// specified call site with a new one.  Note that this method takes linear
00247 /// time, so it should be used sparingly.
00248 void CallGraphNode::replaceCallEdge(CallSite CS,
00249                                     CallSite NewCS, CallGraphNode *NewNode){
00250   for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) {
00251     assert(I != CalledFunctions.end() && "Cannot find callsite to remove!");
00252     if (I->first == CS.getInstruction()) {
00253       I->second->DropRef();
00254       I->first = NewCS.getInstruction();
00255       I->second = NewNode;
00256       NewNode->AddRef();
00257       return;
00258     }
00259   }
00260 }
00261 
00262 //===----------------------------------------------------------------------===//
00263 // Out-of-line definitions of CallGraphAnalysis class members.
00264 //
00265 
00266 char CallGraphAnalysis::PassID;
00267 
00268 //===----------------------------------------------------------------------===//
00269 // Implementations of the CallGraphWrapperPass class methods.
00270 //
00271 
00272 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) {
00273   initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry());
00274 }
00275 
00276 CallGraphWrapperPass::~CallGraphWrapperPass() {}
00277 
00278 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
00279   AU.setPreservesAll();
00280 }
00281 
00282 bool CallGraphWrapperPass::runOnModule(Module &M) {
00283   // All the real work is done in the constructor for the CallGraph.
00284   G.reset(new CallGraph(M));
00285   return false;
00286 }
00287 
00288 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction",
00289                 false, true)
00290 
00291 char CallGraphWrapperPass::ID = 0;
00292 
00293 void CallGraphWrapperPass::releaseMemory() { G.reset(); }
00294 
00295 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const {
00296   if (!G) {
00297     OS << "No call graph has been built!\n";
00298     return;
00299   }
00300 
00301   // Just delegate.
00302   G->print(OS);
00303 }
00304 
00305 LLVM_DUMP_METHOD
00306 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); }