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