|
|
|||
File indexing completed on 2026-05-10 08:43:14
0001 //===- LazyCallGraph.h - Analysis of a Module's call graph ------*- C++ -*-===// 0002 // 0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 0004 // See https://llvm.org/LICENSE.txt for license information. 0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 0006 // 0007 //===----------------------------------------------------------------------===// 0008 /// \file 0009 /// 0010 /// Implements a lazy call graph analysis and related passes for the new pass 0011 /// manager. 0012 /// 0013 /// NB: This is *not* a traditional call graph! It is a graph which models both 0014 /// the current calls and potential calls. As a consequence there are many 0015 /// edges in this call graph that do not correspond to a 'call' or 'invoke' 0016 /// instruction. 0017 /// 0018 /// The primary use cases of this graph analysis is to facilitate iterating 0019 /// across the functions of a module in ways that ensure all callees are 0020 /// visited prior to a caller (given any SCC constraints), or vice versa. As 0021 /// such is it particularly well suited to organizing CGSCC optimizations such 0022 /// as inlining, outlining, argument promotion, etc. That is its primary use 0023 /// case and motivates the design. It may not be appropriate for other 0024 /// purposes. The use graph of functions or some other conservative analysis of 0025 /// call instructions may be interesting for optimizations and subsequent 0026 /// analyses which don't work in the context of an overly specified 0027 /// potential-call-edge graph. 0028 /// 0029 /// To understand the specific rules and nature of this call graph analysis, 0030 /// see the documentation of the \c LazyCallGraph below. 0031 /// 0032 //===----------------------------------------------------------------------===// 0033 0034 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H 0035 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H 0036 0037 #include "llvm/ADT/Any.h" 0038 #include "llvm/ADT/ArrayRef.h" 0039 #include "llvm/ADT/DenseMap.h" 0040 #include "llvm/ADT/PointerIntPair.h" 0041 #include "llvm/ADT/SetVector.h" 0042 #include "llvm/ADT/SmallVector.h" 0043 #include "llvm/ADT/StringRef.h" 0044 #include "llvm/ADT/iterator.h" 0045 #include "llvm/ADT/iterator_range.h" 0046 #include "llvm/Analysis/TargetLibraryInfo.h" 0047 #include "llvm/IR/PassManager.h" 0048 #include "llvm/Support/Allocator.h" 0049 #include "llvm/Support/raw_ostream.h" 0050 #include <cassert> 0051 #include <iterator> 0052 #include <optional> 0053 #include <string> 0054 #include <utility> 0055 0056 namespace llvm { 0057 0058 class Constant; 0059 template <class GraphType> struct GraphTraits; 0060 class Module; 0061 0062 /// A lazily constructed view of the call graph of a module. 0063 /// 0064 /// With the edges of this graph, the motivating constraint that we are 0065 /// attempting to maintain is that function-local optimization, CGSCC-local 0066 /// optimizations, and optimizations transforming a pair of functions connected 0067 /// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC 0068 /// DAG. That is, no optimizations will delete, remove, or add an edge such 0069 /// that functions already visited in a bottom-up order of the SCC DAG are no 0070 /// longer valid to have visited, or such that functions not yet visited in 0071 /// a bottom-up order of the SCC DAG are not required to have already been 0072 /// visited. 0073 /// 0074 /// Within this constraint, the desire is to minimize the merge points of the 0075 /// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points 0076 /// in the SCC DAG, the more independence there is in optimizing within it. 0077 /// There is a strong desire to enable parallelization of optimizations over 0078 /// the call graph, and both limited fanout and merge points will (artificially 0079 /// in some cases) limit the scaling of such an effort. 0080 /// 0081 /// To this end, graph represents both direct and any potential resolution to 0082 /// an indirect call edge. Another way to think about it is that it represents 0083 /// both the direct call edges and any direct call edges that might be formed 0084 /// through static optimizations. Specifically, it considers taking the address 0085 /// of a function to be an edge in the call graph because this might be 0086 /// forwarded to become a direct call by some subsequent function-local 0087 /// optimization. The result is that the graph closely follows the use-def 0088 /// edges for functions. Walking "up" the graph can be done by looking at all 0089 /// of the uses of a function. 0090 /// 0091 /// The roots of the call graph are the external functions and functions 0092 /// escaped into global variables. Those functions can be called from outside 0093 /// of the module or via unknowable means in the IR -- we may not be able to 0094 /// form even a potential call edge from a function body which may dynamically 0095 /// load the function and call it. 0096 /// 0097 /// This analysis still requires updates to remain valid after optimizations 0098 /// which could potentially change the set of potential callees. The 0099 /// constraints it operates under only make the traversal order remain valid. 0100 /// 0101 /// The entire analysis must be re-computed if full interprocedural 0102 /// optimizations run at any point. For example, globalopt completely 0103 /// invalidates the information in this analysis. 0104 /// 0105 /// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish 0106 /// it from the existing CallGraph. At some point, it is expected that this 0107 /// will be the only call graph and it will be renamed accordingly. 0108 class LazyCallGraph { 0109 public: 0110 class Node; 0111 class EdgeSequence; 0112 class RefSCC; 0113 0114 /// A class used to represent edges in the call graph. 0115 /// 0116 /// The lazy call graph models both *call* edges and *reference* edges. Call 0117 /// edges are much what you would expect, and exist when there is a 'call' or 0118 /// 'invoke' instruction of some function. Reference edges are also tracked 0119 /// along side these, and exist whenever any instruction (transitively 0120 /// through its operands) references a function. All call edges are 0121 /// inherently reference edges, and so the reference graph forms a superset 0122 /// of the formal call graph. 0123 /// 0124 /// All of these forms of edges are fundamentally represented as outgoing 0125 /// edges. The edges are stored in the source node and point at the target 0126 /// node. This allows the edge structure itself to be a very compact data 0127 /// structure: essentially a tagged pointer. 0128 class Edge { 0129 public: 0130 /// The kind of edge in the graph. 0131 enum Kind : bool { Ref = false, Call = true }; 0132 0133 Edge(); 0134 explicit Edge(Node &N, Kind K); 0135 0136 /// Test whether the edge is null. 0137 /// 0138 /// This happens when an edge has been deleted. We leave the edge objects 0139 /// around but clear them. 0140 explicit operator bool() const; 0141 0142 /// Returns the \c Kind of the edge. 0143 Kind getKind() const; 0144 0145 /// Test whether the edge represents a direct call to a function. 0146 /// 0147 /// This requires that the edge is not null. 0148 bool isCall() const; 0149 0150 /// Get the call graph node referenced by this edge. 0151 /// 0152 /// This requires that the edge is not null. 0153 Node &getNode() const; 0154 0155 /// Get the function referenced by this edge. 0156 /// 0157 /// This requires that the edge is not null. 0158 Function &getFunction() const; 0159 0160 private: 0161 friend class LazyCallGraph::EdgeSequence; 0162 friend class LazyCallGraph::RefSCC; 0163 0164 PointerIntPair<Node *, 1, Kind> Value; 0165 0166 void setKind(Kind K) { Value.setInt(K); } 0167 }; 0168 0169 /// The edge sequence object. 0170 /// 0171 /// This typically exists entirely within the node but is exposed as 0172 /// a separate type because a node doesn't initially have edges. An explicit 0173 /// population step is required to produce this sequence at first and it is 0174 /// then cached in the node. It is also used to represent edges entering the 0175 /// graph from outside the module to model the graph's roots. 0176 /// 0177 /// The sequence itself both iterable and indexable. The indexes remain 0178 /// stable even as the sequence mutates (including removal). 0179 class EdgeSequence { 0180 friend class LazyCallGraph; 0181 friend class LazyCallGraph::Node; 0182 friend class LazyCallGraph::RefSCC; 0183 0184 using VectorT = SmallVector<Edge, 4>; 0185 using VectorImplT = SmallVectorImpl<Edge>; 0186 0187 public: 0188 /// An iterator used for the edges to both entry nodes and child nodes. 0189 class iterator 0190 : public iterator_adaptor_base<iterator, VectorImplT::iterator, 0191 std::forward_iterator_tag> { 0192 friend class LazyCallGraph; 0193 friend class LazyCallGraph::Node; 0194 0195 VectorImplT::iterator E; 0196 0197 // Build the iterator for a specific position in the edge list. 0198 iterator(VectorImplT::iterator BaseI, VectorImplT::iterator E) 0199 : iterator_adaptor_base(BaseI), E(E) { 0200 while (I != E && !*I) 0201 ++I; 0202 } 0203 0204 public: 0205 iterator() = default; 0206 0207 using iterator_adaptor_base::operator++; 0208 iterator &operator++() { 0209 do { 0210 ++I; 0211 } while (I != E && !*I); 0212 return *this; 0213 } 0214 }; 0215 0216 /// An iterator over specifically call edges. 0217 /// 0218 /// This has the same iteration properties as the \c iterator, but 0219 /// restricts itself to edges which represent actual calls. 0220 class call_iterator 0221 : public iterator_adaptor_base<call_iterator, VectorImplT::iterator, 0222 std::forward_iterator_tag> { 0223 friend class LazyCallGraph; 0224 friend class LazyCallGraph::Node; 0225 0226 VectorImplT::iterator E; 0227 0228 /// Advance the iterator to the next valid, call edge. 0229 void advanceToNextEdge() { 0230 while (I != E && (!*I || !I->isCall())) 0231 ++I; 0232 } 0233 0234 // Build the iterator for a specific position in the edge list. 0235 call_iterator(VectorImplT::iterator BaseI, VectorImplT::iterator E) 0236 : iterator_adaptor_base(BaseI), E(E) { 0237 advanceToNextEdge(); 0238 } 0239 0240 public: 0241 call_iterator() = default; 0242 0243 using iterator_adaptor_base::operator++; 0244 call_iterator &operator++() { 0245 ++I; 0246 advanceToNextEdge(); 0247 return *this; 0248 } 0249 }; 0250 0251 iterator begin() { return iterator(Edges.begin(), Edges.end()); } 0252 iterator end() { return iterator(Edges.end(), Edges.end()); } 0253 0254 Edge &operator[](Node &N) { 0255 assert(EdgeIndexMap.contains(&N) && "No such edge!"); 0256 auto &E = Edges[EdgeIndexMap.find(&N)->second]; 0257 assert(E && "Dead or null edge!"); 0258 return E; 0259 } 0260 0261 Edge *lookup(Node &N) { 0262 auto EI = EdgeIndexMap.find(&N); 0263 if (EI == EdgeIndexMap.end()) 0264 return nullptr; 0265 auto &E = Edges[EI->second]; 0266 return E ? &E : nullptr; 0267 } 0268 0269 call_iterator call_begin() { 0270 return call_iterator(Edges.begin(), Edges.end()); 0271 } 0272 call_iterator call_end() { return call_iterator(Edges.end(), Edges.end()); } 0273 0274 iterator_range<call_iterator> calls() { 0275 return make_range(call_begin(), call_end()); 0276 } 0277 0278 bool empty() { 0279 for (auto &E : Edges) 0280 if (E) 0281 return false; 0282 0283 return true; 0284 } 0285 0286 private: 0287 VectorT Edges; 0288 DenseMap<Node *, int> EdgeIndexMap; 0289 0290 EdgeSequence() = default; 0291 0292 /// Internal helper to insert an edge to a node. 0293 void insertEdgeInternal(Node &ChildN, Edge::Kind EK); 0294 0295 /// Internal helper to change an edge kind. 0296 void setEdgeKind(Node &ChildN, Edge::Kind EK); 0297 0298 /// Internal helper to remove the edge to the given function. 0299 bool removeEdgeInternal(Node &ChildN); 0300 }; 0301 0302 /// A node in the call graph. 0303 /// 0304 /// This represents a single node. Its primary roles are to cache the list of 0305 /// callees, de-duplicate and provide fast testing of whether a function is a 0306 /// callee, and facilitate iteration of child nodes in the graph. 0307 /// 0308 /// The node works much like an optional in order to lazily populate the 0309 /// edges of each node. Until populated, there are no edges. Once populated, 0310 /// you can access the edges by dereferencing the node or using the `->` 0311 /// operator as if the node was an `std::optional<EdgeSequence>`. 0312 class Node { 0313 friend class LazyCallGraph; 0314 friend class LazyCallGraph::RefSCC; 0315 0316 public: 0317 LazyCallGraph &getGraph() const { return *G; } 0318 0319 Function &getFunction() const { return *F; } 0320 0321 StringRef getName() const { return F->getName(); } 0322 0323 /// Equality is defined as address equality. 0324 bool operator==(const Node &N) const { return this == &N; } 0325 bool operator!=(const Node &N) const { return !operator==(N); } 0326 0327 /// Tests whether the node has been populated with edges. 0328 bool isPopulated() const { return Edges.has_value(); } 0329 0330 /// Tests whether this is actually a dead node and no longer valid. 0331 /// 0332 /// Users rarely interact with nodes in this state and other methods are 0333 /// invalid. This is used to model a node in an edge list where the 0334 /// function has been completely removed. 0335 bool isDead() const { 0336 assert(!G == !F && 0337 "Both graph and function pointers should be null or non-null."); 0338 return !G; 0339 } 0340 0341 // We allow accessing the edges by dereferencing or using the arrow 0342 // operator, essentially wrapping the internal optional. 0343 EdgeSequence &operator*() const { 0344 // Rip const off because the node itself isn't changing here. 0345 return const_cast<EdgeSequence &>(*Edges); 0346 } 0347 EdgeSequence *operator->() const { return &**this; } 0348 0349 /// Populate the edges of this node if necessary. 0350 /// 0351 /// The first time this is called it will populate the edges for this node 0352 /// in the graph. It does this by scanning the underlying function, so once 0353 /// this is done, any changes to that function must be explicitly reflected 0354 /// in updates to the graph. 0355 /// 0356 /// \returns the populated \c EdgeSequence to simplify walking it. 0357 /// 0358 /// This will not update or re-scan anything if called repeatedly. Instead, 0359 /// the edge sequence is cached and returned immediately on subsequent 0360 /// calls. 0361 EdgeSequence &populate() { 0362 if (Edges) 0363 return *Edges; 0364 0365 return populateSlow(); 0366 } 0367 0368 private: 0369 LazyCallGraph *G; 0370 Function *F; 0371 0372 // We provide for the DFS numbering and Tarjan walk lowlink numbers to be 0373 // stored directly within the node. These are both '-1' when nodes are part 0374 // of an SCC (or RefSCC), or '0' when not yet reached in a DFS walk. 0375 int DFSNumber = 0; 0376 int LowLink = 0; 0377 0378 std::optional<EdgeSequence> Edges; 0379 0380 /// Basic constructor implements the scanning of F into Edges and 0381 /// EdgeIndexMap. 0382 Node(LazyCallGraph &G, Function &F) : G(&G), F(&F) {} 0383 0384 /// Implementation of the scan when populating. 0385 EdgeSequence &populateSlow(); 0386 0387 /// Internal helper to directly replace the function with a new one. 0388 /// 0389 /// This is used to facilitate transformations which need to replace the 0390 /// formal Function object but directly move the body and users from one to 0391 /// the other. 0392 void replaceFunction(Function &NewF); 0393 0394 void clear() { Edges.reset(); } 0395 0396 /// Print the name of this node's function. 0397 friend raw_ostream &operator<<(raw_ostream &OS, const Node &N) { 0398 return OS << N.F->getName(); 0399 } 0400 0401 /// Dump the name of this node's function to stderr. 0402 void dump() const; 0403 }; 0404 0405 /// An SCC of the call graph. 0406 /// 0407 /// This represents a Strongly Connected Component of the direct call graph 0408 /// -- ignoring indirect calls and function references. It stores this as 0409 /// a collection of call graph nodes. While the order of nodes in the SCC is 0410 /// stable, it is not any particular order. 0411 /// 0412 /// The SCCs are nested within a \c RefSCC, see below for details about that 0413 /// outer structure. SCCs do not support mutation of the call graph, that 0414 /// must be done through the containing \c RefSCC in order to fully reason 0415 /// about the ordering and connections of the graph. 0416 class LLVM_ABI SCC { 0417 friend class LazyCallGraph; 0418 friend class LazyCallGraph::Node; 0419 0420 RefSCC *OuterRefSCC; 0421 SmallVector<Node *, 1> Nodes; 0422 0423 template <typename NodeRangeT> 0424 SCC(RefSCC &OuterRefSCC, NodeRangeT &&Nodes) 0425 : OuterRefSCC(&OuterRefSCC), Nodes(std::forward<NodeRangeT>(Nodes)) {} 0426 0427 void clear() { 0428 OuterRefSCC = nullptr; 0429 Nodes.clear(); 0430 } 0431 0432 /// Print a short description useful for debugging or logging. 0433 /// 0434 /// We print the function names in the SCC wrapped in '()'s and skipping 0435 /// the middle functions if there are a large number. 0436 // 0437 // Note: this is defined inline to dodge issues with GCC's interpretation 0438 // of enclosing namespaces for friend function declarations. 0439 friend raw_ostream &operator<<(raw_ostream &OS, const SCC &C) { 0440 OS << '('; 0441 int I = 0; 0442 for (LazyCallGraph::Node &N : C) { 0443 if (I > 0) 0444 OS << ", "; 0445 // Elide the inner elements if there are too many. 0446 if (I > 8) { 0447 OS << "..., " << *C.Nodes.back(); 0448 break; 0449 } 0450 OS << N; 0451 ++I; 0452 } 0453 OS << ')'; 0454 return OS; 0455 } 0456 0457 /// Dump a short description of this SCC to stderr. 0458 void dump() const; 0459 0460 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 0461 /// Verify invariants about the SCC. 0462 /// 0463 /// This will attempt to validate all of the basic invariants within an 0464 /// SCC, but not that it is a strongly connected component per se. 0465 /// Primarily useful while building and updating the graph to check that 0466 /// basic properties are in place rather than having inexplicable crashes 0467 /// later. 0468 void verify(); 0469 #endif 0470 0471 public: 0472 using iterator = pointee_iterator<SmallVectorImpl<Node *>::const_iterator>; 0473 0474 iterator begin() const { return Nodes.begin(); } 0475 iterator end() const { return Nodes.end(); } 0476 0477 int size() const { return Nodes.size(); } 0478 0479 RefSCC &getOuterRefSCC() const { return *OuterRefSCC; } 0480 0481 /// Test if this SCC is a parent of \a C. 0482 /// 0483 /// Note that this is linear in the number of edges departing the current 0484 /// SCC. 0485 bool isParentOf(const SCC &C) const; 0486 0487 /// Test if this SCC is an ancestor of \a C. 0488 /// 0489 /// Note that in the worst case this is linear in the number of edges 0490 /// departing the current SCC and every SCC in the entire graph reachable 0491 /// from this SCC. Thus this very well may walk every edge in the entire 0492 /// call graph! Do not call this in a tight loop! 0493 bool isAncestorOf(const SCC &C) const; 0494 0495 /// Test if this SCC is a child of \a C. 0496 /// 0497 /// See the comments for \c isParentOf for detailed notes about the 0498 /// complexity of this routine. 0499 bool isChildOf(const SCC &C) const { return C.isParentOf(*this); } 0500 0501 /// Test if this SCC is a descendant of \a C. 0502 /// 0503 /// See the comments for \c isParentOf for detailed notes about the 0504 /// complexity of this routine. 0505 bool isDescendantOf(const SCC &C) const { return C.isAncestorOf(*this); } 0506 0507 /// Provide a short name by printing this SCC to a std::string. 0508 /// 0509 /// This copes with the fact that we don't have a name per se for an SCC 0510 /// while still making the use of this in debugging and logging useful. 0511 std::string getName() const { 0512 std::string Name; 0513 raw_string_ostream OS(Name); 0514 OS << *this; 0515 OS.flush(); 0516 return Name; 0517 } 0518 }; 0519 0520 /// A RefSCC of the call graph. 0521 /// 0522 /// This models a Strongly Connected Component of function reference edges in 0523 /// the call graph. As opposed to actual SCCs, these can be used to scope 0524 /// subgraphs of the module which are independent from other subgraphs of the 0525 /// module because they do not reference it in any way. This is also the unit 0526 /// where we do mutation of the graph in order to restrict mutations to those 0527 /// which don't violate this independence. 0528 /// 0529 /// A RefSCC contains a DAG of actual SCCs. All the nodes within the RefSCC 0530 /// are necessarily within some actual SCC that nests within it. Since 0531 /// a direct call *is* a reference, there will always be at least one RefSCC 0532 /// around any SCC. 0533 /// 0534 /// Spurious ref edges, meaning ref edges that still exist in the call graph 0535 /// even though the corresponding IR reference no longer exists, are allowed. 0536 /// This is mostly to support argument promotion, which can modify a caller to 0537 /// no longer pass a function. The only place that needs to specially handle 0538 /// this is deleting a dead function/node, otherwise the dead ref edges are 0539 /// automatically removed when visiting the function/node no longer containing 0540 /// the ref edge. 0541 class RefSCC { 0542 friend class LazyCallGraph; 0543 friend class LazyCallGraph::Node; 0544 0545 LazyCallGraph *G; 0546 0547 /// A postorder list of the inner SCCs. 0548 SmallVector<SCC *, 4> SCCs; 0549 0550 /// A map from SCC to index in the postorder list. 0551 SmallDenseMap<SCC *, int, 4> SCCIndices; 0552 0553 /// Fast-path constructor. RefSCCs should instead be constructed by calling 0554 /// formRefSCCFast on the graph itself. 0555 RefSCC(LazyCallGraph &G); 0556 0557 void clear() { 0558 SCCs.clear(); 0559 SCCIndices.clear(); 0560 } 0561 0562 /// Print a short description useful for debugging or logging. 0563 /// 0564 /// We print the SCCs wrapped in '[]'s and skipping the middle SCCs if 0565 /// there are a large number. 0566 // 0567 // Note: this is defined inline to dodge issues with GCC's interpretation 0568 // of enclosing namespaces for friend function declarations. 0569 friend raw_ostream &operator<<(raw_ostream &OS, const RefSCC &RC) { 0570 OS << '['; 0571 int I = 0; 0572 for (LazyCallGraph::SCC &C : RC) { 0573 if (I > 0) 0574 OS << ", "; 0575 // Elide the inner elements if there are too many. 0576 if (I > 4) { 0577 OS << "..., " << *RC.SCCs.back(); 0578 break; 0579 } 0580 OS << C; 0581 ++I; 0582 } 0583 OS << ']'; 0584 return OS; 0585 } 0586 0587 /// Dump a short description of this RefSCC to stderr. 0588 void dump() const; 0589 0590 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 0591 /// Verify invariants about the RefSCC and all its SCCs. 0592 /// 0593 /// This will attempt to validate all of the invariants *within* the 0594 /// RefSCC, but not that it is a strongly connected component of the larger 0595 /// graph. This makes it useful even when partially through an update. 0596 /// 0597 /// Invariants checked: 0598 /// - SCCs and their indices match. 0599 /// - The SCCs list is in fact in post-order. 0600 void verify(); 0601 #endif 0602 0603 public: 0604 using iterator = pointee_iterator<SmallVectorImpl<SCC *>::const_iterator>; 0605 using range = iterator_range<iterator>; 0606 using parent_iterator = 0607 pointee_iterator<SmallPtrSetImpl<RefSCC *>::const_iterator>; 0608 0609 iterator begin() const { return SCCs.begin(); } 0610 iterator end() const { return SCCs.end(); } 0611 0612 ssize_t size() const { return SCCs.size(); } 0613 0614 SCC &operator[](int Idx) { return *SCCs[Idx]; } 0615 0616 iterator find(SCC &C) const { 0617 return SCCs.begin() + SCCIndices.find(&C)->second; 0618 } 0619 0620 /// Test if this RefSCC is a parent of \a RC. 0621 /// 0622 /// CAUTION: This method walks every edge in the \c RefSCC, it can be very 0623 /// expensive. 0624 bool isParentOf(const RefSCC &RC) const; 0625 0626 /// Test if this RefSCC is an ancestor of \a RC. 0627 /// 0628 /// CAUTION: This method walks the directed graph of edges as far as 0629 /// necessary to find a possible path to the argument. In the worst case 0630 /// this may walk the entire graph and can be extremely expensive. 0631 bool isAncestorOf(const RefSCC &RC) const; 0632 0633 /// Test if this RefSCC is a child of \a RC. 0634 /// 0635 /// CAUTION: This method walks every edge in the argument \c RefSCC, it can 0636 /// be very expensive. 0637 bool isChildOf(const RefSCC &RC) const { return RC.isParentOf(*this); } 0638 0639 /// Test if this RefSCC is a descendant of \a RC. 0640 /// 0641 /// CAUTION: This method walks the directed graph of edges as far as 0642 /// necessary to find a possible path from the argument. In the worst case 0643 /// this may walk the entire graph and can be extremely expensive. 0644 bool isDescendantOf(const RefSCC &RC) const { 0645 return RC.isAncestorOf(*this); 0646 } 0647 0648 /// Provide a short name by printing this RefSCC to a std::string. 0649 /// 0650 /// This copes with the fact that we don't have a name per se for an RefSCC 0651 /// while still making the use of this in debugging and logging useful. 0652 std::string getName() const { 0653 std::string Name; 0654 raw_string_ostream OS(Name); 0655 OS << *this; 0656 OS.flush(); 0657 return Name; 0658 } 0659 0660 ///@{ 0661 /// \name Mutation API 0662 /// 0663 /// These methods provide the core API for updating the call graph in the 0664 /// presence of (potentially still in-flight) DFS-found RefSCCs and SCCs. 0665 /// 0666 /// Note that these methods sometimes have complex runtimes, so be careful 0667 /// how you call them. 0668 0669 /// Make an existing internal ref edge into a call edge. 0670 /// 0671 /// This may form a larger cycle and thus collapse SCCs into TargetN's SCC. 0672 /// If that happens, the optional callback \p MergedCB will be invoked (if 0673 /// provided) on the SCCs being merged away prior to actually performing 0674 /// the merge. Note that this will never include the target SCC as that 0675 /// will be the SCC functions are merged into to resolve the cycle. Once 0676 /// this function returns, these merged SCCs are not in a valid state but 0677 /// the pointers will remain valid until destruction of the parent graph 0678 /// instance for the purpose of clearing cached information. This function 0679 /// also returns 'true' if a cycle was formed and some SCCs merged away as 0680 /// a convenience. 0681 /// 0682 /// After this operation, both SourceN's SCC and TargetN's SCC may move 0683 /// position within this RefSCC's postorder list. Any SCCs merged are 0684 /// merged into the TargetN's SCC in order to preserve reachability analyses 0685 /// which took place on that SCC. 0686 bool switchInternalEdgeToCall( 0687 Node &SourceN, Node &TargetN, 0688 function_ref<void(ArrayRef<SCC *> MergedSCCs)> MergeCB = {}); 0689 0690 /// Make an existing internal call edge between separate SCCs into a ref 0691 /// edge. 0692 /// 0693 /// If SourceN and TargetN in separate SCCs within this RefSCC, changing 0694 /// the call edge between them to a ref edge is a trivial operation that 0695 /// does not require any structural changes to the call graph. 0696 void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN); 0697 0698 /// Make an existing internal call edge within a single SCC into a ref 0699 /// edge. 0700 /// 0701 /// Since SourceN and TargetN are part of a single SCC, this SCC may be 0702 /// split up due to breaking a cycle in the call edges that formed it. If 0703 /// that happens, then this routine will insert new SCCs into the postorder 0704 /// list *before* the SCC of TargetN (previously the SCC of both). This 0705 /// preserves postorder as the TargetN can reach all of the other nodes by 0706 /// definition of previously being in a single SCC formed by the cycle from 0707 /// SourceN to TargetN. 0708 /// 0709 /// The newly added SCCs are added *immediately* and contiguously 0710 /// prior to the TargetN SCC and return the range covering the new SCCs in 0711 /// the RefSCC's postorder sequence. You can directly iterate the returned 0712 /// range to observe all of the new SCCs in postorder. 0713 /// 0714 /// Note that if SourceN and TargetN are in separate SCCs, the simpler 0715 /// routine `switchTrivialInternalEdgeToRef` should be used instead. 0716 iterator_range<iterator> switchInternalEdgeToRef(Node &SourceN, 0717 Node &TargetN); 0718 0719 /// Make an existing outgoing ref edge into a call edge. 0720 /// 0721 /// Note that this is trivial as there are no cyclic impacts and there 0722 /// remains a reference edge. 0723 void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN); 0724 0725 /// Make an existing outgoing call edge into a ref edge. 0726 /// 0727 /// This is trivial as there are no cyclic impacts and there remains 0728 /// a reference edge. 0729 void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN); 0730 0731 /// Insert a ref edge from one node in this RefSCC to another in this 0732 /// RefSCC. 0733 /// 0734 /// This is always a trivial operation as it doesn't change any part of the 0735 /// graph structure besides connecting the two nodes. 0736 /// 0737 /// Note that we don't support directly inserting internal *call* edges 0738 /// because that could change the graph structure and requires returning 0739 /// information about what became invalid. As a consequence, the pattern 0740 /// should be to first insert the necessary ref edge, and then to switch it 0741 /// to a call edge if needed and handle any invalidation that results. See 0742 /// the \c switchInternalEdgeToCall routine for details. 0743 void insertInternalRefEdge(Node &SourceN, Node &TargetN); 0744 0745 /// Insert an edge whose parent is in this RefSCC and child is in some 0746 /// child RefSCC. 0747 /// 0748 /// There must be an existing path from the \p SourceN to the \p TargetN. 0749 /// This operation is inexpensive and does not change the set of SCCs and 0750 /// RefSCCs in the graph. 0751 void insertOutgoingEdge(Node &SourceN, Node &TargetN, Edge::Kind EK); 0752 0753 /// Insert an edge whose source is in a descendant RefSCC and target is in 0754 /// this RefSCC. 0755 /// 0756 /// There must be an existing path from the target to the source in this 0757 /// case. 0758 /// 0759 /// NB! This is has the potential to be a very expensive function. It 0760 /// inherently forms a cycle in the prior RefSCC DAG and we have to merge 0761 /// RefSCCs to resolve that cycle. But finding all of the RefSCCs which 0762 /// participate in the cycle can in the worst case require traversing every 0763 /// RefSCC in the graph. Every attempt is made to avoid that, but passes 0764 /// must still exercise caution calling this routine repeatedly. 0765 /// 0766 /// Also note that this can only insert ref edges. In order to insert 0767 /// a call edge, first insert a ref edge and then switch it to a call edge. 0768 /// These are intentionally kept as separate interfaces because each step 0769 /// of the operation invalidates a different set of data structures. 0770 /// 0771 /// This returns all the RefSCCs which were merged into the this RefSCC 0772 /// (the target's). This allows callers to invalidate any cached 0773 /// information. 0774 /// 0775 /// FIXME: We could possibly optimize this quite a bit for cases where the 0776 /// caller and callee are very nearby in the graph. See comments in the 0777 /// implementation for details, but that use case might impact users. 0778 SmallVector<RefSCC *, 1> insertIncomingRefEdge(Node &SourceN, 0779 Node &TargetN); 0780 0781 /// Remove an edge whose source is in this RefSCC and target is *not*. 0782 /// 0783 /// This removes an inter-RefSCC edge. All inter-RefSCC edges originating 0784 /// from this SCC have been fully explored by any in-flight DFS graph 0785 /// formation, so this is always safe to call once you have the source 0786 /// RefSCC. 0787 /// 0788 /// This operation does not change the cyclic structure of the graph and so 0789 /// is very inexpensive. It may change the connectivity graph of the SCCs 0790 /// though, so be careful calling this while iterating over them. 0791 void removeOutgoingEdge(Node &SourceN, Node &TargetN); 0792 0793 /// Remove a list of ref edges which are entirely within this RefSCC. 0794 /// 0795 /// Both the \a SourceN and all of the \a TargetNs must be within this 0796 /// RefSCC. Removing these edges may break cycles that form this RefSCC and 0797 /// thus this operation may change the RefSCC graph significantly. In 0798 /// particular, this operation will re-form new RefSCCs based on the 0799 /// remaining connectivity of the graph. The following invariants are 0800 /// guaranteed to hold after calling this method: 0801 /// 0802 /// 1) If a ref-cycle remains after removal, it leaves this RefSCC intact 0803 /// and in the graph. No new RefSCCs are built. 0804 /// 2) Otherwise, this RefSCC will be dead after this call and no longer in 0805 /// the graph or the postorder traversal of the call graph. Any iterator 0806 /// pointing at this RefSCC will become invalid. 0807 /// 3) All newly formed RefSCCs will be returned and the order of the 0808 /// RefSCCs returned will be a valid postorder traversal of the new 0809 /// RefSCCs. 0810 /// 4) No RefSCC other than this RefSCC has its member set changed (this is 0811 /// inherent in the definition of removing such an edge). 0812 /// 0813 /// These invariants are very important to ensure that we can build 0814 /// optimization pipelines on top of the CGSCC pass manager which 0815 /// intelligently update the RefSCC graph without invalidating other parts 0816 /// of the RefSCC graph. 0817 /// 0818 /// Note that we provide no routine to remove a *call* edge. Instead, you 0819 /// must first switch it to a ref edge using \c switchInternalEdgeToRef. 0820 /// This split API is intentional as each of these two steps can invalidate 0821 /// a different aspect of the graph structure and needs to have the 0822 /// invalidation handled independently. 0823 /// 0824 /// The runtime complexity of this method is, in the worst case, O(V+E) 0825 /// where V is the number of nodes in this RefSCC and E is the number of 0826 /// edges leaving the nodes in this RefSCC. Note that E includes both edges 0827 /// within this RefSCC and edges from this RefSCC to child RefSCCs. Some 0828 /// effort has been made to minimize the overhead of common cases such as 0829 /// self-edges and edge removals which result in a spanning tree with no 0830 /// more cycles. 0831 [[nodiscard]] SmallVector<RefSCC *, 1> 0832 removeInternalRefEdges(ArrayRef<std::pair<Node *, Node *>> Edges); 0833 0834 /// A convenience wrapper around the above to handle trivial cases of 0835 /// inserting a new call edge. 0836 /// 0837 /// This is trivial whenever the target is in the same SCC as the source or 0838 /// the edge is an outgoing edge to some descendant SCC. In these cases 0839 /// there is no change to the cyclic structure of SCCs or RefSCCs. 0840 /// 0841 /// To further make calling this convenient, it also handles inserting 0842 /// already existing edges. 0843 void insertTrivialCallEdge(Node &SourceN, Node &TargetN); 0844 0845 /// A convenience wrapper around the above to handle trivial cases of 0846 /// inserting a new ref edge. 0847 /// 0848 /// This is trivial whenever the target is in the same RefSCC as the source 0849 /// or the edge is an outgoing edge to some descendant RefSCC. In these 0850 /// cases there is no change to the cyclic structure of the RefSCCs. 0851 /// 0852 /// To further make calling this convenient, it also handles inserting 0853 /// already existing edges. 0854 void insertTrivialRefEdge(Node &SourceN, Node &TargetN); 0855 0856 /// Directly replace a node's function with a new function. 0857 /// 0858 /// This should be used when moving the body and users of a function to 0859 /// a new formal function object but not otherwise changing the call graph 0860 /// structure in any way. 0861 /// 0862 /// It requires that the old function in the provided node have zero uses 0863 /// and the new function must have calls and references to it establishing 0864 /// an equivalent graph. 0865 void replaceNodeFunction(Node &N, Function &NewF); 0866 0867 ///@} 0868 }; 0869 0870 /// A post-order depth-first RefSCC iterator over the call graph. 0871 /// 0872 /// This iterator walks the cached post-order sequence of RefSCCs. However, 0873 /// it trades stability for flexibility. It is restricted to a forward 0874 /// iterator but will survive mutations which insert new RefSCCs and continue 0875 /// to point to the same RefSCC even if it moves in the post-order sequence. 0876 class postorder_ref_scc_iterator 0877 : public iterator_facade_base<postorder_ref_scc_iterator, 0878 std::forward_iterator_tag, RefSCC> { 0879 friend class LazyCallGraph; 0880 friend class LazyCallGraph::Node; 0881 0882 /// Nonce type to select the constructor for the end iterator. 0883 struct IsAtEndT {}; 0884 0885 LazyCallGraph *G; 0886 RefSCC *RC = nullptr; 0887 0888 /// Build the begin iterator for a node. 0889 postorder_ref_scc_iterator(LazyCallGraph &G) : G(&G), RC(getRC(G, 0)) { 0890 incrementUntilNonEmptyRefSCC(); 0891 } 0892 0893 /// Build the end iterator for a node. This is selected purely by overload. 0894 postorder_ref_scc_iterator(LazyCallGraph &G, IsAtEndT /*Nonce*/) : G(&G) {} 0895 0896 /// Get the post-order RefSCC at the given index of the postorder walk, 0897 /// populating it if necessary. 0898 static RefSCC *getRC(LazyCallGraph &G, int Index) { 0899 if (Index == (int)G.PostOrderRefSCCs.size()) 0900 // We're at the end. 0901 return nullptr; 0902 0903 return G.PostOrderRefSCCs[Index]; 0904 } 0905 0906 // Keep incrementing until RC is non-empty (or null). 0907 void incrementUntilNonEmptyRefSCC() { 0908 while (RC && RC->size() == 0) 0909 increment(); 0910 } 0911 0912 void increment() { 0913 assert(RC && "Cannot increment the end iterator!"); 0914 RC = getRC(*G, G->RefSCCIndices.find(RC)->second + 1); 0915 } 0916 0917 public: 0918 bool operator==(const postorder_ref_scc_iterator &Arg) const { 0919 return G == Arg.G && RC == Arg.RC; 0920 } 0921 0922 reference operator*() const { return *RC; } 0923 0924 using iterator_facade_base::operator++; 0925 postorder_ref_scc_iterator &operator++() { 0926 increment(); 0927 incrementUntilNonEmptyRefSCC(); 0928 return *this; 0929 } 0930 }; 0931 0932 /// Construct a graph for the given module. 0933 /// 0934 /// This sets up the graph and computes all of the entry points of the graph. 0935 /// No function definitions are scanned until their nodes in the graph are 0936 /// requested during traversal. 0937 LazyCallGraph(Module &M, 0938 function_ref<TargetLibraryInfo &(Function &)> GetTLI); 0939 0940 LazyCallGraph(LazyCallGraph &&G); 0941 LazyCallGraph &operator=(LazyCallGraph &&RHS); 0942 0943 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 0944 /// Verify that every RefSCC is valid. 0945 void verify(); 0946 #endif 0947 0948 bool invalidate(Module &, const PreservedAnalyses &PA, 0949 ModuleAnalysisManager::Invalidator &); 0950 0951 EdgeSequence::iterator begin() { return EntryEdges.begin(); } 0952 EdgeSequence::iterator end() { return EntryEdges.end(); } 0953 0954 void buildRefSCCs(); 0955 0956 postorder_ref_scc_iterator postorder_ref_scc_begin() { 0957 if (!EntryEdges.empty()) 0958 assert(!PostOrderRefSCCs.empty() && 0959 "Must form RefSCCs before iterating them!"); 0960 return postorder_ref_scc_iterator(*this); 0961 } 0962 postorder_ref_scc_iterator postorder_ref_scc_end() { 0963 if (!EntryEdges.empty()) 0964 assert(!PostOrderRefSCCs.empty() && 0965 "Must form RefSCCs before iterating them!"); 0966 return postorder_ref_scc_iterator(*this, 0967 postorder_ref_scc_iterator::IsAtEndT()); 0968 } 0969 0970 iterator_range<postorder_ref_scc_iterator> postorder_ref_sccs() { 0971 return make_range(postorder_ref_scc_begin(), postorder_ref_scc_end()); 0972 } 0973 0974 /// Lookup a function in the graph which has already been scanned and added. 0975 Node *lookup(const Function &F) const { return NodeMap.lookup(&F); } 0976 0977 /// Lookup a function's SCC in the graph. 0978 /// 0979 /// \returns null if the function hasn't been assigned an SCC via the RefSCC 0980 /// iterator walk. 0981 SCC *lookupSCC(Node &N) const { return SCCMap.lookup(&N); } 0982 0983 /// Lookup a function's RefSCC in the graph. 0984 /// 0985 /// \returns null if the function hasn't been assigned a RefSCC via the 0986 /// RefSCC iterator walk. 0987 RefSCC *lookupRefSCC(Node &N) const { 0988 if (SCC *C = lookupSCC(N)) 0989 return &C->getOuterRefSCC(); 0990 0991 return nullptr; 0992 } 0993 0994 /// Get a graph node for a given function, scanning it to populate the graph 0995 /// data as necessary. 0996 Node &get(Function &F) { 0997 Node *&N = NodeMap[&F]; 0998 if (N) 0999 return *N; 1000 1001 return insertInto(F, N); 1002 } 1003 1004 /// Get the sequence of known and defined library functions. 1005 /// 1006 /// These functions, because they are known to LLVM, can have calls 1007 /// introduced out of thin air from arbitrary IR. 1008 ArrayRef<Function *> getLibFunctions() const { 1009 return LibFunctions.getArrayRef(); 1010 } 1011 1012 /// Test whether a function is a known and defined library function tracked by 1013 /// the call graph. 1014 /// 1015 /// Because these functions are known to LLVM they are specially modeled in 1016 /// the call graph and even when all IR-level references have been removed 1017 /// remain active and reachable. 1018 bool isLibFunction(Function &F) const { return LibFunctions.count(&F); } 1019 1020 ///@{ 1021 /// \name Pre-SCC Mutation API 1022 /// 1023 /// These methods are only valid to call prior to forming any SCCs for this 1024 /// call graph. They can be used to update the core node-graph during 1025 /// a node-based inorder traversal that precedes any SCC-based traversal. 1026 /// 1027 /// Once you begin manipulating a call graph's SCCs, most mutation of the 1028 /// graph must be performed via a RefSCC method. There are some exceptions 1029 /// below. 1030 1031 /// Update the call graph after inserting a new edge. 1032 void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK); 1033 1034 /// Update the call graph after inserting a new edge. 1035 void insertEdge(Function &Source, Function &Target, Edge::Kind EK) { 1036 return insertEdge(get(Source), get(Target), EK); 1037 } 1038 1039 /// Update the call graph after deleting an edge. 1040 void removeEdge(Node &SourceN, Node &TargetN); 1041 1042 /// Update the call graph after deleting an edge. 1043 void removeEdge(Function &Source, Function &Target) { 1044 return removeEdge(get(Source), get(Target)); 1045 } 1046 1047 ///@} 1048 1049 ///@{ 1050 /// \name General Mutation API 1051 /// 1052 /// There are a very limited set of mutations allowed on the graph as a whole 1053 /// once SCCs have started to be formed. These routines have strict contracts 1054 /// but may be called at any point. 1055 1056 /// Remove dead functions from the call graph. 1057 /// 1058 /// These functions should have already been passed to markDeadFunction(). 1059 /// This is done as a batch to prevent compile time blowup as a result of 1060 /// handling a single function at a time. 1061 void removeDeadFunctions(ArrayRef<Function *> DeadFs); 1062 1063 /// Mark a function as dead to be removed later by removeDeadFunctions(). 1064 /// 1065 /// The function body should have no incoming or outgoing call or ref edges. 1066 /// For example, a function with a single "unreachable" instruction. 1067 void markDeadFunction(Function &F); 1068 1069 /// Add a new function split/outlined from an existing function. 1070 /// 1071 /// The new function may only reference other functions that the original 1072 /// function did. 1073 /// 1074 /// The original function must reference (either directly or indirectly) the 1075 /// new function. 1076 /// 1077 /// The new function may also reference the original function. 1078 /// It may end up in a parent SCC in the case that the original function's 1079 /// edge to the new function is a ref edge, and the edge back is a call edge. 1080 void addSplitFunction(Function &OriginalFunction, Function &NewFunction); 1081 1082 /// Add new ref-recursive functions split/outlined from an existing function. 1083 /// 1084 /// The new functions may only reference other functions that the original 1085 /// function did. The new functions may reference (not call) the original 1086 /// function. 1087 /// 1088 /// The original function must reference (not call) all new functions. 1089 /// All new functions must reference (not call) each other. 1090 void addSplitRefRecursiveFunctions(Function &OriginalFunction, 1091 ArrayRef<Function *> NewFunctions); 1092 1093 ///@} 1094 1095 ///@{ 1096 /// \name Static helpers for code doing updates to the call graph. 1097 /// 1098 /// These helpers are used to implement parts of the call graph but are also 1099 /// useful to code doing updates or otherwise wanting to walk the IR in the 1100 /// same patterns as when we build the call graph. 1101 1102 /// Recursively visits the defined functions whose address is reachable from 1103 /// every constant in the \p Worklist. 1104 /// 1105 /// Doesn't recurse through any constants already in the \p Visited set, and 1106 /// updates that set with every constant visited. 1107 /// 1108 /// For each defined function, calls \p Callback with that function. 1109 static void visitReferences(SmallVectorImpl<Constant *> &Worklist, 1110 SmallPtrSetImpl<Constant *> &Visited, 1111 function_ref<void(Function &)> Callback); 1112 1113 ///@} 1114 1115 private: 1116 using node_stack_iterator = SmallVectorImpl<Node *>::reverse_iterator; 1117 using node_stack_range = iterator_range<node_stack_iterator>; 1118 1119 /// Allocator that holds all the call graph nodes. 1120 SpecificBumpPtrAllocator<Node> BPA; 1121 1122 /// Maps function->node for fast lookup. 1123 DenseMap<const Function *, Node *> NodeMap; 1124 1125 /// The entry edges into the graph. 1126 /// 1127 /// These edges are from "external" sources. Put another way, they 1128 /// escape at the module scope. 1129 EdgeSequence EntryEdges; 1130 1131 /// Allocator that holds all the call graph SCCs. 1132 SpecificBumpPtrAllocator<SCC> SCCBPA; 1133 1134 /// Maps Function -> SCC for fast lookup. 1135 DenseMap<Node *, SCC *> SCCMap; 1136 1137 /// Allocator that holds all the call graph RefSCCs. 1138 SpecificBumpPtrAllocator<RefSCC> RefSCCBPA; 1139 1140 /// The post-order sequence of RefSCCs. 1141 /// 1142 /// This list is lazily formed the first time we walk the graph. 1143 SmallVector<RefSCC *, 16> PostOrderRefSCCs; 1144 1145 /// A map from RefSCC to the index for it in the postorder sequence of 1146 /// RefSCCs. 1147 DenseMap<RefSCC *, int> RefSCCIndices; 1148 1149 /// Defined functions that are also known library functions which the 1150 /// optimizer can reason about and therefore might introduce calls to out of 1151 /// thin air. 1152 SmallSetVector<Function *, 4> LibFunctions; 1153 1154 /// Helper to insert a new function, with an already looked-up entry in 1155 /// the NodeMap. 1156 Node &insertInto(Function &F, Node *&MappedN); 1157 1158 /// Helper to initialize a new node created outside of creating SCCs and add 1159 /// it to the NodeMap if necessary. For example, useful when a function is 1160 /// split. 1161 Node &initNode(Function &F); 1162 1163 /// Helper to update pointers back to the graph object during moves. 1164 void updateGraphPtrs(); 1165 1166 /// Allocates an SCC and constructs it using the graph allocator. 1167 /// 1168 /// The arguments are forwarded to the constructor. 1169 template <typename... Ts> SCC *createSCC(Ts &&...Args) { 1170 return new (SCCBPA.Allocate()) SCC(std::forward<Ts>(Args)...); 1171 } 1172 1173 /// Allocates a RefSCC and constructs it using the graph allocator. 1174 /// 1175 /// The arguments are forwarded to the constructor. 1176 template <typename... Ts> RefSCC *createRefSCC(Ts &&...Args) { 1177 return new (RefSCCBPA.Allocate()) RefSCC(std::forward<Ts>(Args)...); 1178 } 1179 1180 /// Common logic for building SCCs from a sequence of roots. 1181 /// 1182 /// This is a very generic implementation of the depth-first walk and SCC 1183 /// formation algorithm. It uses a generic sequence of roots and generic 1184 /// callbacks for each step. This is designed to be used to implement both 1185 /// the RefSCC formation and SCC formation with shared logic. 1186 /// 1187 /// Currently this is a relatively naive implementation of Tarjan's DFS 1188 /// algorithm to form the SCCs. 1189 /// 1190 /// FIXME: We should consider newer variants such as Nuutila. 1191 template <typename RootsT, typename GetBeginT, typename GetEndT, 1192 typename GetNodeT, typename FormSCCCallbackT> 1193 static void buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin, 1194 GetEndT &&GetEnd, GetNodeT &&GetNode, 1195 FormSCCCallbackT &&FormSCC); 1196 1197 /// Build the SCCs for a RefSCC out of a list of nodes. 1198 void buildSCCs(RefSCC &RC, node_stack_range Nodes); 1199 1200 /// Get the index of a RefSCC within the postorder traversal. 1201 /// 1202 /// Requires that this RefSCC is a valid one in the (perhaps partial) 1203 /// postorder traversed part of the graph. 1204 int getRefSCCIndex(RefSCC &RC) { 1205 auto IndexIt = RefSCCIndices.find(&RC); 1206 assert(IndexIt != RefSCCIndices.end() && "RefSCC doesn't have an index!"); 1207 assert(PostOrderRefSCCs[IndexIt->second] == &RC && 1208 "Index does not point back at RC!"); 1209 return IndexIt->second; 1210 } 1211 }; 1212 1213 inline LazyCallGraph::Edge::Edge() = default; 1214 inline LazyCallGraph::Edge::Edge(Node &N, Kind K) : Value(&N, K) {} 1215 1216 inline LazyCallGraph::Edge::operator bool() const { 1217 return Value.getPointer() && !Value.getPointer()->isDead(); 1218 } 1219 1220 inline LazyCallGraph::Edge::Kind LazyCallGraph::Edge::getKind() const { 1221 assert(*this && "Queried a null edge!"); 1222 return Value.getInt(); 1223 } 1224 1225 inline bool LazyCallGraph::Edge::isCall() const { 1226 assert(*this && "Queried a null edge!"); 1227 return getKind() == Call; 1228 } 1229 1230 inline LazyCallGraph::Node &LazyCallGraph::Edge::getNode() const { 1231 assert(*this && "Queried a null edge!"); 1232 return *Value.getPointer(); 1233 } 1234 1235 inline Function &LazyCallGraph::Edge::getFunction() const { 1236 assert(*this && "Queried a null edge!"); 1237 return getNode().getFunction(); 1238 } 1239 1240 // Provide GraphTraits specializations for call graphs. 1241 template <> struct GraphTraits<LazyCallGraph::Node *> { 1242 using NodeRef = LazyCallGraph::Node *; 1243 using ChildIteratorType = LazyCallGraph::EdgeSequence::iterator; 1244 1245 static NodeRef getEntryNode(NodeRef N) { return N; } 1246 static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); } 1247 static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); } 1248 }; 1249 template <> struct GraphTraits<LazyCallGraph *> { 1250 using NodeRef = LazyCallGraph::Node *; 1251 using ChildIteratorType = LazyCallGraph::EdgeSequence::iterator; 1252 1253 static NodeRef getEntryNode(NodeRef N) { return N; } 1254 static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); } 1255 static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); } 1256 }; 1257 1258 /// An analysis pass which computes the call graph for a module. 1259 class LazyCallGraphAnalysis : public AnalysisInfoMixin<LazyCallGraphAnalysis> { 1260 friend AnalysisInfoMixin<LazyCallGraphAnalysis>; 1261 1262 static AnalysisKey Key; 1263 1264 public: 1265 /// Inform generic clients of the result type. 1266 using Result = LazyCallGraph; 1267 1268 /// Compute the \c LazyCallGraph for the module \c M. 1269 /// 1270 /// This just builds the set of entry points to the call graph. The rest is 1271 /// built lazily as it is walked. 1272 LazyCallGraph run(Module &M, ModuleAnalysisManager &AM) { 1273 FunctionAnalysisManager &FAM = 1274 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 1275 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 1276 return FAM.getResult<TargetLibraryAnalysis>(F); 1277 }; 1278 return LazyCallGraph(M, GetTLI); 1279 } 1280 }; 1281 1282 /// A pass which prints the call graph to a \c raw_ostream. 1283 /// 1284 /// This is primarily useful for testing the analysis. 1285 class LazyCallGraphPrinterPass 1286 : public PassInfoMixin<LazyCallGraphPrinterPass> { 1287 raw_ostream &OS; 1288 1289 public: 1290 explicit LazyCallGraphPrinterPass(raw_ostream &OS); 1291 1292 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); 1293 1294 static bool isRequired() { return true; } 1295 }; 1296 1297 /// A pass which prints the call graph as a DOT file to a \c raw_ostream. 1298 /// 1299 /// This is primarily useful for visualization purposes. 1300 class LazyCallGraphDOTPrinterPass 1301 : public PassInfoMixin<LazyCallGraphDOTPrinterPass> { 1302 raw_ostream &OS; 1303 1304 public: 1305 explicit LazyCallGraphDOTPrinterPass(raw_ostream &OS); 1306 1307 PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); 1308 1309 static bool isRequired() { return true; } 1310 }; 1311 1312 extern template struct LLVM_TEMPLATE_ABI 1313 Any::TypeId<const LazyCallGraph::SCC *>; 1314 } // end namespace llvm 1315 1316 #endif // LLVM_ANALYSIS_LAZYCALLGRAPH_H
| [ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
|
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |
|