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