CallGraph.cpp 13 KB

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