CallGraph.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. //===- CallGraph.h - Build a Module's call graph ----------------*- C++ -*-===//
  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. /// \file
  9. ///
  10. /// This file provides interfaces used to build and manipulate a call graph,
  11. /// which is a very useful tool for interprocedural optimization.
  12. ///
  13. /// Every function in a module is represented as a node in the call graph. The
  14. /// callgraph node keeps track of which functions are called by the function
  15. /// corresponding to the node.
  16. ///
  17. /// A call graph may contain nodes where the function that they correspond to
  18. /// is null. These 'external' nodes are used to represent control flow that is
  19. /// not represented (or analyzable) in the module. In particular, this
  20. /// analysis builds one external node such that:
  21. /// 1. All functions in the module without internal linkage will have edges
  22. /// from this external node, indicating that they could be called by
  23. /// functions outside of the module.
  24. /// 2. All functions whose address is used for something more than a direct
  25. /// call, for example being stored into a memory location will also have
  26. /// an edge from this external node. Since they may be called by an
  27. /// unknown caller later, they must be tracked as such.
  28. ///
  29. /// There is a second external node added for calls that leave this module.
  30. /// Functions have a call edge to the external node iff:
  31. /// 1. The function is external, reflecting the fact that they could call
  32. /// anything without internal linkage or that has its address taken.
  33. /// 2. The function contains an indirect function call.
  34. ///
  35. /// As an extension in the future, there may be multiple nodes with a null
  36. /// function. These will be used when we can prove (through pointer analysis)
  37. /// that an indirect call site can call only a specific set of functions.
  38. ///
  39. /// Because of these properties, the CallGraph captures a conservative superset
  40. /// of all of the caller-callee relationships, which is useful for
  41. /// transformations.
  42. ///
  43. //===----------------------------------------------------------------------===//
  44. #ifndef LLVM_ANALYSIS_CALLGRAPH_H
  45. #define LLVM_ANALYSIS_CALLGRAPH_H
  46. #include "llvm/ADT/GraphTraits.h"
  47. #include "llvm/ADT/STLExtras.h"
  48. #include "llvm/IR/Function.h"
  49. #include "llvm/IR/InstrTypes.h"
  50. #include "llvm/IR/Intrinsics.h"
  51. #include "llvm/IR/PassManager.h"
  52. #include "llvm/IR/ValueHandle.h"
  53. #include "llvm/Pass.h"
  54. #include <cassert>
  55. #include <map>
  56. #include <memory>
  57. #include <utility>
  58. #include <vector>
  59. namespace llvm {
  60. class CallGraphNode;
  61. class Module;
  62. class raw_ostream;
  63. /// The basic data container for the call graph of a \c Module of IR.
  64. ///
  65. /// This class exposes both the interface to the call graph for a module of IR.
  66. ///
  67. /// The core call graph itself can also be updated to reflect changes to the IR.
  68. class CallGraph {
  69. Module &M;
  70. using FunctionMapTy =
  71. std::map<const Function *, std::unique_ptr<CallGraphNode>>;
  72. /// A map from \c Function* to \c CallGraphNode*.
  73. FunctionMapTy FunctionMap;
  74. /// This node has edges to all external functions and those internal
  75. /// functions that have their address taken.
  76. CallGraphNode *ExternalCallingNode;
  77. /// This node has edges to it from all functions making indirect calls
  78. /// or calling an external function.
  79. std::unique_ptr<CallGraphNode> CallsExternalNode;
  80. public:
  81. explicit CallGraph(Module &M);
  82. CallGraph(CallGraph &&Arg);
  83. ~CallGraph();
  84. void print(raw_ostream &OS) const;
  85. void dump() const;
  86. using iterator = FunctionMapTy::iterator;
  87. using const_iterator = FunctionMapTy::const_iterator;
  88. /// Returns the module the call graph corresponds to.
  89. Module &getModule() const { return M; }
  90. bool invalidate(Module &, const PreservedAnalyses &PA,
  91. ModuleAnalysisManager::Invalidator &);
  92. inline iterator begin() { return FunctionMap.begin(); }
  93. inline iterator end() { return FunctionMap.end(); }
  94. inline const_iterator begin() const { return FunctionMap.begin(); }
  95. inline const_iterator end() const { return FunctionMap.end(); }
  96. /// Returns the call graph node for the provided function.
  97. inline const CallGraphNode *operator[](const Function *F) const {
  98. const_iterator I = FunctionMap.find(F);
  99. assert(I != FunctionMap.end() && "Function not in callgraph!");
  100. return I->second.get();
  101. }
  102. /// Returns the call graph node for the provided function.
  103. inline CallGraphNode *operator[](const Function *F) {
  104. const_iterator I = FunctionMap.find(F);
  105. assert(I != FunctionMap.end() && "Function not in callgraph!");
  106. return I->second.get();
  107. }
  108. /// Returns the \c CallGraphNode which is used to represent
  109. /// undetermined calls into the callgraph.
  110. CallGraphNode *getExternalCallingNode() const { return ExternalCallingNode; }
  111. CallGraphNode *getCallsExternalNode() const {
  112. return CallsExternalNode.get();
  113. }
  114. /// Old node has been deleted, and New is to be used in its place, update the
  115. /// ExternalCallingNode.
  116. void ReplaceExternalCallEdge(CallGraphNode *Old, CallGraphNode *New);
  117. //===---------------------------------------------------------------------
  118. // Functions to keep a call graph up to date with a function that has been
  119. // modified.
  120. //
  121. /// Unlink the function from this module, returning it.
  122. ///
  123. /// Because this removes the function from the module, the call graph node is
  124. /// destroyed. This is only valid if the function does not call any other
  125. /// functions (ie, there are no edges in it's CGN). The easiest way to do
  126. /// this is to dropAllReferences before calling this.
  127. Function *removeFunctionFromModule(CallGraphNode *CGN);
  128. /// Similar to operator[], but this will insert a new CallGraphNode for
  129. /// \c F if one does not already exist.
  130. CallGraphNode *getOrInsertFunction(const Function *F);
  131. /// Populate \p CGN based on the calls inside the associated function.
  132. void populateCallGraphNode(CallGraphNode *CGN);
  133. /// Add a function to the call graph, and link the node to all of the
  134. /// functions that it calls.
  135. void addToCallGraph(Function *F);
  136. };
  137. /// A node in the call graph for a module.
  138. ///
  139. /// Typically represents a function in the call graph. There are also special
  140. /// "null" nodes used to represent theoretical entries in the call graph.
  141. class CallGraphNode {
  142. public:
  143. /// A pair of the calling instruction (a call or invoke)
  144. /// and the call graph node being called.
  145. /// Call graph node may have two types of call records which represent an edge
  146. /// in the call graph - reference or a call edge. Reference edges are not
  147. /// associated with any call instruction and are created with the first field
  148. /// set to `None`, while real call edges have instruction address in this
  149. /// field. Therefore, all real call edges are expected to have a value in the
  150. /// first field and it is not supposed to be `nullptr`.
  151. /// Reference edges, for example, are used for connecting broker function
  152. /// caller to the callback function for callback call sites.
  153. using CallRecord = std::pair<Optional<WeakTrackingVH>, CallGraphNode *>;
  154. public:
  155. using CalledFunctionsVector = std::vector<CallRecord>;
  156. /// Creates a node for the specified function.
  157. inline CallGraphNode(CallGraph *CG, Function *F) : CG(CG), F(F) {}
  158. CallGraphNode(const CallGraphNode &) = delete;
  159. CallGraphNode &operator=(const CallGraphNode &) = delete;
  160. ~CallGraphNode() {
  161. assert(NumReferences == 0 && "Node deleted while references remain");
  162. }
  163. using iterator = std::vector<CallRecord>::iterator;
  164. using const_iterator = std::vector<CallRecord>::const_iterator;
  165. /// Returns the function that this call graph node represents.
  166. Function *getFunction() const { return F; }
  167. inline iterator begin() { return CalledFunctions.begin(); }
  168. inline iterator end() { return CalledFunctions.end(); }
  169. inline const_iterator begin() const { return CalledFunctions.begin(); }
  170. inline const_iterator end() const { return CalledFunctions.end(); }
  171. inline bool empty() const { return CalledFunctions.empty(); }
  172. inline unsigned size() const { return (unsigned)CalledFunctions.size(); }
  173. /// Returns the number of other CallGraphNodes in this CallGraph that
  174. /// reference this node in their callee list.
  175. unsigned getNumReferences() const { return NumReferences; }
  176. /// Returns the i'th called function.
  177. CallGraphNode *operator[](unsigned i) const {
  178. assert(i < CalledFunctions.size() && "Invalid index");
  179. return CalledFunctions[i].second;
  180. }
  181. /// Print out this call graph node.
  182. void dump() const;
  183. void print(raw_ostream &OS) const;
  184. //===---------------------------------------------------------------------
  185. // Methods to keep a call graph up to date with a function that has been
  186. // modified
  187. //
  188. /// Removes all edges from this CallGraphNode to any functions it
  189. /// calls.
  190. void removeAllCalledFunctions() {
  191. while (!CalledFunctions.empty()) {
  192. CalledFunctions.back().second->DropRef();
  193. CalledFunctions.pop_back();
  194. }
  195. }
  196. /// Moves all the callee information from N to this node.
  197. void stealCalledFunctionsFrom(CallGraphNode *N) {
  198. assert(CalledFunctions.empty() &&
  199. "Cannot steal callsite information if I already have some");
  200. std::swap(CalledFunctions, N->CalledFunctions);
  201. }
  202. /// Adds a function to the list of functions called by this one.
  203. void addCalledFunction(CallBase *Call, CallGraphNode *M) {
  204. assert(!Call || !Call->getCalledFunction() ||
  205. !Call->getCalledFunction()->isIntrinsic() ||
  206. !Intrinsic::isLeaf(Call->getCalledFunction()->getIntrinsicID()));
  207. CalledFunctions.emplace_back(
  208. Call ? Optional<WeakTrackingVH>(Call) : Optional<WeakTrackingVH>(), M);
  209. M->AddRef();
  210. }
  211. void removeCallEdge(iterator I) {
  212. I->second->DropRef();
  213. *I = CalledFunctions.back();
  214. CalledFunctions.pop_back();
  215. }
  216. /// Removes the edge in the node for the specified call site.
  217. ///
  218. /// Note that this method takes linear time, so it should be used sparingly.
  219. void removeCallEdgeFor(CallBase &Call);
  220. /// Removes all call edges from this node to the specified callee
  221. /// function.
  222. ///
  223. /// This takes more time to execute than removeCallEdgeTo, so it should not
  224. /// be used unless necessary.
  225. void removeAnyCallEdgeTo(CallGraphNode *Callee);
  226. /// Removes one edge associated with a null callsite from this node to
  227. /// the specified callee function.
  228. void removeOneAbstractEdgeTo(CallGraphNode *Callee);
  229. /// Replaces the edge in the node for the specified call site with a
  230. /// new one.
  231. ///
  232. /// Note that this method takes linear time, so it should be used sparingly.
  233. void replaceCallEdge(CallBase &Call, CallBase &NewCall,
  234. CallGraphNode *NewNode);
  235. private:
  236. friend class CallGraph;
  237. CallGraph *CG;
  238. Function *F;
  239. std::vector<CallRecord> CalledFunctions;
  240. /// The number of times that this CallGraphNode occurs in the
  241. /// CalledFunctions array of this or other CallGraphNodes.
  242. unsigned NumReferences = 0;
  243. void DropRef() { --NumReferences; }
  244. void AddRef() { ++NumReferences; }
  245. /// A special function that should only be used by the CallGraph class.
  246. void allReferencesDropped() { NumReferences = 0; }
  247. };
  248. /// An analysis pass to compute the \c CallGraph for a \c Module.
  249. ///
  250. /// This class implements the concept of an analysis pass used by the \c
  251. /// ModuleAnalysisManager to run an analysis over a module and cache the
  252. /// resulting data.
  253. class CallGraphAnalysis : public AnalysisInfoMixin<CallGraphAnalysis> {
  254. friend AnalysisInfoMixin<CallGraphAnalysis>;
  255. static AnalysisKey Key;
  256. public:
  257. /// A formulaic type to inform clients of the result type.
  258. using Result = CallGraph;
  259. /// Compute the \c CallGraph for the module \c M.
  260. ///
  261. /// The real work here is done in the \c CallGraph constructor.
  262. CallGraph run(Module &M, ModuleAnalysisManager &) { return CallGraph(M); }
  263. };
  264. /// Printer pass for the \c CallGraphAnalysis results.
  265. class CallGraphPrinterPass : public PassInfoMixin<CallGraphPrinterPass> {
  266. raw_ostream &OS;
  267. public:
  268. explicit CallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
  269. PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
  270. };
  271. /// The \c ModulePass which wraps up a \c CallGraph and the logic to
  272. /// build it.
  273. ///
  274. /// This class exposes both the interface to the call graph container and the
  275. /// module pass which runs over a module of IR and produces the call graph. The
  276. /// call graph interface is entirelly a wrapper around a \c CallGraph object
  277. /// which is stored internally for each module.
  278. class CallGraphWrapperPass : public ModulePass {
  279. std::unique_ptr<CallGraph> G;
  280. public:
  281. static char ID; // Class identification, replacement for typeinfo
  282. CallGraphWrapperPass();
  283. ~CallGraphWrapperPass() override;
  284. /// The internal \c CallGraph around which the rest of this interface
  285. /// is wrapped.
  286. const CallGraph &getCallGraph() const { return *G; }
  287. CallGraph &getCallGraph() { return *G; }
  288. using iterator = CallGraph::iterator;
  289. using const_iterator = CallGraph::const_iterator;
  290. /// Returns the module the call graph corresponds to.
  291. Module &getModule() const { return G->getModule(); }
  292. inline iterator begin() { return G->begin(); }
  293. inline iterator end() { return G->end(); }
  294. inline const_iterator begin() const { return G->begin(); }
  295. inline const_iterator end() const { return G->end(); }
  296. /// Returns the call graph node for the provided function.
  297. inline const CallGraphNode *operator[](const Function *F) const {
  298. return (*G)[F];
  299. }
  300. /// Returns the call graph node for the provided function.
  301. inline CallGraphNode *operator[](const Function *F) { return (*G)[F]; }
  302. /// Returns the \c CallGraphNode which is used to represent
  303. /// undetermined calls into the callgraph.
  304. CallGraphNode *getExternalCallingNode() const {
  305. return G->getExternalCallingNode();
  306. }
  307. CallGraphNode *getCallsExternalNode() const {
  308. return G->getCallsExternalNode();
  309. }
  310. //===---------------------------------------------------------------------
  311. // Functions to keep a call graph up to date with a function that has been
  312. // modified.
  313. //
  314. /// Unlink the function from this module, returning it.
  315. ///
  316. /// Because this removes the function from the module, the call graph node is
  317. /// destroyed. This is only valid if the function does not call any other
  318. /// functions (ie, there are no edges in it's CGN). The easiest way to do
  319. /// this is to dropAllReferences before calling this.
  320. Function *removeFunctionFromModule(CallGraphNode *CGN) {
  321. return G->removeFunctionFromModule(CGN);
  322. }
  323. /// Similar to operator[], but this will insert a new CallGraphNode for
  324. /// \c F if one does not already exist.
  325. CallGraphNode *getOrInsertFunction(const Function *F) {
  326. return G->getOrInsertFunction(F);
  327. }
  328. //===---------------------------------------------------------------------
  329. // Implementation of the ModulePass interface needed here.
  330. //
  331. void getAnalysisUsage(AnalysisUsage &AU) const override;
  332. bool runOnModule(Module &M) override;
  333. void releaseMemory() override;
  334. void print(raw_ostream &o, const Module *) const override;
  335. void dump() const;
  336. };
  337. //===----------------------------------------------------------------------===//
  338. // GraphTraits specializations for call graphs so that they can be treated as
  339. // graphs by the generic graph algorithms.
  340. //
  341. // Provide graph traits for traversing call graphs using standard graph
  342. // traversals.
  343. template <> struct GraphTraits<CallGraphNode *> {
  344. using NodeRef = CallGraphNode *;
  345. using CGNPairTy = CallGraphNode::CallRecord;
  346. static NodeRef getEntryNode(CallGraphNode *CGN) { return CGN; }
  347. static CallGraphNode *CGNGetValue(CGNPairTy P) { return P.second; }
  348. using ChildIteratorType =
  349. mapped_iterator<CallGraphNode::iterator, decltype(&CGNGetValue)>;
  350. static ChildIteratorType child_begin(NodeRef N) {
  351. return ChildIteratorType(N->begin(), &CGNGetValue);
  352. }
  353. static ChildIteratorType child_end(NodeRef N) {
  354. return ChildIteratorType(N->end(), &CGNGetValue);
  355. }
  356. };
  357. template <> struct GraphTraits<const CallGraphNode *> {
  358. using NodeRef = const CallGraphNode *;
  359. using CGNPairTy = CallGraphNode::CallRecord;
  360. using EdgeRef = const CallGraphNode::CallRecord &;
  361. static NodeRef getEntryNode(const CallGraphNode *CGN) { return CGN; }
  362. static const CallGraphNode *CGNGetValue(CGNPairTy P) { return P.second; }
  363. using ChildIteratorType =
  364. mapped_iterator<CallGraphNode::const_iterator, decltype(&CGNGetValue)>;
  365. using ChildEdgeIteratorType = CallGraphNode::const_iterator;
  366. static ChildIteratorType child_begin(NodeRef N) {
  367. return ChildIteratorType(N->begin(), &CGNGetValue);
  368. }
  369. static ChildIteratorType child_end(NodeRef N) {
  370. return ChildIteratorType(N->end(), &CGNGetValue);
  371. }
  372. static ChildEdgeIteratorType child_edge_begin(NodeRef N) {
  373. return N->begin();
  374. }
  375. static ChildEdgeIteratorType child_edge_end(NodeRef N) { return N->end(); }
  376. static NodeRef edge_dest(EdgeRef E) { return E.second; }
  377. };
  378. template <>
  379. struct GraphTraits<CallGraph *> : public GraphTraits<CallGraphNode *> {
  380. using PairTy =
  381. std::pair<const Function *const, std::unique_ptr<CallGraphNode>>;
  382. static NodeRef getEntryNode(CallGraph *CGN) {
  383. return CGN->getExternalCallingNode(); // Start at the external node!
  384. }
  385. static CallGraphNode *CGGetValuePtr(const PairTy &P) {
  386. return P.second.get();
  387. }
  388. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  389. using nodes_iterator =
  390. mapped_iterator<CallGraph::iterator, decltype(&CGGetValuePtr)>;
  391. static nodes_iterator nodes_begin(CallGraph *CG) {
  392. return nodes_iterator(CG->begin(), &CGGetValuePtr);
  393. }
  394. static nodes_iterator nodes_end(CallGraph *CG) {
  395. return nodes_iterator(CG->end(), &CGGetValuePtr);
  396. }
  397. };
  398. template <>
  399. struct GraphTraits<const CallGraph *> : public GraphTraits<
  400. const CallGraphNode *> {
  401. using PairTy =
  402. std::pair<const Function *const, std::unique_ptr<CallGraphNode>>;
  403. static NodeRef getEntryNode(const CallGraph *CGN) {
  404. return CGN->getExternalCallingNode(); // Start at the external node!
  405. }
  406. static const CallGraphNode *CGGetValuePtr(const PairTy &P) {
  407. return P.second.get();
  408. }
  409. // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
  410. using nodes_iterator =
  411. mapped_iterator<CallGraph::const_iterator, decltype(&CGGetValuePtr)>;
  412. static nodes_iterator nodes_begin(const CallGraph *CG) {
  413. return nodes_iterator(CG->begin(), &CGGetValuePtr);
  414. }
  415. static nodes_iterator nodes_end(const CallGraph *CG) {
  416. return nodes_iterator(CG->end(), &CGGetValuePtr);
  417. }
  418. };
  419. } // end namespace llvm
  420. #endif // LLVM_ANALYSIS_CALLGRAPH_H