xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Analysis/LazyCallGraph.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- LazyCallGraph.h - Analysis of 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 /// Implements a lazy call graph analysis and related passes for the new pass
11 /// manager.
12 ///
13 /// NB: This is *not* a traditional call graph! It is a graph which models both
14 /// the current calls and potential calls. As a consequence there are many
15 /// edges in this call graph that do not correspond to a 'call' or 'invoke'
16 /// instruction.
17 ///
18 /// The primary use cases of this graph analysis is to facilitate iterating
19 /// across the functions of a module in ways that ensure all callees are
20 /// visited prior to a caller (given any SCC constraints), or vice versa. As
21 /// such is it particularly well suited to organizing CGSCC optimizations such
22 /// as inlining, outlining, argument promotion, etc. That is its primary use
23 /// case and motivates the design. It may not be appropriate for other
24 /// purposes. The use graph of functions or some other conservative analysis of
25 /// call instructions may be interesting for optimizations and subsequent
26 /// analyses which don't work in the context of an overly specified
27 /// potential-call-edge graph.
28 ///
29 /// To understand the specific rules and nature of this call graph analysis,
30 /// see the documentation of the \c LazyCallGraph below.
31 ///
32 //===----------------------------------------------------------------------===//
33 
34 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
35 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H
36 
37 #include "llvm/ADT/Any.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/PointerIntPair.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/ADT/iterator.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/Analysis/TargetLibraryInfo.h"
47 #include "llvm/IR/PassManager.h"
48 #include "llvm/Support/Allocator.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <cassert>
52 #include <iterator>
53 #include <optional>
54 #include <string>
55 #include <utility>
56 
57 namespace llvm {
58 
59 class Constant;
60 template <class GraphType> struct GraphTraits;
61 class Module;
62 
63 /// A lazily constructed view of the call graph of a module.
64 ///
65 /// With the edges of this graph, the motivating constraint that we are
66 /// attempting to maintain is that function-local optimization, CGSCC-local
67 /// optimizations, and optimizations transforming a pair of functions connected
68 /// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC
69 /// DAG. That is, no optimizations will delete, remove, or add an edge such
70 /// that functions already visited in a bottom-up order of the SCC DAG are no
71 /// longer valid to have visited, or such that functions not yet visited in
72 /// a bottom-up order of the SCC DAG are not required to have already been
73 /// visited.
74 ///
75 /// Within this constraint, the desire is to minimize the merge points of the
76 /// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points
77 /// in the SCC DAG, the more independence there is in optimizing within it.
78 /// There is a strong desire to enable parallelization of optimizations over
79 /// the call graph, and both limited fanout and merge points will (artificially
80 /// in some cases) limit the scaling of such an effort.
81 ///
82 /// To this end, graph represents both direct and any potential resolution to
83 /// an indirect call edge. Another way to think about it is that it represents
84 /// both the direct call edges and any direct call edges that might be formed
85 /// through static optimizations. Specifically, it considers taking the address
86 /// of a function to be an edge in the call graph because this might be
87 /// forwarded to become a direct call by some subsequent function-local
88 /// optimization. The result is that the graph closely follows the use-def
89 /// edges for functions. Walking "up" the graph can be done by looking at all
90 /// of the uses of a function.
91 ///
92 /// The roots of the call graph are the external functions and functions
93 /// escaped into global variables. Those functions can be called from outside
94 /// of the module or via unknowable means in the IR -- we may not be able to
95 /// form even a potential call edge from a function body which may dynamically
96 /// load the function and call it.
97 ///
98 /// This analysis still requires updates to remain valid after optimizations
99 /// which could potentially change the set of potential callees. The
100 /// constraints it operates under only make the traversal order remain valid.
101 ///
102 /// The entire analysis must be re-computed if full interprocedural
103 /// optimizations run at any point. For example, globalopt completely
104 /// invalidates the information in this analysis.
105 ///
106 /// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish
107 /// it from the existing CallGraph. At some point, it is expected that this
108 /// will be the only call graph and it will be renamed accordingly.
109 class LazyCallGraph {
110 public:
111   class Node;
112   class EdgeSequence;
113   class RefSCC;
114 
115   /// A class used to represent edges in the call graph.
116   ///
117   /// The lazy call graph models both *call* edges and *reference* edges. Call
118   /// edges are much what you would expect, and exist when there is a 'call' or
119   /// 'invoke' instruction of some function. Reference edges are also tracked
120   /// along side these, and exist whenever any instruction (transitively
121   /// through its operands) references a function. All call edges are
122   /// inherently reference edges, and so the reference graph forms a superset
123   /// of the formal call graph.
124   ///
125   /// All of these forms of edges are fundamentally represented as outgoing
126   /// edges. The edges are stored in the source node and point at the target
127   /// node. This allows the edge structure itself to be a very compact data
128   /// structure: essentially a tagged pointer.
129   class Edge {
130   public:
131     /// The kind of edge in the graph.
132     enum Kind : bool { Ref = false, Call = true };
133 
134     Edge();
135     explicit Edge(Node &N, Kind K);
136 
137     /// Test whether the edge is null.
138     ///
139     /// This happens when an edge has been deleted. We leave the edge objects
140     /// around but clear them.
141     explicit operator bool() const;
142 
143     /// Returns the \c Kind of the edge.
144     Kind getKind() const;
145 
146     /// Test whether the edge represents a direct call to a function.
147     ///
148     /// This requires that the edge is not null.
149     bool isCall() const;
150 
151     /// Get the call graph node referenced by this edge.
152     ///
153     /// This requires that the edge is not null.
154     Node &getNode() const;
155 
156     /// Get the function referenced by this edge.
157     ///
158     /// This requires that the edge is not null.
159     Function &getFunction() const;
160 
161   private:
162     friend class LazyCallGraph::EdgeSequence;
163     friend class LazyCallGraph::RefSCC;
164 
165     PointerIntPair<Node *, 1, Kind> Value;
166 
setKind(Kind K)167     void setKind(Kind K) { Value.setInt(K); }
168   };
169 
170   /// The edge sequence object.
171   ///
172   /// This typically exists entirely within the node but is exposed as
173   /// a separate type because a node doesn't initially have edges. An explicit
174   /// population step is required to produce this sequence at first and it is
175   /// then cached in the node. It is also used to represent edges entering the
176   /// graph from outside the module to model the graph's roots.
177   ///
178   /// The sequence itself both iterable and indexable. The indexes remain
179   /// stable even as the sequence mutates (including removal).
180   class EdgeSequence {
181     friend class LazyCallGraph;
182     friend class LazyCallGraph::Node;
183     friend class LazyCallGraph::RefSCC;
184 
185     using VectorT = SmallVector<Edge, 4>;
186     using VectorImplT = SmallVectorImpl<Edge>;
187 
188   public:
189     /// An iterator used for the edges to both entry nodes and child nodes.
190     class iterator
191         : public iterator_adaptor_base<iterator, VectorImplT::iterator,
192                                        std::forward_iterator_tag> {
193       friend class LazyCallGraph;
194       friend class LazyCallGraph::Node;
195 
196       VectorImplT::iterator E;
197 
198       // Build the iterator for a specific position in the edge list.
iterator(VectorImplT::iterator BaseI,VectorImplT::iterator E)199       iterator(VectorImplT::iterator BaseI, VectorImplT::iterator E)
200           : iterator_adaptor_base(BaseI), E(E) {
201         while (I != E && !*I)
202           ++I;
203       }
204 
205     public:
206       iterator() = default;
207 
208       using iterator_adaptor_base::operator++;
209       iterator &operator++() {
210         do {
211           ++I;
212         } while (I != E && !*I);
213         return *this;
214       }
215     };
216 
217     /// An iterator over specifically call edges.
218     ///
219     /// This has the same iteration properties as the \c iterator, but
220     /// restricts itself to edges which represent actual calls.
221     class call_iterator
222         : public iterator_adaptor_base<call_iterator, VectorImplT::iterator,
223                                        std::forward_iterator_tag> {
224       friend class LazyCallGraph;
225       friend class LazyCallGraph::Node;
226 
227       VectorImplT::iterator E;
228 
229       /// Advance the iterator to the next valid, call edge.
advanceToNextEdge()230       void advanceToNextEdge() {
231         while (I != E && (!*I || !I->isCall()))
232           ++I;
233       }
234 
235       // Build the iterator for a specific position in the edge list.
call_iterator(VectorImplT::iterator BaseI,VectorImplT::iterator E)236       call_iterator(VectorImplT::iterator BaseI, VectorImplT::iterator E)
237           : iterator_adaptor_base(BaseI), E(E) {
238         advanceToNextEdge();
239       }
240 
241     public:
242       call_iterator() = default;
243 
244       using iterator_adaptor_base::operator++;
245       call_iterator &operator++() {
246         ++I;
247         advanceToNextEdge();
248         return *this;
249       }
250     };
251 
begin()252     iterator begin() { return iterator(Edges.begin(), Edges.end()); }
end()253     iterator end() { return iterator(Edges.end(), Edges.end()); }
254 
255     Edge &operator[](Node &N) {
256       assert(EdgeIndexMap.contains(&N) && "No such edge!");
257       auto &E = Edges[EdgeIndexMap.find(&N)->second];
258       assert(E && "Dead or null edge!");
259       return E;
260     }
261 
lookup(Node & N)262     Edge *lookup(Node &N) {
263       auto EI = EdgeIndexMap.find(&N);
264       if (EI == EdgeIndexMap.end())
265         return nullptr;
266       auto &E = Edges[EI->second];
267       return E ? &E : nullptr;
268     }
269 
call_begin()270     call_iterator call_begin() {
271       return call_iterator(Edges.begin(), Edges.end());
272     }
call_end()273     call_iterator call_end() { return call_iterator(Edges.end(), Edges.end()); }
274 
calls()275     iterator_range<call_iterator> calls() {
276       return make_range(call_begin(), call_end());
277     }
278 
empty()279     bool empty() {
280       for (auto &E : Edges)
281         if (E)
282           return false;
283 
284       return true;
285     }
286 
287   private:
288     VectorT Edges;
289     DenseMap<Node *, int> EdgeIndexMap;
290 
291     EdgeSequence() = default;
292 
293     /// Internal helper to insert an edge to a node.
294     void insertEdgeInternal(Node &ChildN, Edge::Kind EK);
295 
296     /// Internal helper to change an edge kind.
297     void setEdgeKind(Node &ChildN, Edge::Kind EK);
298 
299     /// Internal helper to remove the edge to the given function.
300     bool removeEdgeInternal(Node &ChildN);
301   };
302 
303   /// A node in the call graph.
304   ///
305   /// This represents a single node. Its primary roles are to cache the list of
306   /// callees, de-duplicate and provide fast testing of whether a function is a
307   /// callee, and facilitate iteration of child nodes in the graph.
308   ///
309   /// The node works much like an optional in order to lazily populate the
310   /// edges of each node. Until populated, there are no edges. Once populated,
311   /// you can access the edges by dereferencing the node or using the `->`
312   /// operator as if the node was an `std::optional<EdgeSequence>`.
313   class Node {
314     friend class LazyCallGraph;
315     friend class LazyCallGraph::RefSCC;
316 
317   public:
getGraph()318     LazyCallGraph &getGraph() const { return *G; }
319 
getFunction()320     Function &getFunction() const { return *F; }
321 
getName()322     StringRef getName() const { return F->getName(); }
323 
324     /// Equality is defined as address equality.
325     bool operator==(const Node &N) const { return this == &N; }
326     bool operator!=(const Node &N) const { return !operator==(N); }
327 
328     /// Tests whether the node has been populated with edges.
isPopulated()329     bool isPopulated() const { return Edges.has_value(); }
330 
331     /// Tests whether this is actually a dead node and no longer valid.
332     ///
333     /// Users rarely interact with nodes in this state and other methods are
334     /// invalid. This is used to model a node in an edge list where the
335     /// function has been completely removed.
isDead()336     bool isDead() const {
337       assert(!G == !F &&
338              "Both graph and function pointers should be null or non-null.");
339       return !G;
340     }
341 
342     // We allow accessing the edges by dereferencing or using the arrow
343     // operator, essentially wrapping the internal optional.
344     EdgeSequence &operator*() const {
345       // Rip const off because the node itself isn't changing here.
346       return const_cast<EdgeSequence &>(*Edges);
347     }
348     EdgeSequence *operator->() const { return &**this; }
349 
350     /// Populate the edges of this node if necessary.
351     ///
352     /// The first time this is called it will populate the edges for this node
353     /// in the graph. It does this by scanning the underlying function, so once
354     /// this is done, any changes to that function must be explicitly reflected
355     /// in updates to the graph.
356     ///
357     /// \returns the populated \c EdgeSequence to simplify walking it.
358     ///
359     /// This will not update or re-scan anything if called repeatedly. Instead,
360     /// the edge sequence is cached and returned immediately on subsequent
361     /// calls.
populate()362     EdgeSequence &populate() {
363       if (Edges)
364         return *Edges;
365 
366       return populateSlow();
367     }
368 
369   private:
370     LazyCallGraph *G;
371     Function *F;
372 
373     // We provide for the DFS numbering and Tarjan walk lowlink numbers to be
374     // stored directly within the node. These are both '-1' when nodes are part
375     // of an SCC (or RefSCC), or '0' when not yet reached in a DFS walk.
376     int DFSNumber = 0;
377     int LowLink = 0;
378 
379     std::optional<EdgeSequence> Edges;
380 
381     /// Basic constructor implements the scanning of F into Edges and
382     /// EdgeIndexMap.
Node(LazyCallGraph & G,Function & F)383     Node(LazyCallGraph &G, Function &F) : G(&G), F(&F) {}
384 
385     /// Implementation of the scan when populating.
386     LLVM_ABI EdgeSequence &populateSlow();
387 
388     /// Internal helper to directly replace the function with a new one.
389     ///
390     /// This is used to facilitate transformations which need to replace the
391     /// formal Function object but directly move the body and users from one to
392     /// the other.
393     void replaceFunction(Function &NewF);
394 
clear()395     void clear() { Edges.reset(); }
396 
397     /// Print the name of this node's function.
398     friend raw_ostream &operator<<(raw_ostream &OS, const Node &N) {
399       return OS << N.F->getName();
400     }
401 
402     /// Dump the name of this node's function to stderr.
403     void dump() const;
404   };
405 
406   /// An SCC of the call graph.
407   ///
408   /// This represents a Strongly Connected Component of the direct call graph
409   /// -- ignoring indirect calls and function references. It stores this as
410   /// a collection of call graph nodes. While the order of nodes in the SCC is
411   /// stable, it is not any particular order.
412   ///
413   /// The SCCs are nested within a \c RefSCC, see below for details about that
414   /// outer structure. SCCs do not support mutation of the call graph, that
415   /// must be done through the containing \c RefSCC in order to fully reason
416   /// about the ordering and connections of the graph.
417   class LLVM_ABI SCC {
418     friend class LazyCallGraph;
419     friend class LazyCallGraph::Node;
420 
421     RefSCC *OuterRefSCC;
422     SmallVector<Node *, 1> Nodes;
423 
424     template <typename NodeRangeT>
SCC(RefSCC & OuterRefSCC,NodeRangeT && Nodes)425     SCC(RefSCC &OuterRefSCC, NodeRangeT &&Nodes)
426         : OuterRefSCC(&OuterRefSCC), Nodes(std::forward<NodeRangeT>(Nodes)) {}
427 
clear()428     void clear() {
429       OuterRefSCC = nullptr;
430       Nodes.clear();
431     }
432 
433     /// Print a short description useful for debugging or logging.
434     ///
435     /// We print the function names in the SCC wrapped in '()'s and skipping
436     /// the middle functions if there are a large number.
437     //
438     // Note: this is defined inline to dodge issues with GCC's interpretation
439     // of enclosing namespaces for friend function declarations.
440     friend raw_ostream &operator<<(raw_ostream &OS, const SCC &C) {
441       OS << '(';
442       int I = 0;
443       for (LazyCallGraph::Node &N : C) {
444         if (I > 0)
445           OS << ", ";
446         // Elide the inner elements if there are too many.
447         if (I > 8) {
448           OS << "..., " << *C.Nodes.back();
449           break;
450         }
451         OS << N;
452         ++I;
453       }
454       OS << ')';
455       return OS;
456     }
457 
458     /// Dump a short description of this SCC to stderr.
459     void dump() const;
460 
461 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
462     /// Verify invariants about the SCC.
463     ///
464     /// This will attempt to validate all of the basic invariants within an
465     /// SCC, but not that it is a strongly connected component per se.
466     /// Primarily useful while building and updating the graph to check that
467     /// basic properties are in place rather than having inexplicable crashes
468     /// later.
469     void verify();
470 #endif
471 
472   public:
473     using iterator = pointee_iterator<SmallVectorImpl<Node *>::const_iterator>;
474 
begin()475     iterator begin() const { return Nodes.begin(); }
end()476     iterator end() const { return Nodes.end(); }
477 
size()478     int size() const { return Nodes.size(); }
479 
getOuterRefSCC()480     RefSCC &getOuterRefSCC() const { return *OuterRefSCC; }
481 
482     /// Test if this SCC is a parent of \a C.
483     ///
484     /// Note that this is linear in the number of edges departing the current
485     /// SCC.
486     bool isParentOf(const SCC &C) const;
487 
488     /// Test if this SCC is an ancestor of \a C.
489     ///
490     /// Note that in the worst case this is linear in the number of edges
491     /// departing the current SCC and every SCC in the entire graph reachable
492     /// from this SCC. Thus this very well may walk every edge in the entire
493     /// call graph! Do not call this in a tight loop!
494     bool isAncestorOf(const SCC &C) const;
495 
496     /// Test if this SCC is a child of \a C.
497     ///
498     /// See the comments for \c isParentOf for detailed notes about the
499     /// complexity of this routine.
isChildOf(const SCC & C)500     bool isChildOf(const SCC &C) const { return C.isParentOf(*this); }
501 
502     /// Test if this SCC is a descendant of \a C.
503     ///
504     /// See the comments for \c isParentOf for detailed notes about the
505     /// complexity of this routine.
isDescendantOf(const SCC & C)506     bool isDescendantOf(const SCC &C) const { return C.isAncestorOf(*this); }
507 
508     /// Provide a short name by printing this SCC to a std::string.
509     ///
510     /// This copes with the fact that we don't have a name per se for an SCC
511     /// while still making the use of this in debugging and logging useful.
getName()512     std::string getName() const {
513       std::string Name;
514       raw_string_ostream OS(Name);
515       OS << *this;
516       OS.flush();
517       return Name;
518     }
519   };
520 
521   /// A RefSCC of the call graph.
522   ///
523   /// This models a Strongly Connected Component of function reference edges in
524   /// the call graph. As opposed to actual SCCs, these can be used to scope
525   /// subgraphs of the module which are independent from other subgraphs of the
526   /// module because they do not reference it in any way. This is also the unit
527   /// where we do mutation of the graph in order to restrict mutations to those
528   /// which don't violate this independence.
529   ///
530   /// A RefSCC contains a DAG of actual SCCs. All the nodes within the RefSCC
531   /// are necessarily within some actual SCC that nests within it. Since
532   /// a direct call *is* a reference, there will always be at least one RefSCC
533   /// around any SCC.
534   ///
535   /// Spurious ref edges, meaning ref edges that still exist in the call graph
536   /// even though the corresponding IR reference no longer exists, are allowed.
537   /// This is mostly to support argument promotion, which can modify a caller to
538   /// no longer pass a function. The only place that needs to specially handle
539   /// this is deleting a dead function/node, otherwise the dead ref edges are
540   /// automatically removed when visiting the function/node no longer containing
541   /// the ref edge.
542   class RefSCC {
543     friend class LazyCallGraph;
544     friend class LazyCallGraph::Node;
545 
546     LazyCallGraph *G;
547 
548     /// A postorder list of the inner SCCs.
549     SmallVector<SCC *, 4> SCCs;
550 
551     /// A map from SCC to index in the postorder list.
552     SmallDenseMap<SCC *, int, 4> SCCIndices;
553 
554     /// Fast-path constructor. RefSCCs should instead be constructed by calling
555     /// formRefSCCFast on the graph itself.
556     RefSCC(LazyCallGraph &G);
557 
clear()558     void clear() {
559       SCCs.clear();
560       SCCIndices.clear();
561     }
562 
563     /// Print a short description useful for debugging or logging.
564     ///
565     /// We print the SCCs wrapped in '[]'s and skipping the middle SCCs if
566     /// there are a large number.
567     //
568     // Note: this is defined inline to dodge issues with GCC's interpretation
569     // of enclosing namespaces for friend function declarations.
570     friend raw_ostream &operator<<(raw_ostream &OS, const RefSCC &RC) {
571       OS << '[';
572       int I = 0;
573       for (LazyCallGraph::SCC &C : RC) {
574         if (I > 0)
575           OS << ", ";
576         // Elide the inner elements if there are too many.
577         if (I > 4) {
578           OS << "..., " << *RC.SCCs.back();
579           break;
580         }
581         OS << C;
582         ++I;
583       }
584       OS << ']';
585       return OS;
586     }
587 
588     /// Dump a short description of this RefSCC to stderr.
589     void dump() const;
590 
591 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
592     /// Verify invariants about the RefSCC and all its SCCs.
593     ///
594     /// This will attempt to validate all of the invariants *within* the
595     /// RefSCC, but not that it is a strongly connected component of the larger
596     /// graph. This makes it useful even when partially through an update.
597     ///
598     /// Invariants checked:
599     /// - SCCs and their indices match.
600     /// - The SCCs list is in fact in post-order.
601     void verify();
602 #endif
603 
604   public:
605     using iterator = pointee_iterator<SmallVectorImpl<SCC *>::const_iterator>;
606     using range = iterator_range<iterator>;
607     using parent_iterator =
608         pointee_iterator<SmallPtrSetImpl<RefSCC *>::const_iterator>;
609 
begin()610     iterator begin() const { return SCCs.begin(); }
end()611     iterator end() const { return SCCs.end(); }
612 
size()613     ssize_t size() const { return SCCs.size(); }
614 
615     SCC &operator[](int Idx) { return *SCCs[Idx]; }
616 
find(SCC & C)617     iterator find(SCC &C) const {
618       return SCCs.begin() + SCCIndices.find(&C)->second;
619     }
620 
621     /// Test if this RefSCC is a parent of \a RC.
622     ///
623     /// CAUTION: This method walks every edge in the \c RefSCC, it can be very
624     /// expensive.
625     LLVM_ABI bool isParentOf(const RefSCC &RC) const;
626 
627     /// Test if this RefSCC is an ancestor of \a RC.
628     ///
629     /// CAUTION: This method walks the directed graph of edges as far as
630     /// necessary to find a possible path to the argument. In the worst case
631     /// this may walk the entire graph and can be extremely expensive.
632     LLVM_ABI bool isAncestorOf(const RefSCC &RC) const;
633 
634     /// Test if this RefSCC is a child of \a RC.
635     ///
636     /// CAUTION: This method walks every edge in the argument \c RefSCC, it can
637     /// be very expensive.
isChildOf(const RefSCC & RC)638     bool isChildOf(const RefSCC &RC) const { return RC.isParentOf(*this); }
639 
640     /// Test if this RefSCC is a descendant of \a RC.
641     ///
642     /// CAUTION: This method walks the directed graph of edges as far as
643     /// necessary to find a possible path from the argument. In the worst case
644     /// this may walk the entire graph and can be extremely expensive.
isDescendantOf(const RefSCC & RC)645     bool isDescendantOf(const RefSCC &RC) const {
646       return RC.isAncestorOf(*this);
647     }
648 
649     /// Provide a short name by printing this RefSCC to a std::string.
650     ///
651     /// This copes with the fact that we don't have a name per se for an RefSCC
652     /// while still making the use of this in debugging and logging useful.
getName()653     std::string getName() const {
654       std::string Name;
655       raw_string_ostream OS(Name);
656       OS << *this;
657       OS.flush();
658       return Name;
659     }
660 
661     ///@{
662     /// \name Mutation API
663     ///
664     /// These methods provide the core API for updating the call graph in the
665     /// presence of (potentially still in-flight) DFS-found RefSCCs and SCCs.
666     ///
667     /// Note that these methods sometimes have complex runtimes, so be careful
668     /// how you call them.
669 
670     /// Make an existing internal ref edge into a call edge.
671     ///
672     /// This may form a larger cycle and thus collapse SCCs into TargetN's SCC.
673     /// If that happens, the optional callback \p MergedCB will be invoked (if
674     /// provided) on the SCCs being merged away prior to actually performing
675     /// the merge. Note that this will never include the target SCC as that
676     /// will be the SCC functions are merged into to resolve the cycle. Once
677     /// this function returns, these merged SCCs are not in a valid state but
678     /// the pointers will remain valid until destruction of the parent graph
679     /// instance for the purpose of clearing cached information. This function
680     /// also returns 'true' if a cycle was formed and some SCCs merged away as
681     /// a convenience.
682     ///
683     /// After this operation, both SourceN's SCC and TargetN's SCC may move
684     /// position within this RefSCC's postorder list. Any SCCs merged are
685     /// merged into the TargetN's SCC in order to preserve reachability analyses
686     /// which took place on that SCC.
687     LLVM_ABI bool switchInternalEdgeToCall(
688         Node &SourceN, Node &TargetN,
689         function_ref<void(ArrayRef<SCC *> MergedSCCs)> MergeCB = {});
690 
691     /// Make an existing internal call edge between separate SCCs into a ref
692     /// edge.
693     ///
694     /// If SourceN and TargetN in separate SCCs within this RefSCC, changing
695     /// the call edge between them to a ref edge is a trivial operation that
696     /// does not require any structural changes to the call graph.
697     LLVM_ABI void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN);
698 
699     /// Make an existing internal call edge within a single SCC into a ref
700     /// edge.
701     ///
702     /// Since SourceN and TargetN are part of a single SCC, this SCC may be
703     /// split up due to breaking a cycle in the call edges that formed it. If
704     /// that happens, then this routine will insert new SCCs into the postorder
705     /// list *before* the SCC of TargetN (previously the SCC of both). This
706     /// preserves postorder as the TargetN can reach all of the other nodes by
707     /// definition of previously being in a single SCC formed by the cycle from
708     /// SourceN to TargetN.
709     ///
710     /// The newly added SCCs are added *immediately* and contiguously
711     /// prior to the TargetN SCC and return the range covering the new SCCs in
712     /// the RefSCC's postorder sequence. You can directly iterate the returned
713     /// range to observe all of the new SCCs in postorder.
714     ///
715     /// Note that if SourceN and TargetN are in separate SCCs, the simpler
716     /// routine `switchTrivialInternalEdgeToRef` should be used instead.
717     LLVM_ABI iterator_range<iterator> switchInternalEdgeToRef(Node &SourceN,
718                                                               Node &TargetN);
719 
720     /// Make an existing outgoing ref edge into a call edge.
721     ///
722     /// Note that this is trivial as there are no cyclic impacts and there
723     /// remains a reference edge.
724     LLVM_ABI void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN);
725 
726     /// Make an existing outgoing call edge into a ref edge.
727     ///
728     /// This is trivial as there are no cyclic impacts and there remains
729     /// a reference edge.
730     LLVM_ABI void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN);
731 
732     /// Insert a ref edge from one node in this RefSCC to another in this
733     /// RefSCC.
734     ///
735     /// This is always a trivial operation as it doesn't change any part of the
736     /// graph structure besides connecting the two nodes.
737     ///
738     /// Note that we don't support directly inserting internal *call* edges
739     /// because that could change the graph structure and requires returning
740     /// information about what became invalid. As a consequence, the pattern
741     /// should be to first insert the necessary ref edge, and then to switch it
742     /// to a call edge if needed and handle any invalidation that results. See
743     /// the \c switchInternalEdgeToCall routine for details.
744     LLVM_ABI void insertInternalRefEdge(Node &SourceN, Node &TargetN);
745 
746     /// Insert an edge whose parent is in this RefSCC and child is in some
747     /// child RefSCC.
748     ///
749     /// There must be an existing path from the \p SourceN to the \p TargetN.
750     /// This operation is inexpensive and does not change the set of SCCs and
751     /// RefSCCs in the graph.
752     LLVM_ABI void insertOutgoingEdge(Node &SourceN, Node &TargetN,
753                                      Edge::Kind EK);
754 
755     /// Insert an edge whose source is in a descendant RefSCC and target is in
756     /// this RefSCC.
757     ///
758     /// There must be an existing path from the target to the source in this
759     /// case.
760     ///
761     /// NB! This is has the potential to be a very expensive function. It
762     /// inherently forms a cycle in the prior RefSCC DAG and we have to merge
763     /// RefSCCs to resolve that cycle. But finding all of the RefSCCs which
764     /// participate in the cycle can in the worst case require traversing every
765     /// RefSCC in the graph. Every attempt is made to avoid that, but passes
766     /// must still exercise caution calling this routine repeatedly.
767     ///
768     /// Also note that this can only insert ref edges. In order to insert
769     /// a call edge, first insert a ref edge and then switch it to a call edge.
770     /// These are intentionally kept as separate interfaces because each step
771     /// of the operation invalidates a different set of data structures.
772     ///
773     /// This returns all the RefSCCs which were merged into the this RefSCC
774     /// (the target's). This allows callers to invalidate any cached
775     /// information.
776     ///
777     /// FIXME: We could possibly optimize this quite a bit for cases where the
778     /// caller and callee are very nearby in the graph. See comments in the
779     /// implementation for details, but that use case might impact users.
780     LLVM_ABI SmallVector<RefSCC *, 1> insertIncomingRefEdge(Node &SourceN,
781                                                             Node &TargetN);
782 
783     /// Remove an edge whose source is in this RefSCC and target is *not*.
784     ///
785     /// This removes an inter-RefSCC edge. All inter-RefSCC edges originating
786     /// from this SCC have been fully explored by any in-flight DFS graph
787     /// formation, so this is always safe to call once you have the source
788     /// RefSCC.
789     ///
790     /// This operation does not change the cyclic structure of the graph and so
791     /// is very inexpensive. It may change the connectivity graph of the SCCs
792     /// though, so be careful calling this while iterating over them.
793     LLVM_ABI void removeOutgoingEdge(Node &SourceN, Node &TargetN);
794 
795     /// Remove a list of ref edges which are entirely within this RefSCC.
796     ///
797     /// Both the \a SourceN and all of the \a TargetNs must be within this
798     /// RefSCC. Removing these edges may break cycles that form this RefSCC and
799     /// thus this operation may change the RefSCC graph significantly. In
800     /// particular, this operation will re-form new RefSCCs based on the
801     /// remaining connectivity of the graph. The following invariants are
802     /// guaranteed to hold after calling this method:
803     ///
804     /// 1) If a ref-cycle remains after removal, it leaves this RefSCC intact
805     ///    and in the graph. No new RefSCCs are built.
806     /// 2) Otherwise, this RefSCC will be dead after this call and no longer in
807     ///    the graph or the postorder traversal of the call graph. Any iterator
808     ///    pointing at this RefSCC will become invalid.
809     /// 3) All newly formed RefSCCs will be returned and the order of the
810     ///    RefSCCs returned will be a valid postorder traversal of the new
811     ///    RefSCCs.
812     /// 4) No RefSCC other than this RefSCC has its member set changed (this is
813     ///    inherent in the definition of removing such an edge).
814     ///
815     /// These invariants are very important to ensure that we can build
816     /// optimization pipelines on top of the CGSCC pass manager which
817     /// intelligently update the RefSCC graph without invalidating other parts
818     /// of the RefSCC graph.
819     ///
820     /// Note that we provide no routine to remove a *call* edge. Instead, you
821     /// must first switch it to a ref edge using \c switchInternalEdgeToRef.
822     /// This split API is intentional as each of these two steps can invalidate
823     /// a different aspect of the graph structure and needs to have the
824     /// invalidation handled independently.
825     ///
826     /// The runtime complexity of this method is, in the worst case, O(V+E)
827     /// where V is the number of nodes in this RefSCC and E is the number of
828     /// edges leaving the nodes in this RefSCC. Note that E includes both edges
829     /// within this RefSCC and edges from this RefSCC to child RefSCCs. Some
830     /// effort has been made to minimize the overhead of common cases such as
831     /// self-edges and edge removals which result in a spanning tree with no
832     /// more cycles.
833     [[nodiscard]] LLVM_ABI SmallVector<RefSCC *, 1>
834     removeInternalRefEdges(ArrayRef<std::pair<Node *, Node *>> Edges);
835 
836     /// A convenience wrapper around the above to handle trivial cases of
837     /// inserting a new call edge.
838     ///
839     /// This is trivial whenever the target is in the same SCC as the source or
840     /// the edge is an outgoing edge to some descendant SCC. In these cases
841     /// there is no change to the cyclic structure of SCCs or RefSCCs.
842     ///
843     /// To further make calling this convenient, it also handles inserting
844     /// already existing edges.
845     LLVM_ABI void insertTrivialCallEdge(Node &SourceN, Node &TargetN);
846 
847     /// A convenience wrapper around the above to handle trivial cases of
848     /// inserting a new ref edge.
849     ///
850     /// This is trivial whenever the target is in the same RefSCC as the source
851     /// or the edge is an outgoing edge to some descendant RefSCC. In these
852     /// cases there is no change to the cyclic structure of the RefSCCs.
853     ///
854     /// To further make calling this convenient, it also handles inserting
855     /// already existing edges.
856     LLVM_ABI void insertTrivialRefEdge(Node &SourceN, Node &TargetN);
857 
858     /// Directly replace a node's function with a new function.
859     ///
860     /// This should be used when moving the body and users of a function to
861     /// a new formal function object but not otherwise changing the call graph
862     /// structure in any way.
863     ///
864     /// It requires that the old function in the provided node have zero uses
865     /// and the new function must have calls and references to it establishing
866     /// an equivalent graph.
867     LLVM_ABI void replaceNodeFunction(Node &N, Function &NewF);
868 
869     ///@}
870   };
871 
872   /// A post-order depth-first RefSCC iterator over the call graph.
873   ///
874   /// This iterator walks the cached post-order sequence of RefSCCs. However,
875   /// it trades stability for flexibility. It is restricted to a forward
876   /// iterator but will survive mutations which insert new RefSCCs and continue
877   /// to point to the same RefSCC even if it moves in the post-order sequence.
878   class postorder_ref_scc_iterator
879       : public iterator_facade_base<postorder_ref_scc_iterator,
880                                     std::forward_iterator_tag, RefSCC> {
881     friend class LazyCallGraph;
882     friend class LazyCallGraph::Node;
883 
884     /// Nonce type to select the constructor for the end iterator.
885     struct IsAtEndT {};
886 
887     LazyCallGraph *G;
888     RefSCC *RC = nullptr;
889 
890     /// Build the begin iterator for a node.
postorder_ref_scc_iterator(LazyCallGraph & G)891     postorder_ref_scc_iterator(LazyCallGraph &G) : G(&G), RC(getRC(G, 0)) {
892       incrementUntilNonEmptyRefSCC();
893     }
894 
895     /// Build the end iterator for a node. This is selected purely by overload.
postorder_ref_scc_iterator(LazyCallGraph & G,IsAtEndT)896     postorder_ref_scc_iterator(LazyCallGraph &G, IsAtEndT /*Nonce*/) : G(&G) {}
897 
898     /// Get the post-order RefSCC at the given index of the postorder walk,
899     /// populating it if necessary.
getRC(LazyCallGraph & G,int Index)900     static RefSCC *getRC(LazyCallGraph &G, int Index) {
901       if (Index == (int)G.PostOrderRefSCCs.size())
902         // We're at the end.
903         return nullptr;
904 
905       return G.PostOrderRefSCCs[Index];
906     }
907 
908     // Keep incrementing until RC is non-empty (or null).
incrementUntilNonEmptyRefSCC()909     void incrementUntilNonEmptyRefSCC() {
910       while (RC && RC->size() == 0)
911         increment();
912     }
913 
increment()914     void increment() {
915       assert(RC && "Cannot increment the end iterator!");
916       RC = getRC(*G, G->RefSCCIndices.find(RC)->second + 1);
917     }
918 
919   public:
920     bool operator==(const postorder_ref_scc_iterator &Arg) const {
921       return G == Arg.G && RC == Arg.RC;
922     }
923 
924     reference operator*() const { return *RC; }
925 
926     using iterator_facade_base::operator++;
927     postorder_ref_scc_iterator &operator++() {
928       increment();
929       incrementUntilNonEmptyRefSCC();
930       return *this;
931     }
932   };
933 
934   /// Construct a graph for the given module.
935   ///
936   /// This sets up the graph and computes all of the entry points of the graph.
937   /// No function definitions are scanned until their nodes in the graph are
938   /// requested during traversal.
939   LLVM_ABI LazyCallGraph(Module &M,
940                          function_ref<TargetLibraryInfo &(Function &)> GetTLI);
941 
942   LLVM_ABI LazyCallGraph(LazyCallGraph &&G);
943   LLVM_ABI LazyCallGraph &operator=(LazyCallGraph &&RHS);
944 
945 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
946   /// Verify that every RefSCC is valid.
947   void verify();
948 #endif
949 
950   LLVM_ABI bool invalidate(Module &, const PreservedAnalyses &PA,
951                            ModuleAnalysisManager::Invalidator &);
952 
begin()953   EdgeSequence::iterator begin() { return EntryEdges.begin(); }
end()954   EdgeSequence::iterator end() { return EntryEdges.end(); }
955 
956   LLVM_ABI void buildRefSCCs();
957 
postorder_ref_scc_begin()958   postorder_ref_scc_iterator postorder_ref_scc_begin() {
959     if (!EntryEdges.empty())
960       assert(!PostOrderRefSCCs.empty() &&
961              "Must form RefSCCs before iterating them!");
962     return postorder_ref_scc_iterator(*this);
963   }
postorder_ref_scc_end()964   postorder_ref_scc_iterator postorder_ref_scc_end() {
965     if (!EntryEdges.empty())
966       assert(!PostOrderRefSCCs.empty() &&
967              "Must form RefSCCs before iterating them!");
968     return postorder_ref_scc_iterator(*this,
969                                       postorder_ref_scc_iterator::IsAtEndT());
970   }
971 
postorder_ref_sccs()972   iterator_range<postorder_ref_scc_iterator> postorder_ref_sccs() {
973     return make_range(postorder_ref_scc_begin(), postorder_ref_scc_end());
974   }
975 
976   /// Lookup a function in the graph which has already been scanned and added.
lookup(const Function & F)977   Node *lookup(const Function &F) const { return NodeMap.lookup(&F); }
978 
979   /// Lookup a function's SCC in the graph.
980   ///
981   /// \returns null if the function hasn't been assigned an SCC via the RefSCC
982   /// iterator walk.
lookupSCC(Node & N)983   SCC *lookupSCC(Node &N) const { return SCCMap.lookup(&N); }
984 
985   /// Lookup a function's RefSCC in the graph.
986   ///
987   /// \returns null if the function hasn't been assigned a RefSCC via the
988   /// RefSCC iterator walk.
lookupRefSCC(Node & N)989   RefSCC *lookupRefSCC(Node &N) const {
990     if (SCC *C = lookupSCC(N))
991       return &C->getOuterRefSCC();
992 
993     return nullptr;
994   }
995 
996   /// Get a graph node for a given function, scanning it to populate the graph
997   /// data as necessary.
get(Function & F)998   Node &get(Function &F) {
999     Node *&N = NodeMap[&F];
1000     if (N)
1001       return *N;
1002 
1003     return insertInto(F, N);
1004   }
1005 
1006   /// Get the sequence of known and defined library functions.
1007   ///
1008   /// These functions, because they are known to LLVM, can have calls
1009   /// introduced out of thin air from arbitrary IR.
getLibFunctions()1010   ArrayRef<Function *> getLibFunctions() const {
1011     return LibFunctions.getArrayRef();
1012   }
1013 
1014   /// Test whether a function is a known and defined library function tracked by
1015   /// the call graph.
1016   ///
1017   /// Because these functions are known to LLVM they are specially modeled in
1018   /// the call graph and even when all IR-level references have been removed
1019   /// remain active and reachable.
isLibFunction(Function & F)1020   bool isLibFunction(Function &F) const { return LibFunctions.count(&F); }
1021 
1022   ///@{
1023   /// \name Pre-SCC Mutation API
1024   ///
1025   /// These methods are only valid to call prior to forming any SCCs for this
1026   /// call graph. They can be used to update the core node-graph during
1027   /// a node-based inorder traversal that precedes any SCC-based traversal.
1028   ///
1029   /// Once you begin manipulating a call graph's SCCs, most mutation of the
1030   /// graph must be performed via a RefSCC method. There are some exceptions
1031   /// below.
1032 
1033   /// Update the call graph after inserting a new edge.
1034   LLVM_ABI void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK);
1035 
1036   /// Update the call graph after inserting a new edge.
insertEdge(Function & Source,Function & Target,Edge::Kind EK)1037   void insertEdge(Function &Source, Function &Target, Edge::Kind EK) {
1038     return insertEdge(get(Source), get(Target), EK);
1039   }
1040 
1041   /// Update the call graph after deleting an edge.
1042   LLVM_ABI void removeEdge(Node &SourceN, Node &TargetN);
1043 
1044   /// Update the call graph after deleting an edge.
removeEdge(Function & Source,Function & Target)1045   void removeEdge(Function &Source, Function &Target) {
1046     return removeEdge(get(Source), get(Target));
1047   }
1048 
1049   ///@}
1050 
1051   ///@{
1052   /// \name General Mutation API
1053   ///
1054   /// There are a very limited set of mutations allowed on the graph as a whole
1055   /// once SCCs have started to be formed. These routines have strict contracts
1056   /// but may be called at any point.
1057 
1058   /// Remove dead functions from the call graph.
1059   ///
1060   /// These functions should have already been passed to markDeadFunction().
1061   /// This is done as a batch to prevent compile time blowup as a result of
1062   /// handling a single function at a time.
1063   LLVM_ABI void removeDeadFunctions(ArrayRef<Function *> DeadFs);
1064 
1065   /// Mark a function as dead to be removed later by removeDeadFunctions().
1066   ///
1067   /// The function body should have no incoming or outgoing call or ref edges.
1068   /// For example, a function with a single "unreachable" instruction.
1069   LLVM_ABI void markDeadFunction(Function &F);
1070 
1071   /// Add a new function split/outlined from an existing function.
1072   ///
1073   /// The new function may only reference other functions that the original
1074   /// function did.
1075   ///
1076   /// The original function must reference (either directly or indirectly) the
1077   /// new function.
1078   ///
1079   /// The new function may also reference the original function.
1080   /// It may end up in a parent SCC in the case that the original function's
1081   /// edge to the new function is a ref edge, and the edge back is a call edge.
1082   LLVM_ABI void addSplitFunction(Function &OriginalFunction,
1083                                  Function &NewFunction);
1084 
1085   /// Add new ref-recursive functions split/outlined from an existing function.
1086   ///
1087   /// The new functions may only reference other functions that the original
1088   /// function did. The new functions may reference (not call) the original
1089   /// function.
1090   ///
1091   /// The original function must reference (not call) all new functions.
1092   /// All new functions must reference (not call) each other.
1093   LLVM_ABI void
1094   addSplitRefRecursiveFunctions(Function &OriginalFunction,
1095                                 ArrayRef<Function *> NewFunctions);
1096 
1097   ///@}
1098 
1099   ///@{
1100   /// \name Static helpers for code doing updates to the call graph.
1101   ///
1102   /// These helpers are used to implement parts of the call graph but are also
1103   /// useful to code doing updates or otherwise wanting to walk the IR in the
1104   /// same patterns as when we build the call graph.
1105 
1106   /// Recursively visits the defined functions whose address is reachable from
1107   /// every constant in the \p Worklist.
1108   ///
1109   /// Doesn't recurse through any constants already in the \p Visited set, and
1110   /// updates that set with every constant visited.
1111   ///
1112   /// For each defined function, calls \p Callback with that function.
1113   LLVM_ABI static void visitReferences(SmallVectorImpl<Constant *> &Worklist,
1114                                        SmallPtrSetImpl<Constant *> &Visited,
1115                                        function_ref<void(Function &)> Callback);
1116 
1117   ///@}
1118 
1119 private:
1120   using node_stack_iterator = SmallVectorImpl<Node *>::reverse_iterator;
1121   using node_stack_range = iterator_range<node_stack_iterator>;
1122 
1123   /// Allocator that holds all the call graph nodes.
1124   SpecificBumpPtrAllocator<Node> BPA;
1125 
1126   /// Maps function->node for fast lookup.
1127   DenseMap<const Function *, Node *> NodeMap;
1128 
1129   /// The entry edges into the graph.
1130   ///
1131   /// These edges are from "external" sources. Put another way, they
1132   /// escape at the module scope.
1133   EdgeSequence EntryEdges;
1134 
1135   /// Allocator that holds all the call graph SCCs.
1136   SpecificBumpPtrAllocator<SCC> SCCBPA;
1137 
1138   /// Maps Function -> SCC for fast lookup.
1139   DenseMap<Node *, SCC *> SCCMap;
1140 
1141   /// Allocator that holds all the call graph RefSCCs.
1142   SpecificBumpPtrAllocator<RefSCC> RefSCCBPA;
1143 
1144   /// The post-order sequence of RefSCCs.
1145   ///
1146   /// This list is lazily formed the first time we walk the graph.
1147   SmallVector<RefSCC *, 16> PostOrderRefSCCs;
1148 
1149   /// A map from RefSCC to the index for it in the postorder sequence of
1150   /// RefSCCs.
1151   DenseMap<RefSCC *, int> RefSCCIndices;
1152 
1153   /// Defined functions that are also known library functions which the
1154   /// optimizer can reason about and therefore might introduce calls to out of
1155   /// thin air.
1156   SmallSetVector<Function *, 4> LibFunctions;
1157 
1158   /// Helper to insert a new function, with an already looked-up entry in
1159   /// the NodeMap.
1160   LLVM_ABI Node &insertInto(Function &F, Node *&MappedN);
1161 
1162   /// Helper to initialize a new node created outside of creating SCCs and add
1163   /// it to the NodeMap if necessary. For example, useful when a function is
1164   /// split.
1165   Node &initNode(Function &F);
1166 
1167   /// Helper to update pointers back to the graph object during moves.
1168   void updateGraphPtrs();
1169 
1170   /// Allocates an SCC and constructs it using the graph allocator.
1171   ///
1172   /// The arguments are forwarded to the constructor.
createSCC(Ts &&...Args)1173   template <typename... Ts> SCC *createSCC(Ts &&...Args) {
1174     return new (SCCBPA.Allocate()) SCC(std::forward<Ts>(Args)...);
1175   }
1176 
1177   /// Allocates a RefSCC and constructs it using the graph allocator.
1178   ///
1179   /// The arguments are forwarded to the constructor.
createRefSCC(Ts &&...Args)1180   template <typename... Ts> RefSCC *createRefSCC(Ts &&...Args) {
1181     return new (RefSCCBPA.Allocate()) RefSCC(std::forward<Ts>(Args)...);
1182   }
1183 
1184   /// Common logic for building SCCs from a sequence of roots.
1185   ///
1186   /// This is a very generic implementation of the depth-first walk and SCC
1187   /// formation algorithm. It uses a generic sequence of roots and generic
1188   /// callbacks for each step. This is designed to be used to implement both
1189   /// the RefSCC formation and SCC formation with shared logic.
1190   ///
1191   /// Currently this is a relatively naive implementation of Tarjan's DFS
1192   /// algorithm to form the SCCs.
1193   ///
1194   /// FIXME: We should consider newer variants such as Nuutila.
1195   template <typename RootsT, typename GetBeginT, typename GetEndT,
1196             typename GetNodeT, typename FormSCCCallbackT>
1197   static void buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1198                                GetEndT &&GetEnd, GetNodeT &&GetNode,
1199                                FormSCCCallbackT &&FormSCC);
1200 
1201   /// Build the SCCs for a RefSCC out of a list of nodes.
1202   void buildSCCs(RefSCC &RC, node_stack_range Nodes);
1203 
1204   /// Get the index of a RefSCC within the postorder traversal.
1205   ///
1206   /// Requires that this RefSCC is a valid one in the (perhaps partial)
1207   /// postorder traversed part of the graph.
getRefSCCIndex(RefSCC & RC)1208   int getRefSCCIndex(RefSCC &RC) {
1209     auto IndexIt = RefSCCIndices.find(&RC);
1210     assert(IndexIt != RefSCCIndices.end() && "RefSCC doesn't have an index!");
1211     assert(PostOrderRefSCCs[IndexIt->second] == &RC &&
1212            "Index does not point back at RC!");
1213     return IndexIt->second;
1214   }
1215 };
1216 
1217 inline LazyCallGraph::Edge::Edge() = default;
Edge(Node & N,Kind K)1218 inline LazyCallGraph::Edge::Edge(Node &N, Kind K) : Value(&N, K) {}
1219 
1220 inline LazyCallGraph::Edge::operator bool() const {
1221   return Value.getPointer() && !Value.getPointer()->isDead();
1222 }
1223 
getKind()1224 inline LazyCallGraph::Edge::Kind LazyCallGraph::Edge::getKind() const {
1225   assert(*this && "Queried a null edge!");
1226   return Value.getInt();
1227 }
1228 
isCall()1229 inline bool LazyCallGraph::Edge::isCall() const {
1230   assert(*this && "Queried a null edge!");
1231   return getKind() == Call;
1232 }
1233 
getNode()1234 inline LazyCallGraph::Node &LazyCallGraph::Edge::getNode() const {
1235   assert(*this && "Queried a null edge!");
1236   return *Value.getPointer();
1237 }
1238 
getFunction()1239 inline Function &LazyCallGraph::Edge::getFunction() const {
1240   assert(*this && "Queried a null edge!");
1241   return getNode().getFunction();
1242 }
1243 
1244 // Provide GraphTraits specializations for call graphs.
1245 template <> struct GraphTraits<LazyCallGraph::Node *> {
1246   using NodeRef = LazyCallGraph::Node *;
1247   using ChildIteratorType = LazyCallGraph::EdgeSequence::iterator;
1248 
1249   static NodeRef getEntryNode(NodeRef N) { return N; }
1250   static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); }
1251   static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); }
1252 };
1253 template <> struct GraphTraits<LazyCallGraph *> {
1254   using NodeRef = LazyCallGraph::Node *;
1255   using ChildIteratorType = LazyCallGraph::EdgeSequence::iterator;
1256 
1257   static NodeRef getEntryNode(NodeRef N) { return N; }
1258   static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); }
1259   static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); }
1260 };
1261 
1262 /// An analysis pass which computes the call graph for a module.
1263 class LazyCallGraphAnalysis : public AnalysisInfoMixin<LazyCallGraphAnalysis> {
1264   friend AnalysisInfoMixin<LazyCallGraphAnalysis>;
1265 
1266   LLVM_ABI static AnalysisKey Key;
1267 
1268 public:
1269   /// Inform generic clients of the result type.
1270   using Result = LazyCallGraph;
1271 
1272   /// Compute the \c LazyCallGraph for the module \c M.
1273   ///
1274   /// This just builds the set of entry points to the call graph. The rest is
1275   /// built lazily as it is walked.
1276   LazyCallGraph run(Module &M, ModuleAnalysisManager &AM) {
1277     FunctionAnalysisManager &FAM =
1278         AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1279     auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1280       return FAM.getResult<TargetLibraryAnalysis>(F);
1281     };
1282     return LazyCallGraph(M, GetTLI);
1283   }
1284 };
1285 
1286 /// A pass which prints the call graph to a \c raw_ostream.
1287 ///
1288 /// This is primarily useful for testing the analysis.
1289 class LazyCallGraphPrinterPass
1290     : public PassInfoMixin<LazyCallGraphPrinterPass> {
1291   raw_ostream &OS;
1292 
1293 public:
1294   LLVM_ABI explicit LazyCallGraphPrinterPass(raw_ostream &OS);
1295 
1296   LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
1297 
1298   static bool isRequired() { return true; }
1299 };
1300 
1301 /// A pass which prints the call graph as a DOT file to a \c raw_ostream.
1302 ///
1303 /// This is primarily useful for visualization purposes.
1304 class LazyCallGraphDOTPrinterPass
1305     : public PassInfoMixin<LazyCallGraphDOTPrinterPass> {
1306   raw_ostream &OS;
1307 
1308 public:
1309   LLVM_ABI explicit LazyCallGraphDOTPrinterPass(raw_ostream &OS);
1310 
1311   LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
1312 
1313   static bool isRequired() { return true; }
1314 };
1315 
1316 extern template struct LLVM_TEMPLATE_ABI
1317     Any::TypeId<const LazyCallGraph::SCC *>;
1318 } // end namespace llvm
1319 
1320 #endif // LLVM_ANALYSIS_LAZYCALLGRAPH_H
1321