1 //===- LazyCallGraph.h - Analysis of a Module's call graph ------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Implements a lazy call graph analysis and related passes for the new pass
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'
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.
29 /// To understand the specific rules and nature of this call graph analysis,
30 /// see the documentation of the \c LazyCallGraph below.
32 //===----------------------------------------------------------------------===//
34 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
35 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H
37 #include "llvm/ADT/ArrayRef.h"
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/Optional.h"
40 #include "llvm/ADT/PointerIntPair.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringRef.h"
45 #include "llvm/ADT/iterator.h"
46 #include "llvm/ADT/iterator_range.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/Function.h"
51 #include "llvm/IR/PassManager.h"
52 #include "llvm/Support/Allocator.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/raw_ostream.h"
65 /// A lazily constructed view of the call graph of a module.
67 /// With the edges of this graph, the motivating constraint that we are
68 /// attempting to maintain is that function-local optimization, CGSCC-local
69 /// optimizations, and optimizations transforming a pair of functions connected
70 /// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC
71 /// DAG. That is, no optimizations will delete, remove, or add an edge such
72 /// that functions already visited in a bottom-up order of the SCC DAG are no
73 /// longer valid to have visited, or such that functions not yet visited in
74 /// a bottom-up order of the SCC DAG are not required to have already been
77 /// Within this constraint, the desire is to minimize the merge points of the
78 /// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points
79 /// in the SCC DAG, the more independence there is in optimizing within it.
80 /// There is a strong desire to enable parallelization of optimizations over
81 /// the call graph, and both limited fanout and merge points will (artificially
82 /// in some cases) limit the scaling of such an effort.
84 /// To this end, graph represents both direct and any potential resolution to
85 /// an indirect call edge. Another way to think about it is that it represents
86 /// both the direct call edges and any direct call edges that might be formed
87 /// through static optimizations. Specifically, it considers taking the address
88 /// of a function to be an edge in the call graph because this might be
89 /// forwarded to become a direct call by some subsequent function-local
90 /// optimization. The result is that the graph closely follows the use-def
91 /// edges for functions. Walking "up" the graph can be done by looking at all
92 /// of the uses of a function.
94 /// The roots of the call graph are the external functions and functions
95 /// escaped into global variables. Those functions can be called from outside
96 /// of the module or via unknowable means in the IR -- we may not be able to
97 /// form even a potential call edge from a function body which may dynamically
98 /// load the function and call it.
100 /// This analysis still requires updates to remain valid after optimizations
101 /// which could potentially change the set of potential callees. The
102 /// constraints it operates under only make the traversal order remain valid.
104 /// The entire analysis must be re-computed if full interprocedural
105 /// optimizations run at any point. For example, globalopt completely
106 /// invalidates the information in this analysis.
108 /// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish
109 /// it from the existing CallGraph. At some point, it is expected that this
110 /// will be the only call graph and it will be renamed accordingly.
111 class LazyCallGraph
{
118 class call_edge_iterator
;
120 /// A class used to represent edges in the call graph.
122 /// The lazy call graph models both *call* edges and *reference* edges. Call
123 /// edges are much what you would expect, and exist when there is a 'call' or
124 /// 'invoke' instruction of some function. Reference edges are also tracked
125 /// along side these, and exist whenever any instruction (transitively
126 /// through its operands) references a function. All call edges are
127 /// inherently reference edges, and so the reference graph forms a superset
128 /// of the formal call graph.
130 /// All of these forms of edges are fundamentally represented as outgoing
131 /// edges. The edges are stored in the source node and point at the target
132 /// node. This allows the edge structure itself to be a very compact data
133 /// structure: essentially a tagged pointer.
136 /// The kind of edge in the graph.
137 enum Kind
: bool { Ref
= false, Call
= true };
140 explicit Edge(Node
&N
, Kind K
);
142 /// Test whether the edge is null.
144 /// This happens when an edge has been deleted. We leave the edge objects
145 /// around but clear them.
146 explicit operator bool() const;
148 /// Returnss the \c Kind of the edge.
149 Kind
getKind() const;
151 /// Test whether the edge represents a direct call to a function.
153 /// This requires that the edge is not null.
156 /// Get the call graph node referenced by this edge.
158 /// This requires that the edge is not null.
159 Node
&getNode() const;
161 /// Get the function referenced by this edge.
163 /// This requires that the edge is not null.
164 Function
&getFunction() const;
167 friend class LazyCallGraph::EdgeSequence
;
168 friend class LazyCallGraph::RefSCC
;
170 PointerIntPair
<Node
*, 1, Kind
> Value
;
172 void setKind(Kind K
) { Value
.setInt(K
); }
175 /// The edge sequence object.
177 /// This typically exists entirely within the node but is exposed as
178 /// a separate type because a node doesn't initially have edges. An explicit
179 /// population step is required to produce this sequence at first and it is
180 /// then cached in the node. It is also used to represent edges entering the
181 /// graph from outside the module to model the graph's roots.
183 /// The sequence itself both iterable and indexable. The indexes remain
184 /// stable even as the sequence mutates (including removal).
186 friend class LazyCallGraph
;
187 friend class LazyCallGraph::Node
;
188 friend class LazyCallGraph::RefSCC
;
190 using VectorT
= SmallVector
<Edge
, 4>;
191 using VectorImplT
= SmallVectorImpl
<Edge
>;
194 /// An iterator used for the edges to both entry nodes and child nodes.
196 : public iterator_adaptor_base
<iterator
, VectorImplT::iterator
,
197 std::forward_iterator_tag
> {
198 friend class LazyCallGraph
;
199 friend class LazyCallGraph::Node
;
201 VectorImplT::iterator E
;
203 // Build the iterator for a specific position in the edge list.
204 iterator(VectorImplT::iterator BaseI
, VectorImplT::iterator E
)
205 : iterator_adaptor_base(BaseI
), E(E
) {
206 while (I
!= E
&& !*I
)
211 iterator() = default;
213 using iterator_adaptor_base::operator++;
214 iterator
&operator++() {
217 } while (I
!= E
&& !*I
);
222 /// An iterator over specifically call edges.
224 /// This has the same iteration properties as the \c iterator, but
225 /// restricts itself to edges which represent actual calls.
227 : public iterator_adaptor_base
<call_iterator
, VectorImplT::iterator
,
228 std::forward_iterator_tag
> {
229 friend class LazyCallGraph
;
230 friend class LazyCallGraph::Node
;
232 VectorImplT::iterator E
;
234 /// Advance the iterator to the next valid, call edge.
235 void advanceToNextEdge() {
236 while (I
!= E
&& (!*I
|| !I
->isCall()))
240 // Build the iterator for a specific position in the edge list.
241 call_iterator(VectorImplT::iterator BaseI
, VectorImplT::iterator E
)
242 : iterator_adaptor_base(BaseI
), E(E
) {
247 call_iterator() = default;
249 using iterator_adaptor_base::operator++;
250 call_iterator
&operator++() {
257 iterator
begin() { return iterator(Edges
.begin(), Edges
.end()); }
258 iterator
end() { return iterator(Edges
.end(), Edges
.end()); }
260 Edge
&operator[](int i
) { return Edges
[i
]; }
261 Edge
&operator[](Node
&N
) {
262 assert(EdgeIndexMap
.find(&N
) != EdgeIndexMap
.end() && "No such edge!");
263 auto &E
= Edges
[EdgeIndexMap
.find(&N
)->second
];
264 assert(E
&& "Dead or null edge!");
268 Edge
*lookup(Node
&N
) {
269 auto EI
= EdgeIndexMap
.find(&N
);
270 if (EI
== EdgeIndexMap
.end())
272 auto &E
= Edges
[EI
->second
];
273 return E
? &E
: nullptr;
276 call_iterator
call_begin() {
277 return call_iterator(Edges
.begin(), Edges
.end());
279 call_iterator
call_end() { return call_iterator(Edges
.end(), Edges
.end()); }
281 iterator_range
<call_iterator
> calls() {
282 return make_range(call_begin(), call_end());
286 for (auto &E
: Edges
)
295 DenseMap
<Node
*, int> EdgeIndexMap
;
297 EdgeSequence() = default;
299 /// Internal helper to insert an edge to a node.
300 void insertEdgeInternal(Node
&ChildN
, Edge::Kind EK
);
302 /// Internal helper to change an edge kind.
303 void setEdgeKind(Node
&ChildN
, Edge::Kind EK
);
305 /// Internal helper to remove the edge to the given function.
306 bool removeEdgeInternal(Node
&ChildN
);
308 /// Internal helper to replace an edge key with a new one.
310 /// This should be used when the function for a particular node in the
311 /// graph gets replaced and we are updating all of the edges to that node
312 /// to use the new function as the key.
313 void replaceEdgeKey(Function
&OldTarget
, Function
&NewTarget
);
316 /// A node in the call graph.
318 /// This represents a single node. It's primary roles are to cache the list of
319 /// callees, de-duplicate and provide fast testing of whether a function is
320 /// a callee, and facilitate iteration of child nodes in the graph.
322 /// The node works much like an optional in order to lazily populate the
323 /// edges of each node. Until populated, there are no edges. Once populated,
324 /// you can access the edges by dereferencing the node or using the `->`
325 /// operator as if the node was an `Optional<EdgeSequence>`.
327 friend class LazyCallGraph
;
328 friend class LazyCallGraph::RefSCC
;
331 LazyCallGraph
&getGraph() const { return *G
; }
333 Function
&getFunction() const { return *F
; }
335 StringRef
getName() const { return F
->getName(); }
337 /// Equality is defined as address equality.
338 bool operator==(const Node
&N
) const { return this == &N
; }
339 bool operator!=(const Node
&N
) const { return !operator==(N
); }
341 /// Tests whether the node has been populated with edges.
342 bool isPopulated() const { return Edges
.hasValue(); }
344 /// Tests whether this is actually a dead node and no longer valid.
346 /// Users rarely interact with nodes in this state and other methods are
347 /// invalid. This is used to model a node in an edge list where the
348 /// function has been completely removed.
349 bool isDead() const {
351 "Both graph and function pointers should be null or non-null.");
355 // We allow accessing the edges by dereferencing or using the arrow
356 // operator, essentially wrapping the internal optional.
357 EdgeSequence
&operator*() const {
358 // Rip const off because the node itself isn't changing here.
359 return const_cast<EdgeSequence
&>(*Edges
);
361 EdgeSequence
*operator->() const { return &**this; }
363 /// Populate the edges of this node if necessary.
365 /// The first time this is called it will populate the edges for this node
366 /// in the graph. It does this by scanning the underlying function, so once
367 /// this is done, any changes to that function must be explicitly reflected
368 /// in updates to the graph.
370 /// \returns the populated \c EdgeSequence to simplify walking it.
372 /// This will not update or re-scan anything if called repeatedly. Instead,
373 /// the edge sequence is cached and returned immediately on subsequent
375 EdgeSequence
&populate() {
379 return populateSlow();
386 // We provide for the DFS numbering and Tarjan walk lowlink numbers to be
387 // stored directly within the node. These are both '-1' when nodes are part
388 // of an SCC (or RefSCC), or '0' when not yet reached in a DFS walk.
392 Optional
<EdgeSequence
> Edges
;
394 /// Basic constructor implements the scanning of F into Edges and
396 Node(LazyCallGraph
&G
, Function
&F
) : G(&G
), F(&F
) {}
398 /// Implementation of the scan when populating.
399 EdgeSequence
&populateSlow();
401 /// Internal helper to directly replace the function with a new one.
403 /// This is used to facilitate tranfsormations which need to replace the
404 /// formal Function object but directly move the body and users from one to
406 void replaceFunction(Function
&NewF
);
408 void clear() { Edges
.reset(); }
410 /// Print the name of this node's function.
411 friend raw_ostream
&operator<<(raw_ostream
&OS
, const Node
&N
) {
412 return OS
<< N
.F
->getName();
415 /// Dump the name of this node's function to stderr.
419 /// An SCC of the call graph.
421 /// This represents a Strongly Connected Component of the direct call graph
422 /// -- ignoring indirect calls and function references. It stores this as
423 /// a collection of call graph nodes. While the order of nodes in the SCC is
424 /// stable, it is not any particular order.
426 /// The SCCs are nested within a \c RefSCC, see below for details about that
427 /// outer structure. SCCs do not support mutation of the call graph, that
428 /// must be done through the containing \c RefSCC in order to fully reason
429 /// about the ordering and connections of the graph.
431 friend class LazyCallGraph
;
432 friend class LazyCallGraph::Node
;
435 SmallVector
<Node
*, 1> Nodes
;
437 template <typename NodeRangeT
>
438 SCC(RefSCC
&OuterRefSCC
, NodeRangeT
&&Nodes
)
439 : OuterRefSCC(&OuterRefSCC
), Nodes(std::forward
<NodeRangeT
>(Nodes
)) {}
442 OuterRefSCC
= nullptr;
446 /// Print a short descrtiption useful for debugging or logging.
448 /// We print the function names in the SCC wrapped in '()'s and skipping
449 /// the middle functions if there are a large number.
451 // Note: this is defined inline to dodge issues with GCC's interpretation
452 // of enclosing namespaces for friend function declarations.
453 friend raw_ostream
&operator<<(raw_ostream
&OS
, const SCC
&C
) {
456 for (LazyCallGraph::Node
&N
: C
) {
459 // Elide the inner elements if there are too many.
461 OS
<< "..., " << *C
.Nodes
.back();
471 /// Dump a short description of this SCC to stderr.
475 /// Verify invariants about the SCC.
477 /// This will attempt to validate all of the basic invariants within an
478 /// SCC, but not that it is a strongly connected componet per-se. Primarily
479 /// useful while building and updating the graph to check that basic
480 /// properties are in place rather than having inexplicable crashes later.
485 using iterator
= pointee_iterator
<SmallVectorImpl
<Node
*>::const_iterator
>;
487 iterator
begin() const { return Nodes
.begin(); }
488 iterator
end() const { return Nodes
.end(); }
490 int size() const { return Nodes
.size(); }
492 RefSCC
&getOuterRefSCC() const { return *OuterRefSCC
; }
494 /// Test if this SCC is a parent of \a C.
496 /// Note that this is linear in the number of edges departing the current
498 bool isParentOf(const SCC
&C
) const;
500 /// Test if this SCC is an ancestor of \a C.
502 /// Note that in the worst case this is linear in the number of edges
503 /// departing the current SCC and every SCC in the entire graph reachable
504 /// from this SCC. Thus this very well may walk every edge in the entire
505 /// call graph! Do not call this in a tight loop!
506 bool isAncestorOf(const SCC
&C
) const;
508 /// Test if this SCC is a child of \a C.
510 /// See the comments for \c isParentOf for detailed notes about the
511 /// complexity of this routine.
512 bool isChildOf(const SCC
&C
) const { return C
.isParentOf(*this); }
514 /// Test if this SCC is a descendant of \a C.
516 /// See the comments for \c isParentOf for detailed notes about the
517 /// complexity of this routine.
518 bool isDescendantOf(const SCC
&C
) const { return C
.isAncestorOf(*this); }
520 /// Provide a short name by printing this SCC to a std::string.
522 /// This copes with the fact that we don't have a name per-se for an SCC
523 /// while still making the use of this in debugging and logging useful.
524 std::string
getName() const {
526 raw_string_ostream
OS(Name
);
533 /// A RefSCC of the call graph.
535 /// This models a Strongly Connected Component of function reference edges in
536 /// the call graph. As opposed to actual SCCs, these can be used to scope
537 /// subgraphs of the module which are independent from other subgraphs of the
538 /// module because they do not reference it in any way. This is also the unit
539 /// where we do mutation of the graph in order to restrict mutations to those
540 /// which don't violate this independence.
542 /// A RefSCC contains a DAG of actual SCCs. All the nodes within the RefSCC
543 /// are necessarily within some actual SCC that nests within it. Since
544 /// a direct call *is* a reference, there will always be at least one RefSCC
547 friend class LazyCallGraph
;
548 friend class LazyCallGraph::Node
;
552 /// A postorder list of the inner SCCs.
553 SmallVector
<SCC
*, 4> SCCs
;
555 /// A map from SCC to index in the postorder list.
556 SmallDenseMap
<SCC
*, int, 4> SCCIndices
;
558 /// Fast-path constructor. RefSCCs should instead be constructed by calling
559 /// formRefSCCFast on the graph itself.
560 RefSCC(LazyCallGraph
&G
);
567 /// Print a short description useful for debugging or logging.
569 /// We print the SCCs wrapped in '[]'s and skipping the middle SCCs if
570 /// there are a large number.
572 // Note: this is defined inline to dodge issues with GCC's interpretation
573 // of enclosing namespaces for friend function declarations.
574 friend raw_ostream
&operator<<(raw_ostream
&OS
, const RefSCC
&RC
) {
577 for (LazyCallGraph::SCC
&C
: RC
) {
580 // Elide the inner elements if there are too many.
582 OS
<< "..., " << *RC
.SCCs
.back();
592 /// Dump a short description of this RefSCC to stderr.
596 /// Verify invariants about the RefSCC and all its SCCs.
598 /// This will attempt to validate all of the invariants *within* the
599 /// RefSCC, but not that it is a strongly connected component of the larger
600 /// graph. This makes it useful even when partially through an update.
602 /// Invariants checked:
603 /// - SCCs and their indices match.
604 /// - The SCCs list is in fact in post-order.
608 /// Handle any necessary parent set updates after inserting a trivial ref
610 void handleTrivialEdgeInsertion(Node
&SourceN
, Node
&TargetN
);
613 using iterator
= pointee_iterator
<SmallVectorImpl
<SCC
*>::const_iterator
>;
614 using range
= iterator_range
<iterator
>;
615 using parent_iterator
=
616 pointee_iterator
<SmallPtrSetImpl
<RefSCC
*>::const_iterator
>;
618 iterator
begin() const { return SCCs
.begin(); }
619 iterator
end() const { return SCCs
.end(); }
621 ssize_t
size() const { return SCCs
.size(); }
623 SCC
&operator[](int Idx
) { return *SCCs
[Idx
]; }
625 iterator
find(SCC
&C
) const {
626 return SCCs
.begin() + SCCIndices
.find(&C
)->second
;
629 /// Test if this RefSCC is a parent of \a RC.
631 /// CAUTION: This method walks every edge in the \c RefSCC, it can be very
633 bool isParentOf(const RefSCC
&RC
) const;
635 /// Test if this RefSCC is an ancestor of \a RC.
637 /// CAUTION: This method walks the directed graph of edges as far as
638 /// necessary to find a possible path to the argument. In the worst case
639 /// this may walk the entire graph and can be extremely expensive.
640 bool isAncestorOf(const RefSCC
&RC
) const;
642 /// Test if this RefSCC is a child of \a RC.
644 /// CAUTION: This method walks every edge in the argument \c RefSCC, it can
645 /// be very expensive.
646 bool isChildOf(const RefSCC
&RC
) const { return RC
.isParentOf(*this); }
648 /// Test if this RefSCC is a descendant of \a RC.
650 /// CAUTION: This method walks the directed graph of edges as far as
651 /// necessary to find a possible path from the argument. In the worst case
652 /// this may walk the entire graph and can be extremely expensive.
653 bool isDescendantOf(const RefSCC
&RC
) const {
654 return RC
.isAncestorOf(*this);
657 /// Provide a short name by printing this RefSCC to a std::string.
659 /// This copes with the fact that we don't have a name per-se for an RefSCC
660 /// while still making the use of this in debugging and logging useful.
661 std::string
getName() const {
663 raw_string_ostream
OS(Name
);
670 /// \name Mutation API
672 /// These methods provide the core API for updating the call graph in the
673 /// presence of (potentially still in-flight) DFS-found RefSCCs and SCCs.
675 /// Note that these methods sometimes have complex runtimes, so be careful
676 /// how you call them.
678 /// Make an existing internal ref edge into a call edge.
680 /// This may form a larger cycle and thus collapse SCCs into TargetN's SCC.
681 /// If that happens, the optional callback \p MergedCB will be invoked (if
682 /// provided) on the SCCs being merged away prior to actually performing
683 /// the merge. Note that this will never include the target SCC as that
684 /// will be the SCC functions are merged into to resolve the cycle. Once
685 /// this function returns, these merged SCCs are not in a valid state but
686 /// the pointers will remain valid until destruction of the parent graph
687 /// instance for the purpose of clearing cached information. This function
688 /// also returns 'true' if a cycle was formed and some SCCs merged away as
691 /// After this operation, both SourceN's SCC and TargetN's SCC may move
692 /// position within this RefSCC's postorder list. Any SCCs merged are
693 /// merged into the TargetN's SCC in order to preserve reachability analyses
694 /// which took place on that SCC.
695 bool switchInternalEdgeToCall(
696 Node
&SourceN
, Node
&TargetN
,
697 function_ref
<void(ArrayRef
<SCC
*> MergedSCCs
)> MergeCB
= {});
699 /// Make an existing internal call edge between separate SCCs into a ref
702 /// If SourceN and TargetN in separate SCCs within this RefSCC, changing
703 /// the call edge between them to a ref edge is a trivial operation that
704 /// does not require any structural changes to the call graph.
705 void switchTrivialInternalEdgeToRef(Node
&SourceN
, Node
&TargetN
);
707 /// Make an existing internal call edge within a single SCC into a ref
710 /// Since SourceN and TargetN are part of a single SCC, this SCC may be
711 /// split up due to breaking a cycle in the call edges that formed it. If
712 /// that happens, then this routine will insert new SCCs into the postorder
713 /// list *before* the SCC of TargetN (previously the SCC of both). This
714 /// preserves postorder as the TargetN can reach all of the other nodes by
715 /// definition of previously being in a single SCC formed by the cycle from
716 /// SourceN to TargetN.
718 /// The newly added SCCs are added *immediately* and contiguously
719 /// prior to the TargetN SCC and return the range covering the new SCCs in
720 /// the RefSCC's postorder sequence. You can directly iterate the returned
721 /// range to observe all of the new SCCs in postorder.
723 /// Note that if SourceN and TargetN are in separate SCCs, the simpler
724 /// routine `switchTrivialInternalEdgeToRef` should be used instead.
725 iterator_range
<iterator
> switchInternalEdgeToRef(Node
&SourceN
,
728 /// Make an existing outgoing ref edge into a call edge.
730 /// Note that this is trivial as there are no cyclic impacts and there
731 /// remains a reference edge.
732 void switchOutgoingEdgeToCall(Node
&SourceN
, Node
&TargetN
);
734 /// Make an existing outgoing call edge into a ref edge.
736 /// This is trivial as there are no cyclic impacts and there remains
737 /// a reference edge.
738 void switchOutgoingEdgeToRef(Node
&SourceN
, Node
&TargetN
);
740 /// Insert a ref edge from one node in this RefSCC to another in this
743 /// This is always a trivial operation as it doesn't change any part of the
744 /// graph structure besides connecting the two nodes.
746 /// Note that we don't support directly inserting internal *call* edges
747 /// because that could change the graph structure and requires returning
748 /// information about what became invalid. As a consequence, the pattern
749 /// should be to first insert the necessary ref edge, and then to switch it
750 /// to a call edge if needed and handle any invalidation that results. See
751 /// the \c switchInternalEdgeToCall routine for details.
752 void insertInternalRefEdge(Node
&SourceN
, Node
&TargetN
);
754 /// Insert an edge whose parent is in this RefSCC and child is in some
757 /// There must be an existing path from the \p SourceN to the \p TargetN.
758 /// This operation is inexpensive and does not change the set of SCCs and
759 /// RefSCCs in the graph.
760 void insertOutgoingEdge(Node
&SourceN
, Node
&TargetN
, Edge::Kind EK
);
762 /// Insert an edge whose source is in a descendant RefSCC and target is in
765 /// There must be an existing path from the target to the source in this
768 /// NB! This is has the potential to be a very expensive function. It
769 /// inherently forms a cycle in the prior RefSCC DAG and we have to merge
770 /// RefSCCs to resolve that cycle. But finding all of the RefSCCs which
771 /// participate in the cycle can in the worst case require traversing every
772 /// RefSCC in the graph. Every attempt is made to avoid that, but passes
773 /// must still exercise caution calling this routine repeatedly.
775 /// Also note that this can only insert ref edges. In order to insert
776 /// a call edge, first insert a ref edge and then switch it to a call edge.
777 /// These are intentionally kept as separate interfaces because each step
778 /// of the operation invalidates a different set of data structures.
780 /// This returns all the RefSCCs which were merged into the this RefSCC
781 /// (the target's). This allows callers to invalidate any cached
784 /// FIXME: We could possibly optimize this quite a bit for cases where the
785 /// caller and callee are very nearby in the graph. See comments in the
786 /// implementation for details, but that use case might impact users.
787 SmallVector
<RefSCC
*, 1> insertIncomingRefEdge(Node
&SourceN
,
790 /// Remove an edge whose source is in this RefSCC and target is *not*.
792 /// This removes an inter-RefSCC edge. All inter-RefSCC edges originating
793 /// from this SCC have been fully explored by any in-flight DFS graph
794 /// formation, so this is always safe to call once you have the source
797 /// This operation does not change the cyclic structure of the graph and so
798 /// is very inexpensive. It may change the connectivity graph of the SCCs
799 /// though, so be careful calling this while iterating over them.
800 void removeOutgoingEdge(Node
&SourceN
, Node
&TargetN
);
802 /// Remove a list of ref edges which are entirely within this RefSCC.
804 /// Both the \a SourceN and all of the \a TargetNs must be within this
805 /// RefSCC. Removing these edges may break cycles that form this RefSCC and
806 /// thus this operation may change the RefSCC graph significantly. In
807 /// particular, this operation will re-form new RefSCCs based on the
808 /// remaining connectivity of the graph. The following invariants are
809 /// guaranteed to hold after calling this method:
811 /// 1) If a ref-cycle remains after removal, it leaves this RefSCC intact
812 /// and in the graph. No new RefSCCs are built.
813 /// 2) Otherwise, this RefSCC will be dead after this call and no longer in
814 /// the graph or the postorder traversal of the call graph. Any iterator
815 /// pointing at this RefSCC will become invalid.
816 /// 3) All newly formed RefSCCs will be returned and the order of the
817 /// RefSCCs returned will be a valid postorder traversal of the new
819 /// 4) No RefSCC other than this RefSCC has its member set changed (this is
820 /// inherent in the definition of removing such an edge).
822 /// These invariants are very important to ensure that we can build
823 /// optimization pipelines on top of the CGSCC pass manager which
824 /// intelligently update the RefSCC graph without invalidating other parts
825 /// of the RefSCC graph.
827 /// Note that we provide no routine to remove a *call* edge. Instead, you
828 /// must first switch it to a ref edge using \c switchInternalEdgeToRef.
829 /// This split API is intentional as each of these two steps can invalidate
830 /// a different aspect of the graph structure and needs to have the
831 /// invalidation handled independently.
833 /// The runtime complexity of this method is, in the worst case, O(V+E)
834 /// where V is the number of nodes in this RefSCC and E is the number of
835 /// edges leaving the nodes in this RefSCC. Note that E includes both edges
836 /// within this RefSCC and edges from this RefSCC to child RefSCCs. Some
837 /// effort has been made to minimize the overhead of common cases such as
838 /// self-edges and edge removals which result in a spanning tree with no
840 SmallVector
<RefSCC
*, 1> removeInternalRefEdge(Node
&SourceN
,
841 ArrayRef
<Node
*> TargetNs
);
843 /// A convenience wrapper around the above to handle trivial cases of
844 /// inserting a new call edge.
846 /// This is trivial whenever the target is in the same SCC as the source or
847 /// the edge is an outgoing edge to some descendant SCC. In these cases
848 /// there is no change to the cyclic structure of SCCs or RefSCCs.
850 /// To further make calling this convenient, it also handles inserting
851 /// already existing edges.
852 void insertTrivialCallEdge(Node
&SourceN
, Node
&TargetN
);
854 /// A convenience wrapper around the above to handle trivial cases of
855 /// inserting a new ref edge.
857 /// This is trivial whenever the target is in the same RefSCC as the source
858 /// or the edge is an outgoing edge to some descendant RefSCC. In these
859 /// cases there is no change to the cyclic structure of the RefSCCs.
861 /// To further make calling this convenient, it also handles inserting
862 /// already existing edges.
863 void insertTrivialRefEdge(Node
&SourceN
, Node
&TargetN
);
865 /// Directly replace a node's function with a new function.
867 /// This should be used when moving the body and users of a function to
868 /// a new formal function object but not otherwise changing the call graph
869 /// structure in any way.
871 /// It requires that the old function in the provided node have zero uses
872 /// and the new function must have calls and references to it establishing
873 /// an equivalent graph.
874 void replaceNodeFunction(Node
&N
, Function
&NewF
);
879 /// A post-order depth-first RefSCC iterator over the call graph.
881 /// This iterator walks the cached post-order sequence of RefSCCs. However,
882 /// it trades stability for flexibility. It is restricted to a forward
883 /// iterator but will survive mutations which insert new RefSCCs and continue
884 /// to point to the same RefSCC even if it moves in the post-order sequence.
885 class postorder_ref_scc_iterator
886 : public iterator_facade_base
<postorder_ref_scc_iterator
,
887 std::forward_iterator_tag
, RefSCC
> {
888 friend class LazyCallGraph
;
889 friend class LazyCallGraph::Node
;
891 /// Nonce type to select the constructor for the end iterator.
895 RefSCC
*RC
= nullptr;
897 /// Build the begin iterator for a node.
898 postorder_ref_scc_iterator(LazyCallGraph
&G
) : G(&G
), RC(getRC(G
, 0)) {}
900 /// Build the end iterator for a node. This is selected purely by overload.
901 postorder_ref_scc_iterator(LazyCallGraph
&G
, IsAtEndT
/*Nonce*/) : G(&G
) {}
903 /// Get the post-order RefSCC at the given index of the postorder walk,
904 /// populating it if necessary.
905 static RefSCC
*getRC(LazyCallGraph
&G
, int Index
) {
906 if (Index
== (int)G
.PostOrderRefSCCs
.size())
910 return G
.PostOrderRefSCCs
[Index
];
914 bool operator==(const postorder_ref_scc_iterator
&Arg
) const {
915 return G
== Arg
.G
&& RC
== Arg
.RC
;
918 reference
operator*() const { return *RC
; }
920 using iterator_facade_base::operator++;
921 postorder_ref_scc_iterator
&operator++() {
922 assert(RC
&& "Cannot increment the end iterator!");
923 RC
= getRC(*G
, G
->RefSCCIndices
.find(RC
)->second
+ 1);
928 /// Construct a graph for the given module.
930 /// This sets up the graph and computes all of the entry points of the graph.
931 /// No function definitions are scanned until their nodes in the graph are
932 /// requested during traversal.
933 LazyCallGraph(Module
&M
, TargetLibraryInfo
&TLI
);
935 LazyCallGraph(LazyCallGraph
&&G
);
936 LazyCallGraph
&operator=(LazyCallGraph
&&RHS
);
938 EdgeSequence::iterator
begin() { return EntryEdges
.begin(); }
939 EdgeSequence::iterator
end() { return EntryEdges
.end(); }
943 postorder_ref_scc_iterator
postorder_ref_scc_begin() {
944 if (!EntryEdges
.empty())
945 assert(!PostOrderRefSCCs
.empty() &&
946 "Must form RefSCCs before iterating them!");
947 return postorder_ref_scc_iterator(*this);
949 postorder_ref_scc_iterator
postorder_ref_scc_end() {
950 if (!EntryEdges
.empty())
951 assert(!PostOrderRefSCCs
.empty() &&
952 "Must form RefSCCs before iterating them!");
953 return postorder_ref_scc_iterator(*this,
954 postorder_ref_scc_iterator::IsAtEndT());
957 iterator_range
<postorder_ref_scc_iterator
> postorder_ref_sccs() {
958 return make_range(postorder_ref_scc_begin(), postorder_ref_scc_end());
961 /// Lookup a function in the graph which has already been scanned and added.
962 Node
*lookup(const Function
&F
) const { return NodeMap
.lookup(&F
); }
964 /// Lookup a function's SCC in the graph.
966 /// \returns null if the function hasn't been assigned an SCC via the RefSCC
968 SCC
*lookupSCC(Node
&N
) const { return SCCMap
.lookup(&N
); }
970 /// Lookup a function's RefSCC in the graph.
972 /// \returns null if the function hasn't been assigned a RefSCC via the
973 /// RefSCC iterator walk.
974 RefSCC
*lookupRefSCC(Node
&N
) const {
975 if (SCC
*C
= lookupSCC(N
))
976 return &C
->getOuterRefSCC();
981 /// Get a graph node for a given function, scanning it to populate the graph
982 /// data as necessary.
983 Node
&get(Function
&F
) {
984 Node
*&N
= NodeMap
[&F
];
988 return insertInto(F
, N
);
991 /// Get the sequence of known and defined library functions.
993 /// These functions, because they are known to LLVM, can have calls
994 /// introduced out of thin air from arbitrary IR.
995 ArrayRef
<Function
*> getLibFunctions() const {
996 return LibFunctions
.getArrayRef();
999 /// Test whether a function is a known and defined library function tracked by
1002 /// Because these functions are known to LLVM they are specially modeled in
1003 /// the call graph and even when all IR-level references have been removed
1004 /// remain active and reachable.
1005 bool isLibFunction(Function
&F
) const { return LibFunctions
.count(&F
); }
1008 /// \name Pre-SCC Mutation API
1010 /// These methods are only valid to call prior to forming any SCCs for this
1011 /// call graph. They can be used to update the core node-graph during
1012 /// a node-based inorder traversal that precedes any SCC-based traversal.
1014 /// Once you begin manipulating a call graph's SCCs, most mutation of the
1015 /// graph must be performed via a RefSCC method. There are some exceptions
1018 /// Update the call graph after inserting a new edge.
1019 void insertEdge(Node
&SourceN
, Node
&TargetN
, Edge::Kind EK
);
1021 /// Update the call graph after inserting a new edge.
1022 void insertEdge(Function
&Source
, Function
&Target
, Edge::Kind EK
) {
1023 return insertEdge(get(Source
), get(Target
), EK
);
1026 /// Update the call graph after deleting an edge.
1027 void removeEdge(Node
&SourceN
, Node
&TargetN
);
1029 /// Update the call graph after deleting an edge.
1030 void removeEdge(Function
&Source
, Function
&Target
) {
1031 return removeEdge(get(Source
), get(Target
));
1037 /// \name General Mutation API
1039 /// There are a very limited set of mutations allowed on the graph as a whole
1040 /// once SCCs have started to be formed. These routines have strict contracts
1041 /// but may be called at any point.
1043 /// Remove a dead function from the call graph (typically to delete it).
1045 /// Note that the function must have an empty use list, and the call graph
1046 /// must be up-to-date prior to calling this. That means it is by itself in
1047 /// a maximal SCC which is by itself in a maximal RefSCC, etc. No structural
1048 /// changes result from calling this routine other than potentially removing
1049 /// entry points into the call graph.
1051 /// If SCC formation has begun, this function must not be part of the current
1052 /// DFS in order to call this safely. Typically, the function will have been
1053 /// fully visited by the DFS prior to calling this routine.
1054 void removeDeadFunction(Function
&F
);
1059 /// \name Static helpers for code doing updates to the call graph.
1061 /// These helpers are used to implement parts of the call graph but are also
1062 /// useful to code doing updates or otherwise wanting to walk the IR in the
1063 /// same patterns as when we build the call graph.
1065 /// Recursively visits the defined functions whose address is reachable from
1066 /// every constant in the \p Worklist.
1068 /// Doesn't recurse through any constants already in the \p Visited set, and
1069 /// updates that set with every constant visited.
1071 /// For each defined function, calls \p Callback with that function.
1072 template <typename CallbackT
>
1073 static void visitReferences(SmallVectorImpl
<Constant
*> &Worklist
,
1074 SmallPtrSetImpl
<Constant
*> &Visited
,
1075 CallbackT Callback
) {
1076 while (!Worklist
.empty()) {
1077 Constant
*C
= Worklist
.pop_back_val();
1079 if (Function
*F
= dyn_cast
<Function
>(C
)) {
1080 if (!F
->isDeclaration())
1085 if (BlockAddress
*BA
= dyn_cast
<BlockAddress
>(C
)) {
1086 // The blockaddress constant expression is a weird special case, we
1087 // can't generically walk its operands the way we do for all other
1089 if (Visited
.insert(BA
->getFunction()).second
)
1090 Worklist
.push_back(BA
->getFunction());
1094 for (Value
*Op
: C
->operand_values())
1095 if (Visited
.insert(cast
<Constant
>(Op
)).second
)
1096 Worklist
.push_back(cast
<Constant
>(Op
));
1103 using node_stack_iterator
= SmallVectorImpl
<Node
*>::reverse_iterator
;
1104 using node_stack_range
= iterator_range
<node_stack_iterator
>;
1106 /// Allocator that holds all the call graph nodes.
1107 SpecificBumpPtrAllocator
<Node
> BPA
;
1109 /// Maps function->node for fast lookup.
1110 DenseMap
<const Function
*, Node
*> NodeMap
;
1112 /// The entry edges into the graph.
1114 /// These edges are from "external" sources. Put another way, they
1115 /// escape at the module scope.
1116 EdgeSequence EntryEdges
;
1118 /// Allocator that holds all the call graph SCCs.
1119 SpecificBumpPtrAllocator
<SCC
> SCCBPA
;
1121 /// Maps Function -> SCC for fast lookup.
1122 DenseMap
<Node
*, SCC
*> SCCMap
;
1124 /// Allocator that holds all the call graph RefSCCs.
1125 SpecificBumpPtrAllocator
<RefSCC
> RefSCCBPA
;
1127 /// The post-order sequence of RefSCCs.
1129 /// This list is lazily formed the first time we walk the graph.
1130 SmallVector
<RefSCC
*, 16> PostOrderRefSCCs
;
1132 /// A map from RefSCC to the index for it in the postorder sequence of
1134 DenseMap
<RefSCC
*, int> RefSCCIndices
;
1136 /// Defined functions that are also known library functions which the
1137 /// optimizer can reason about and therefore might introduce calls to out of
1139 SmallSetVector
<Function
*, 4> LibFunctions
;
1141 /// Helper to insert a new function, with an already looked-up entry in
1143 Node
&insertInto(Function
&F
, Node
*&MappedN
);
1145 /// Helper to update pointers back to the graph object during moves.
1146 void updateGraphPtrs();
1148 /// Allocates an SCC and constructs it using the graph allocator.
1150 /// The arguments are forwarded to the constructor.
1151 template <typename
... Ts
> SCC
*createSCC(Ts
&&... Args
) {
1152 return new (SCCBPA
.Allocate()) SCC(std::forward
<Ts
>(Args
)...);
1155 /// Allocates a RefSCC and constructs it using the graph allocator.
1157 /// The arguments are forwarded to the constructor.
1158 template <typename
... Ts
> RefSCC
*createRefSCC(Ts
&&... Args
) {
1159 return new (RefSCCBPA
.Allocate()) RefSCC(std::forward
<Ts
>(Args
)...);
1162 /// Common logic for building SCCs from a sequence of roots.
1164 /// This is a very generic implementation of the depth-first walk and SCC
1165 /// formation algorithm. It uses a generic sequence of roots and generic
1166 /// callbacks for each step. This is designed to be used to implement both
1167 /// the RefSCC formation and SCC formation with shared logic.
1169 /// Currently this is a relatively naive implementation of Tarjan's DFS
1170 /// algorithm to form the SCCs.
1172 /// FIXME: We should consider newer variants such as Nuutila.
1173 template <typename RootsT
, typename GetBeginT
, typename GetEndT
,
1174 typename GetNodeT
, typename FormSCCCallbackT
>
1175 static void buildGenericSCCs(RootsT
&&Roots
, GetBeginT
&&GetBegin
,
1176 GetEndT
&&GetEnd
, GetNodeT
&&GetNode
,
1177 FormSCCCallbackT
&&FormSCC
);
1179 /// Build the SCCs for a RefSCC out of a list of nodes.
1180 void buildSCCs(RefSCC
&RC
, node_stack_range Nodes
);
1182 /// Get the index of a RefSCC within the postorder traversal.
1184 /// Requires that this RefSCC is a valid one in the (perhaps partial)
1185 /// postorder traversed part of the graph.
1186 int getRefSCCIndex(RefSCC
&RC
) {
1187 auto IndexIt
= RefSCCIndices
.find(&RC
);
1188 assert(IndexIt
!= RefSCCIndices
.end() && "RefSCC doesn't have an index!");
1189 assert(PostOrderRefSCCs
[IndexIt
->second
] == &RC
&&
1190 "Index does not point back at RC!");
1191 return IndexIt
->second
;
1195 inline LazyCallGraph::Edge::Edge() : Value() {}
1196 inline LazyCallGraph::Edge::Edge(Node
&N
, Kind K
) : Value(&N
, K
) {}
1198 inline LazyCallGraph::Edge::operator bool() const {
1199 return Value
.getPointer() && !Value
.getPointer()->isDead();
1202 inline LazyCallGraph::Edge::Kind
LazyCallGraph::Edge::getKind() const {
1203 assert(*this && "Queried a null edge!");
1204 return Value
.getInt();
1207 inline bool LazyCallGraph::Edge::isCall() const {
1208 assert(*this && "Queried a null edge!");
1209 return getKind() == Call
;
1212 inline LazyCallGraph::Node
&LazyCallGraph::Edge::getNode() const {
1213 assert(*this && "Queried a null edge!");
1214 return *Value
.getPointer();
1217 inline Function
&LazyCallGraph::Edge::getFunction() const {
1218 assert(*this && "Queried a null edge!");
1219 return getNode().getFunction();
1222 // Provide GraphTraits specializations for call graphs.
1223 template <> struct GraphTraits
<LazyCallGraph::Node
*> {
1224 using NodeRef
= LazyCallGraph::Node
*;
1225 using ChildIteratorType
= LazyCallGraph::EdgeSequence::iterator
;
1227 static NodeRef
getEntryNode(NodeRef N
) { return N
; }
1228 static ChildIteratorType
child_begin(NodeRef N
) { return (*N
)->begin(); }
1229 static ChildIteratorType
child_end(NodeRef N
) { return (*N
)->end(); }
1231 template <> struct GraphTraits
<LazyCallGraph
*> {
1232 using NodeRef
= LazyCallGraph::Node
*;
1233 using ChildIteratorType
= LazyCallGraph::EdgeSequence::iterator
;
1235 static NodeRef
getEntryNode(NodeRef N
) { return N
; }
1236 static ChildIteratorType
child_begin(NodeRef N
) { return (*N
)->begin(); }
1237 static ChildIteratorType
child_end(NodeRef N
) { return (*N
)->end(); }
1240 /// An analysis pass which computes the call graph for a module.
1241 class LazyCallGraphAnalysis
: public AnalysisInfoMixin
<LazyCallGraphAnalysis
> {
1242 friend AnalysisInfoMixin
<LazyCallGraphAnalysis
>;
1244 static AnalysisKey Key
;
1247 /// Inform generic clients of the result type.
1248 using Result
= LazyCallGraph
;
1250 /// Compute the \c LazyCallGraph for the module \c M.
1252 /// This just builds the set of entry points to the call graph. The rest is
1253 /// built lazily as it is walked.
1254 LazyCallGraph
run(Module
&M
, ModuleAnalysisManager
&AM
) {
1255 return LazyCallGraph(M
, AM
.getResult
<TargetLibraryAnalysis
>(M
));
1259 /// A pass which prints the call graph to a \c raw_ostream.
1261 /// This is primarily useful for testing the analysis.
1262 class LazyCallGraphPrinterPass
1263 : public PassInfoMixin
<LazyCallGraphPrinterPass
> {
1267 explicit LazyCallGraphPrinterPass(raw_ostream
&OS
);
1269 PreservedAnalyses
run(Module
&M
, ModuleAnalysisManager
&AM
);
1272 /// A pass which prints the call graph as a DOT file to a \c raw_ostream.
1274 /// This is primarily useful for visualization purposes.
1275 class LazyCallGraphDOTPrinterPass
1276 : public PassInfoMixin
<LazyCallGraphDOTPrinterPass
> {
1280 explicit LazyCallGraphDOTPrinterPass(raw_ostream
&OS
);
1282 PreservedAnalyses
run(Module
&M
, ModuleAnalysisManager
&AM
);
1285 } // end namespace llvm
1287 #endif // LLVM_ANALYSIS_LAZYCALLGRAPH_H