1 //===- CallGraph.cpp - Build a Module's call graph ------------------------===// 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 #include "llvm/Analysis/CallGraph.h" 11 #include "llvm/IR/CallSite.h" 12 #include "llvm/IR/Instructions.h" 13 #include "llvm/IR/IntrinsicInst.h" 14 #include "llvm/IR/Module.h" 15 #include "llvm/Support/Debug.h" 16 #include "llvm/Support/raw_ostream.h" 17 using namespace llvm; 18 19 //===----------------------------------------------------------------------===// 20 // Implementations of the CallGraph class methods. 21 // 22 23 CallGraph::CallGraph(Module &M) 24 : M(M), ExternalCallingNode(getOrInsertFunction(nullptr)), 25 CallsExternalNode(llvm::make_unique<CallGraphNode>(nullptr)) { 26 // Add every function to the call graph. 27 for (Function &F : M) 28 addToCallGraph(&F); 29 } 30 31 CallGraph::CallGraph(CallGraph &&Arg) 32 : M(Arg.M), FunctionMap(std::move(Arg.FunctionMap)), 33 ExternalCallingNode(Arg.ExternalCallingNode), 34 CallsExternalNode(std::move(Arg.CallsExternalNode)) { 35 Arg.FunctionMap.clear(); 36 Arg.ExternalCallingNode = nullptr; 37 } 38 39 CallGraph::~CallGraph() { 40 // CallsExternalNode is not in the function map, delete it explicitly. 41 if (CallsExternalNode) 42 CallsExternalNode->allReferencesDropped(); 43 44 // Reset all node's use counts to zero before deleting them to prevent an 45 // assertion from firing. 46 #ifndef NDEBUG 47 for (auto &I : FunctionMap) 48 I.second->allReferencesDropped(); 49 #endif 50 } 51 52 void CallGraph::addToCallGraph(Function *F) { 53 CallGraphNode *Node = getOrInsertFunction(F); 54 55 // If this function has external linkage or has its address taken, anything 56 // could call it. 57 if (!F->hasLocalLinkage() || F->hasAddressTaken()) 58 ExternalCallingNode->addCalledFunction(CallSite(), Node); 59 60 // If this function is not defined in this translation unit, it could call 61 // anything. 62 if (F->isDeclaration() && !F->isIntrinsic()) 63 Node->addCalledFunction(CallSite(), CallsExternalNode.get()); 64 65 // Look for calls by this function. 66 for (BasicBlock &BB : *F) 67 for (Instruction &I : BB) { 68 if (auto CS = CallSite(&I)) { 69 const Function *Callee = CS.getCalledFunction(); 70 if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID())) 71 // Indirect calls of intrinsics are not allowed so no need to check. 72 // We can be more precise here by using TargetArg returned by 73 // Intrinsic::isLeaf. 74 Node->addCalledFunction(CS, CallsExternalNode.get()); 75 else if (!Callee->isIntrinsic()) 76 Node->addCalledFunction(CS, getOrInsertFunction(Callee)); 77 } 78 } 79 } 80 81 void CallGraph::print(raw_ostream &OS) const { 82 // Print in a deterministic order by sorting CallGraphNodes by name. We do 83 // this here to avoid slowing down the non-printing fast path. 84 85 SmallVector<CallGraphNode *, 16> Nodes; 86 Nodes.reserve(FunctionMap.size()); 87 88 for (const auto &I : *this) 89 Nodes.push_back(I.second.get()); 90 91 std::sort(Nodes.begin(), Nodes.end(), 92 [](CallGraphNode *LHS, CallGraphNode *RHS) { 93 if (Function *LF = LHS->getFunction()) 94 if (Function *RF = RHS->getFunction()) 95 return LF->getName() < RF->getName(); 96 97 return RHS->getFunction() != nullptr; 98 }); 99 100 for (CallGraphNode *CN : Nodes) 101 CN->print(OS); 102 } 103 104 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 105 LLVM_DUMP_METHOD void CallGraph::dump() const { print(dbgs()); } 106 #endif 107 108 // removeFunctionFromModule - Unlink the function from this module, returning 109 // it. Because this removes the function from the module, the call graph node 110 // is destroyed. This is only valid if the function does not call any other 111 // functions (ie, there are no edges in it's CGN). The easiest way to do this 112 // is to dropAllReferences before calling this. 113 // 114 Function *CallGraph::removeFunctionFromModule(CallGraphNode *CGN) { 115 assert(CGN->empty() && "Cannot remove function from call " 116 "graph if it references other functions!"); 117 Function *F = CGN->getFunction(); // Get the function for the call graph node 118 FunctionMap.erase(F); // Remove the call graph node from the map 119 120 M.getFunctionList().remove(F); 121 return F; 122 } 123 124 /// spliceFunction - Replace the function represented by this node by another. 125 /// This does not rescan the body of the function, so it is suitable when 126 /// splicing the body of the old function to the new while also updating all 127 /// callers from old to new. 128 /// 129 void CallGraph::spliceFunction(const Function *From, const Function *To) { 130 assert(FunctionMap.count(From) && "No CallGraphNode for function!"); 131 assert(!FunctionMap.count(To) && 132 "Pointing CallGraphNode at a function that already exists"); 133 FunctionMapTy::iterator I = FunctionMap.find(From); 134 I->second->F = const_cast<Function*>(To); 135 FunctionMap[To] = std::move(I->second); 136 FunctionMap.erase(I); 137 } 138 139 // getOrInsertFunction - This method is identical to calling operator[], but 140 // it will insert a new CallGraphNode for the specified function if one does 141 // not already exist. 142 CallGraphNode *CallGraph::getOrInsertFunction(const Function *F) { 143 auto &CGN = FunctionMap[F]; 144 if (CGN) 145 return CGN.get(); 146 147 assert((!F || F->getParent() == &M) && "Function not in current module!"); 148 CGN = llvm::make_unique<CallGraphNode>(const_cast<Function *>(F)); 149 return CGN.get(); 150 } 151 152 //===----------------------------------------------------------------------===// 153 // Implementations of the CallGraphNode class methods. 154 // 155 156 void CallGraphNode::print(raw_ostream &OS) const { 157 if (Function *F = getFunction()) 158 OS << "Call graph node for function: '" << F->getName() << "'"; 159 else 160 OS << "Call graph node <<null function>>"; 161 162 OS << "<<" << this << ">> #uses=" << getNumReferences() << '\n'; 163 164 for (const auto &I : *this) { 165 OS << " CS<" << I.first << "> calls "; 166 if (Function *FI = I.second->getFunction()) 167 OS << "function '" << FI->getName() <<"'\n"; 168 else 169 OS << "external node\n"; 170 } 171 OS << '\n'; 172 } 173 174 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 175 LLVM_DUMP_METHOD void CallGraphNode::dump() const { print(dbgs()); } 176 #endif 177 178 /// removeCallEdgeFor - This method removes the edge in the node for the 179 /// specified call site. Note that this method takes linear time, so it 180 /// should be used sparingly. 181 void CallGraphNode::removeCallEdgeFor(CallSite CS) { 182 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 183 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!"); 184 if (I->first == CS.getInstruction()) { 185 I->second->DropRef(); 186 *I = CalledFunctions.back(); 187 CalledFunctions.pop_back(); 188 return; 189 } 190 } 191 } 192 193 // removeAnyCallEdgeTo - This method removes any call edges from this node to 194 // the specified callee function. This takes more time to execute than 195 // removeCallEdgeTo, so it should not be used unless necessary. 196 void CallGraphNode::removeAnyCallEdgeTo(CallGraphNode *Callee) { 197 for (unsigned i = 0, e = CalledFunctions.size(); i != e; ++i) 198 if (CalledFunctions[i].second == Callee) { 199 Callee->DropRef(); 200 CalledFunctions[i] = CalledFunctions.back(); 201 CalledFunctions.pop_back(); 202 --i; --e; 203 } 204 } 205 206 /// removeOneAbstractEdgeTo - Remove one edge associated with a null callsite 207 /// from this node to the specified callee function. 208 void CallGraphNode::removeOneAbstractEdgeTo(CallGraphNode *Callee) { 209 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 210 assert(I != CalledFunctions.end() && "Cannot find callee to remove!"); 211 CallRecord &CR = *I; 212 if (CR.second == Callee && CR.first == nullptr) { 213 Callee->DropRef(); 214 *I = CalledFunctions.back(); 215 CalledFunctions.pop_back(); 216 return; 217 } 218 } 219 } 220 221 /// replaceCallEdge - This method replaces the edge in the node for the 222 /// specified call site with a new one. Note that this method takes linear 223 /// time, so it should be used sparingly. 224 void CallGraphNode::replaceCallEdge(CallSite CS, 225 CallSite NewCS, CallGraphNode *NewNode){ 226 for (CalledFunctionsVector::iterator I = CalledFunctions.begin(); ; ++I) { 227 assert(I != CalledFunctions.end() && "Cannot find callsite to remove!"); 228 if (I->first == CS.getInstruction()) { 229 I->second->DropRef(); 230 I->first = NewCS.getInstruction(); 231 I->second = NewNode; 232 NewNode->AddRef(); 233 return; 234 } 235 } 236 } 237 238 // Provide an explicit template instantiation for the static ID. 239 AnalysisKey CallGraphAnalysis::Key; 240 241 PreservedAnalyses CallGraphPrinterPass::run(Module &M, 242 ModuleAnalysisManager &AM) { 243 AM.getResult<CallGraphAnalysis>(M).print(OS); 244 return PreservedAnalyses::all(); 245 } 246 247 //===----------------------------------------------------------------------===// 248 // Out-of-line definitions of CallGraphAnalysis class members. 249 // 250 251 //===----------------------------------------------------------------------===// 252 // Implementations of the CallGraphWrapperPass class methods. 253 // 254 255 CallGraphWrapperPass::CallGraphWrapperPass() : ModulePass(ID) { 256 initializeCallGraphWrapperPassPass(*PassRegistry::getPassRegistry()); 257 } 258 259 CallGraphWrapperPass::~CallGraphWrapperPass() {} 260 261 void CallGraphWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 262 AU.setPreservesAll(); 263 } 264 265 bool CallGraphWrapperPass::runOnModule(Module &M) { 266 // All the real work is done in the constructor for the CallGraph. 267 G.reset(new CallGraph(M)); 268 return false; 269 } 270 271 INITIALIZE_PASS(CallGraphWrapperPass, "basiccg", "CallGraph Construction", 272 false, true) 273 274 char CallGraphWrapperPass::ID = 0; 275 276 void CallGraphWrapperPass::releaseMemory() { G.reset(); } 277 278 void CallGraphWrapperPass::print(raw_ostream &OS, const Module *) const { 279 if (!G) { 280 OS << "No call graph has been built!\n"; 281 return; 282 } 283 284 // Just delegate. 285 G->print(OS); 286 } 287 288 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 289 LLVM_DUMP_METHOD 290 void CallGraphWrapperPass::dump() const { print(dbgs(), nullptr); } 291 #endif 292 293 namespace { 294 struct CallGraphPrinterLegacyPass : public ModulePass { 295 static char ID; // Pass ID, replacement for typeid 296 CallGraphPrinterLegacyPass() : ModulePass(ID) { 297 initializeCallGraphPrinterLegacyPassPass(*PassRegistry::getPassRegistry()); 298 } 299 300 void getAnalysisUsage(AnalysisUsage &AU) const override { 301 AU.setPreservesAll(); 302 AU.addRequiredTransitive<CallGraphWrapperPass>(); 303 } 304 bool runOnModule(Module &M) override { 305 getAnalysis<CallGraphWrapperPass>().print(errs(), &M); 306 return false; 307 } 308 }; 309 } 310 311 char CallGraphPrinterLegacyPass::ID = 0; 312 313 INITIALIZE_PASS_BEGIN(CallGraphPrinterLegacyPass, "print-callgraph", 314 "Print a call graph", true, true) 315 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 316 INITIALIZE_PASS_END(CallGraphPrinterLegacyPass, "print-callgraph", 317 "Print a call graph", true, true) 318