1 //===- LazyCallGraph.h - Analysis of a Module's call graph ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Implements a lazy call graph analysis and related passes for the new pass
14 /// NB: This is *not* a traditional call graph! It is a graph which models both
15 /// the current calls and potential calls. As a consequence there are many
16 /// edges in this call graph that do not correspond to a 'call' or 'invoke'
19 /// The primary use cases of this graph analysis is to facilitate iterating
20 /// across the functions of a module in ways that ensure all callees are
21 /// visited prior to a caller (given any SCC constraints), or vice versa. As
22 /// such is it particularly well suited to organizing CGSCC optimizations such
23 /// as inlining, outlining, argument promotion, etc. That is its primary use
24 /// case and motivates the design. It may not be appropriate for other
25 /// purposes. The use graph of functions or some other conservative analysis of
26 /// call instructions may be interesting for optimizations and subsequent
27 /// analyses which don't work in the context of an overly specified
28 /// potential-call-edge graph.
30 /// To understand the specific rules and nature of this call graph analysis,
31 /// see the documentation of the \c LazyCallGraph below.
33 //===----------------------------------------------------------------------===//
35 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
36 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/iterator.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/Support/Allocator.h"
54 class PreservedAnalyses;
57 /// A lazily constructed view of the call graph of a module.
59 /// With the edges of this graph, the motivating constraint that we are
60 /// attempting to maintain is that function-local optimization, CGSCC-local
61 /// optimizations, and optimizations transforming a pair of functions connected
62 /// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC
63 /// DAG. That is, no optimizations will delete, remove, or add an edge such
64 /// that functions already visited in a bottom-up order of the SCC DAG are no
65 /// longer valid to have visited, or such that functions not yet visited in
66 /// a bottom-up order of the SCC DAG are not required to have already been
69 /// Within this constraint, the desire is to minimize the merge points of the
70 /// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points
71 /// in the SCC DAG, the more independence there is in optimizing within it.
72 /// There is a strong desire to enable parallelization of optimizations over
73 /// the call graph, and both limited fanout and merge points will (artificially
74 /// in some cases) limit the scaling of such an effort.
76 /// To this end, graph represents both direct and any potential resolution to
77 /// an indirect call edge. Another way to think about it is that it represents
78 /// both the direct call edges and any direct call edges that might be formed
79 /// through static optimizations. Specifically, it considers taking the address
80 /// of a function to be an edge in the call graph because this might be
81 /// forwarded to become a direct call by some subsequent function-local
82 /// optimization. The result is that the graph closely follows the use-def
83 /// edges for functions. Walking "up" the graph can be done by looking at all
84 /// of the uses of a function.
86 /// The roots of the call graph are the external functions and functions
87 /// escaped into global variables. Those functions can be called from outside
88 /// of the module or via unknowable means in the IR -- we may not be able to
89 /// form even a potential call edge from a function body which may dynamically
90 /// load the function and call it.
92 /// This analysis still requires updates to remain valid after optimizations
93 /// which could potentially change the set of potential callees. The
94 /// constraints it operates under only make the traversal order remain valid.
96 /// The entire analysis must be re-computed if full interprocedural
97 /// optimizations run at any point. For example, globalopt completely
98 /// invalidates the information in this analysis.
100 /// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish
101 /// it from the existing CallGraph. At some point, it is expected that this
102 /// will be the only call graph and it will be renamed accordingly.
103 class LazyCallGraph {
108 typedef SmallVector<PointerUnion<Function *, Node *>, 4> NodeVectorT;
109 typedef SmallVectorImpl<PointerUnion<Function *, Node *>> NodeVectorImplT;
111 /// A node in the call graph.
113 /// This represents a single node. It's primary roles are to cache the list of
114 /// callees, de-duplicate and provide fast testing of whether a function is
115 /// a callee, and facilitate iteration of child nodes in the graph.
117 friend class LazyCallGraph;
118 friend class LazyCallGraph::SCC;
123 // We provide for the DFS numbering and Tarjan walk lowlink numbers to be
124 // stored directly within the node.
128 mutable NodeVectorT Callees;
129 DenseMap<Function *, size_t> CalleeIndexMap;
131 /// Basic constructor implements the scanning of F into Callees and
133 Node(LazyCallGraph &G, Function &F);
135 /// Internal helper to insert a callee.
136 void insertEdgeInternal(Function &Callee);
138 /// Internal helper to insert a callee.
139 void insertEdgeInternal(Node &CalleeN);
141 /// Internal helper to remove a callee from this node.
142 void removeEdgeInternal(Function &Callee);
145 typedef LazyCallGraph::iterator iterator;
147 Function &getFunction() const { return F; }
149 iterator begin() const {
150 return iterator(*G, Callees.begin(), Callees.end());
152 iterator end() const { return iterator(*G, Callees.end(), Callees.end()); }
154 /// Equality is defined as address equality.
155 bool operator==(const Node &N) const { return this == &N; }
156 bool operator!=(const Node &N) const { return !operator==(N); }
159 /// A lazy iterator used for both the entry nodes and child nodes.
161 /// When this iterator is dereferenced, if not yet available, a function will
162 /// be scanned for "calls" or uses of functions and its child information
163 /// will be constructed. All of these results are accumulated and cached in
166 : public iterator_adaptor_base<iterator, NodeVectorImplT::iterator,
167 std::forward_iterator_tag, Node> {
168 friend class LazyCallGraph;
169 friend class LazyCallGraph::Node;
172 NodeVectorImplT::iterator E;
174 // Build the iterator for a specific position in a node list.
175 iterator(LazyCallGraph &G, NodeVectorImplT::iterator NI,
176 NodeVectorImplT::iterator E)
177 : iterator_adaptor_base(NI), G(&G), E(E) {
178 while (I != E && I->isNull())
185 using iterator_adaptor_base::operator++;
186 iterator &operator++() {
189 } while (I != E && I->isNull());
193 reference operator*() const {
195 return *I->get<Node *>();
197 Function *F = I->get<Function *>();
198 Node &ChildN = G->get(*F);
204 /// An SCC of the call graph.
206 /// This represents a Strongly Connected Component of the call graph as
207 /// a collection of call graph nodes. While the order of nodes in the SCC is
208 /// stable, it is not any particular order.
210 friend class LazyCallGraph;
211 friend class LazyCallGraph::Node;
214 SmallPtrSet<SCC *, 1> ParentSCCs;
215 SmallVector<Node *, 1> Nodes;
217 SCC(LazyCallGraph &G) : G(&G) {}
219 void insert(Node &N);
222 internalDFS(SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack,
223 SmallVectorImpl<Node *> &PendingSCCStack, Node *N,
224 SmallVectorImpl<SCC *> &ResultSCCs);
227 typedef SmallVectorImpl<Node *>::const_iterator iterator;
228 typedef pointee_iterator<SmallPtrSet<SCC *, 1>::const_iterator>
231 iterator begin() const { return Nodes.begin(); }
232 iterator end() const { return Nodes.end(); }
234 parent_iterator parent_begin() const { return ParentSCCs.begin(); }
235 parent_iterator parent_end() const { return ParentSCCs.end(); }
237 iterator_range<parent_iterator> parents() const {
238 return make_range(parent_begin(), parent_end());
241 /// Test if this SCC is a parent of \a C.
242 bool isParentOf(const SCC &C) const { return C.isChildOf(*this); }
244 /// Test if this SCC is an ancestor of \a C.
245 bool isAncestorOf(const SCC &C) const { return C.isDescendantOf(*this); }
247 /// Test if this SCC is a child of \a C.
248 bool isChildOf(const SCC &C) const {
249 return ParentSCCs.count(const_cast<SCC *>(&C));
252 /// Test if this SCC is a descendant of \a C.
253 bool isDescendantOf(const SCC &C) const;
255 /// Short name useful for debugging or logging.
257 /// We use the name of the first function in the SCC to name the SCC for
258 /// the purposes of debugging and logging.
259 StringRef getName() const { return (*begin())->getFunction().getName(); }
262 /// \name Mutation API
264 /// These methods provide the core API for updating the call graph in the
265 /// presence of a (potentially still in-flight) DFS-found SCCs.
267 /// Note that these methods sometimes have complex runtimes, so be careful
268 /// how you call them.
270 /// Insert an edge from one node in this SCC to another in this SCC.
272 /// By the definition of an SCC, this does not change the nature or make-up
274 void insertIntraSCCEdge(Node &CallerN, Node &CalleeN);
276 /// Insert an edge whose tail is in this SCC and head is in some child SCC.
278 /// There must be an existing path from the caller to the callee. This
279 /// operation is inexpensive and does not change the set of SCCs in the
281 void insertOutgoingEdge(Node &CallerN, Node &CalleeN);
283 /// Insert an edge whose tail is in a descendant SCC and head is in this
286 /// There must be an existing path from the callee to the caller in this
287 /// case. NB! This is has the potential to be a very expensive function. It
288 /// inherently forms a cycle in the prior SCC DAG and we have to merge SCCs
289 /// to resolve that cycle. But finding all of the SCCs which participate in
290 /// the cycle can in the worst case require traversing every SCC in the
291 /// graph. Every attempt is made to avoid that, but passes must still
292 /// exercise caution calling this routine repeatedly.
294 /// FIXME: We could possibly optimize this quite a bit for cases where the
295 /// caller and callee are very nearby in the graph. See comments in the
296 /// implementation for details, but that use case might impact users.
297 SmallVector<SCC *, 1> insertIncomingEdge(Node &CallerN, Node &CalleeN);
299 /// Remove an edge whose source is in this SCC and target is *not*.
301 /// This removes an inter-SCC edge. All inter-SCC edges originating from
302 /// this SCC have been fully explored by any in-flight DFS SCC formation,
303 /// so this is always safe to call once you have the source SCC.
305 /// This operation does not change the set of SCCs or the members of the
306 /// SCCs and so is very inexpensive. It may change the connectivity graph
307 /// of the SCCs though, so be careful calling this while iterating over
309 void removeInterSCCEdge(Node &CallerN, Node &CalleeN);
311 /// Remove an edge which is entirely within this SCC.
313 /// Both the \a Caller and the \a Callee must be within this SCC. Removing
314 /// such an edge make break cycles that form this SCC and thus this
315 /// operation may change the SCC graph significantly. In particular, this
316 /// operation will re-form new SCCs based on the remaining connectivity of
317 /// the graph. The following invariants are guaranteed to hold after
318 /// calling this method:
320 /// 1) This SCC is still an SCC in the graph.
321 /// 2) This SCC will be the parent of any new SCCs. Thus, this SCC is
322 /// preserved as the root of any new SCC directed graph formed.
323 /// 3) No SCC other than this SCC has its member set changed (this is
324 /// inherent in the definition of removing such an edge).
325 /// 4) All of the parent links of the SCC graph will be updated to reflect
326 /// the new SCC structure.
327 /// 5) All SCCs formed out of this SCC, excluding this SCC, will be
328 /// returned in a vector.
329 /// 6) The order of the SCCs in the vector will be a valid postorder
330 /// traversal of the new SCCs.
332 /// These invariants are very important to ensure that we can build
333 /// optimization pipeliens on top of the CGSCC pass manager which
334 /// intelligently update the SCC graph without invalidating other parts of
337 /// The runtime complexity of this method is, in the worst case, O(V+E)
338 /// where V is the number of nodes in this SCC and E is the number of edges
339 /// leaving the nodes in this SCC. Note that E includes both edges within
340 /// this SCC and edges from this SCC to child SCCs. Some effort has been
341 /// made to minimize the overhead of common cases such as self-edges and
342 /// edge removals which result in a spanning tree with no more cycles.
343 SmallVector<SCC *, 1> removeIntraSCCEdge(Node &CallerN, Node &CalleeN);
348 /// A post-order depth-first SCC iterator over the call graph.
350 /// This iterator triggers the Tarjan DFS-based formation of the SCC DAG for
351 /// the call graph, walking it lazily in depth-first post-order. That is, it
352 /// always visits SCCs for a callee prior to visiting the SCC for a caller
353 /// (when they are in different SCCs).
354 class postorder_scc_iterator
355 : public iterator_facade_base<postorder_scc_iterator,
356 std::forward_iterator_tag, SCC> {
357 friend class LazyCallGraph;
358 friend class LazyCallGraph::Node;
360 /// Nonce type to select the constructor for the end iterator.
366 // Build the begin iterator for a node.
367 postorder_scc_iterator(LazyCallGraph &G) : G(&G) {
368 C = G.getNextSCCInPostOrder();
371 // Build the end iterator for a node. This is selected purely by overload.
372 postorder_scc_iterator(LazyCallGraph &G, IsAtEndT /*Nonce*/)
373 : G(&G), C(nullptr) {}
376 bool operator==(const postorder_scc_iterator &Arg) const {
377 return G == Arg.G && C == Arg.C;
380 reference operator*() const { return *C; }
382 using iterator_facade_base::operator++;
383 postorder_scc_iterator &operator++() {
384 C = G->getNextSCCInPostOrder();
389 /// Construct a graph for the given module.
391 /// This sets up the graph and computes all of the entry points of the graph.
392 /// No function definitions are scanned until their nodes in the graph are
393 /// requested during traversal.
394 LazyCallGraph(Module &M);
396 LazyCallGraph(LazyCallGraph &&G);
397 LazyCallGraph &operator=(LazyCallGraph &&RHS);
400 return iterator(*this, EntryNodes.begin(), EntryNodes.end());
402 iterator end() { return iterator(*this, EntryNodes.end(), EntryNodes.end()); }
404 postorder_scc_iterator postorder_scc_begin() {
405 return postorder_scc_iterator(*this);
407 postorder_scc_iterator postorder_scc_end() {
408 return postorder_scc_iterator(*this, postorder_scc_iterator::IsAtEndT());
411 iterator_range<postorder_scc_iterator> postorder_sccs() {
412 return make_range(postorder_scc_begin(), postorder_scc_end());
415 /// Lookup a function in the graph which has already been scanned and added.
416 Node *lookup(const Function &F) const { return NodeMap.lookup(&F); }
418 /// Lookup a function's SCC in the graph.
420 /// \returns null if the function hasn't been assigned an SCC via the SCC
422 SCC *lookupSCC(Node &N) const { return SCCMap.lookup(&N); }
424 /// Get a graph node for a given function, scanning it to populate the graph
425 /// data as necessary.
426 Node &get(Function &F) {
427 Node *&N = NodeMap[&F];
431 return insertInto(F, N);
435 /// \name Pre-SCC Mutation API
437 /// These methods are only valid to call prior to forming any SCCs for this
438 /// call graph. They can be used to update the core node-graph during
439 /// a node-based inorder traversal that precedes any SCC-based traversal.
441 /// Once you begin manipulating a call graph's SCCs, you must perform all
442 /// mutation of the graph via the SCC methods.
444 /// Update the call graph after inserting a new edge.
445 void insertEdge(Node &Caller, Function &Callee);
447 /// Update the call graph after inserting a new edge.
448 void insertEdge(Function &Caller, Function &Callee) {
449 return insertEdge(get(Caller), Callee);
452 /// Update the call graph after deleting an edge.
453 void removeEdge(Node &Caller, Function &Callee);
455 /// Update the call graph after deleting an edge.
456 void removeEdge(Function &Caller, Function &Callee) {
457 return removeEdge(get(Caller), Callee);
463 /// Allocator that holds all the call graph nodes.
464 SpecificBumpPtrAllocator<Node> BPA;
466 /// Maps function->node for fast lookup.
467 DenseMap<const Function *, Node *> NodeMap;
469 /// The entry nodes to the graph.
471 /// These nodes are reachable through "external" means. Put another way, they
472 /// escape at the module scope.
473 NodeVectorT EntryNodes;
475 /// Map of the entry nodes in the graph to their indices in \c EntryNodes.
476 DenseMap<Function *, size_t> EntryIndexMap;
478 /// Allocator that holds all the call graph SCCs.
479 SpecificBumpPtrAllocator<SCC> SCCBPA;
481 /// Maps Function -> SCC for fast lookup.
482 DenseMap<Node *, SCC *> SCCMap;
484 /// The leaf SCCs of the graph.
486 /// These are all of the SCCs which have no children.
487 SmallVector<SCC *, 4> LeafSCCs;
489 /// Stack of nodes in the DFS walk.
490 SmallVector<std::pair<Node *, iterator>, 4> DFSStack;
492 /// Set of entry nodes not-yet-processed into SCCs.
493 SmallVector<Function *, 4> SCCEntryNodes;
495 /// Stack of nodes the DFS has walked but not yet put into a SCC.
496 SmallVector<Node *, 4> PendingSCCStack;
498 /// Counter for the next DFS number to assign.
501 /// Helper to insert a new function, with an already looked-up entry in
503 Node &insertInto(Function &F, Node *&MappedN);
505 /// Helper to update pointers back to the graph object during moves.
506 void updateGraphPtrs();
508 /// Helper to form a new SCC out of the top of a DFSStack-like
510 SCC *formSCC(Node *RootN, SmallVectorImpl<Node *> &NodeStack);
512 /// Retrieve the next node in the post-order SCC walk of the call graph.
513 SCC *getNextSCCInPostOrder();
516 // Provide GraphTraits specializations for call graphs.
517 template <> struct GraphTraits<LazyCallGraph::Node *> {
518 typedef LazyCallGraph::Node NodeType;
519 typedef LazyCallGraph::iterator ChildIteratorType;
521 static NodeType *getEntryNode(NodeType *N) { return N; }
522 static ChildIteratorType child_begin(NodeType *N) { return N->begin(); }
523 static ChildIteratorType child_end(NodeType *N) { return N->end(); }
525 template <> struct GraphTraits<LazyCallGraph *> {
526 typedef LazyCallGraph::Node NodeType;
527 typedef LazyCallGraph::iterator ChildIteratorType;
529 static NodeType *getEntryNode(NodeType *N) { return N; }
530 static ChildIteratorType child_begin(NodeType *N) { return N->begin(); }
531 static ChildIteratorType child_end(NodeType *N) { return N->end(); }
534 /// An analysis pass which computes the call graph for a module.
535 class LazyCallGraphAnalysis {
537 /// Inform generic clients of the result type.
538 typedef LazyCallGraph Result;
540 static void *ID() { return (void *)&PassID; }
542 static StringRef name() { return "Lazy CallGraph Analysis"; }
544 /// Compute the \c LazyCallGraph for the module \c M.
546 /// This just builds the set of entry points to the call graph. The rest is
547 /// built lazily as it is walked.
548 LazyCallGraph run(Module &M) { return LazyCallGraph(M); }
554 /// A pass which prints the call graph to a \c raw_ostream.
556 /// This is primarily useful for testing the analysis.
557 class LazyCallGraphPrinterPass {
561 explicit LazyCallGraphPrinterPass(raw_ostream &OS);
563 PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM);
565 static StringRef name() { return "LazyCallGraphPrinterPass"; }