xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Analysis/CGSCCPassManager.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===- CGSCCPassManager.h - Call graph pass management ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// This header provides classes for managing passes over SCCs of the call
11 /// graph. These passes form an important component of LLVM's interprocedural
12 /// optimizations. Because they operate on the SCCs of the call graph, and they
13 /// traverse the graph in post-order, they can effectively do pair-wise
14 /// interprocedural optimizations for all call edges in the program while
15 /// incrementally refining it and improving the context of these pair-wise
16 /// optimizations. At each call site edge, the callee has already been
17 /// optimized as much as is possible. This in turn allows very accurate
18 /// analysis of it for IPO.
19 ///
20 /// A secondary more general goal is to be able to isolate optimization on
21 /// unrelated parts of the IR module. This is useful to ensure our
22 /// optimizations are principled and don't miss oportunities where refinement
23 /// of one part of the module influences transformations in another part of the
24 /// module. But this is also useful if we want to parallelize the optimizations
25 /// across common large module graph shapes which tend to be very wide and have
26 /// large regions of unrelated cliques.
27 ///
28 /// To satisfy these goals, we use the LazyCallGraph which provides two graphs
29 /// nested inside each other (and built lazily from the bottom-up): the call
30 /// graph proper, and a reference graph. The reference graph is super set of
31 /// the call graph and is a conservative approximation of what could through
32 /// scalar or CGSCC transforms *become* the call graph. Using this allows us to
33 /// ensure we optimize functions prior to them being introduced into the call
34 /// graph by devirtualization or other technique, and thus ensures that
35 /// subsequent pair-wise interprocedural optimizations observe the optimized
36 /// form of these functions. The (potentially transitive) reference
37 /// reachability used by the reference graph is a conservative approximation
38 /// that still allows us to have independent regions of the graph.
39 ///
40 /// FIXME: There is one major drawback of the reference graph: in its naive
41 /// form it is quadratic because it contains a distinct edge for each
42 /// (potentially indirect) reference, even if are all through some common
43 /// global table of function pointers. This can be fixed in a number of ways
44 /// that essentially preserve enough of the normalization. While it isn't
45 /// expected to completely preclude the usability of this, it will need to be
46 /// addressed.
47 ///
48 ///
49 /// All of these issues are made substantially more complex in the face of
50 /// mutations to the call graph while optimization passes are being run. When
51 /// mutations to the call graph occur we want to achieve two different things:
52 ///
53 /// - We need to update the call graph in-flight and invalidate analyses
54 ///   cached on entities in the graph. Because of the cache-based analysis
55 ///   design of the pass manager, it is essential to have stable identities for
56 ///   the elements of the IR that passes traverse, and to invalidate any
57 ///   analyses cached on these elements as the mutations take place.
58 ///
59 /// - We want to preserve the incremental and post-order traversal of the
60 ///   graph even as it is refined and mutated. This means we want optimization
61 ///   to observe the most refined form of the call graph and to do so in
62 ///   post-order.
63 ///
64 /// To address this, the CGSCC manager uses both worklists that can be expanded
65 /// by passes which transform the IR, and provides invalidation tests to skip
66 /// entries that become dead. This extra data is provided to every SCC pass so
67 /// that it can carefully update the manager's traversal as the call graph
68 /// mutates.
69 ///
70 /// We also provide support for running function passes within the CGSCC walk,
71 /// and there we provide automatic update of the call graph including of the
72 /// pass manager to reflect call graph changes that fall out naturally as part
73 /// of scalar transformations.
74 ///
75 /// The patterns used to ensure the goals of post-order visitation of the fully
76 /// refined graph:
77 ///
78 /// 1) Sink toward the "bottom" as the graph is refined. This means that any
79 ///    iteration continues in some valid post-order sequence after the mutation
80 ///    has altered the structure.
81 ///
82 /// 2) Enqueue in post-order, including the current entity. If the current
83 ///    entity's shape changes, it and everything after it in post-order needs
84 ///    to be visited to observe that shape.
85 ///
86 //===----------------------------------------------------------------------===//
87 
88 #ifndef LLVM_ANALYSIS_CGSCCPASSMANAGER_H
89 #define LLVM_ANALYSIS_CGSCCPASSMANAGER_H
90 
91 #include "llvm/ADT/MapVector.h"
92 #include "llvm/Analysis/LazyCallGraph.h"
93 #include "llvm/IR/PassManager.h"
94 #include "llvm/IR/ValueHandle.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include <cassert>
98 #include <utility>
99 
100 namespace llvm {
101 
102 class Function;
103 template <typename T, unsigned int N> class SmallPriorityWorklist;
104 struct CGSCCUpdateResult;
105 
106 class Module;
107 
108 // Allow debug logging in this inline function.
109 #define DEBUG_TYPE "cgscc"
110 
111 /// Extern template declaration for the analysis set for this IR unit.
112 extern template class LLVM_TEMPLATE_ABI AllAnalysesOn<LazyCallGraph::SCC>;
113 
114 extern template class LLVM_TEMPLATE_ABI
115     AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
116 
117 /// The CGSCC analysis manager.
118 ///
119 /// See the documentation for the AnalysisManager template for detail
120 /// documentation. This type serves as a convenient way to refer to this
121 /// construct in the adaptors and proxies used to integrate this into the larger
122 /// pass manager infrastructure.
123 using CGSCCAnalysisManager =
124     AnalysisManager<LazyCallGraph::SCC, LazyCallGraph &>;
125 
126 // Explicit specialization and instantiation declarations for the pass manager.
127 // See the comments on the definition of the specialization for details on how
128 // it differs from the primary template.
129 template <>
130 LLVM_ABI PreservedAnalyses
131 PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
132             CGSCCUpdateResult &>::run(LazyCallGraph::SCC &InitialC,
133                                       CGSCCAnalysisManager &AM,
134                                       LazyCallGraph &G, CGSCCUpdateResult &UR);
135 extern template class PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager,
136                                   LazyCallGraph &, CGSCCUpdateResult &>;
137 
138 /// The CGSCC pass manager.
139 ///
140 /// See the documentation for the PassManager template for details. It runs
141 /// a sequence of SCC passes over each SCC that the manager is run over. This
142 /// type serves as a convenient way to refer to this construct.
143 using CGSCCPassManager =
144     PassManager<LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,
145                 CGSCCUpdateResult &>;
146 
147 /// An explicit specialization of the require analysis template pass.
148 template <typename AnalysisT>
149 struct RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC, CGSCCAnalysisManager,
150                            LazyCallGraph &, CGSCCUpdateResult &>
151     : PassInfoMixin<RequireAnalysisPass<AnalysisT, LazyCallGraph::SCC,
152                                         CGSCCAnalysisManager, LazyCallGraph &,
153                                         CGSCCUpdateResult &>> {
154   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
155                         LazyCallGraph &CG, CGSCCUpdateResult &) {
156     (void)AM.template getResult<AnalysisT>(C, CG);
157     return PreservedAnalyses::all();
158   }
159   void printPipeline(raw_ostream &OS,
160                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
161     auto ClassName = AnalysisT::name();
162     auto PassName = MapClassName2PassName(ClassName);
163     OS << "require<" << PassName << '>';
164   }
165 };
166 
167 /// A proxy from a \c CGSCCAnalysisManager to a \c Module.
168 using CGSCCAnalysisManagerModuleProxy =
169     InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
170 
171 /// We need a specialized result for the \c CGSCCAnalysisManagerModuleProxy so
172 /// it can have access to the call graph in order to walk all the SCCs when
173 /// invalidating things.
174 template <> class CGSCCAnalysisManagerModuleProxy::Result {
175 public:
176   explicit Result(CGSCCAnalysisManager &InnerAM, LazyCallGraph &G)
177       : InnerAM(&InnerAM), G(&G) {}
178 
179   /// Accessor for the analysis manager.
180   CGSCCAnalysisManager &getManager() { return *InnerAM; }
181 
182   /// Handler for invalidation of the Module.
183   ///
184   /// If the proxy analysis itself is preserved, then we assume that the set of
185   /// SCCs in the Module hasn't changed. Thus any pointers to SCCs in the
186   /// CGSCCAnalysisManager are still valid, and we don't need to call \c clear
187   /// on the CGSCCAnalysisManager.
188   ///
189   /// Regardless of whether this analysis is marked as preserved, all of the
190   /// analyses in the \c CGSCCAnalysisManager are potentially invalidated based
191   /// on the set of preserved analyses.
192   LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA,
193                            ModuleAnalysisManager::Invalidator &Inv);
194 
195 private:
196   CGSCCAnalysisManager *InnerAM;
197   LazyCallGraph *G;
198 };
199 
200 /// Provide a specialized run method for the \c CGSCCAnalysisManagerModuleProxy
201 /// so it can pass the lazy call graph to the result.
202 template <>
203 LLVM_ABI CGSCCAnalysisManagerModuleProxy::Result
204 CGSCCAnalysisManagerModuleProxy::run(Module &M, ModuleAnalysisManager &AM);
205 
206 // Ensure the \c CGSCCAnalysisManagerModuleProxy is provided as an extern
207 // template.
208 extern template class InnerAnalysisManagerProxy<CGSCCAnalysisManager, Module>;
209 
210 extern template class LLVM_TEMPLATE_ABI OuterAnalysisManagerProxy<
211     ModuleAnalysisManager, LazyCallGraph::SCC, LazyCallGraph &>;
212 
213 /// A proxy from a \c ModuleAnalysisManager to an \c SCC.
214 using ModuleAnalysisManagerCGSCCProxy =
215     OuterAnalysisManagerProxy<ModuleAnalysisManager, LazyCallGraph::SCC,
216                               LazyCallGraph &>;
217 
218 /// Support structure for SCC passes to communicate updates the call graph back
219 /// to the CGSCC pass manager infrastructure.
220 ///
221 /// The CGSCC pass manager runs SCC passes which are allowed to update the call
222 /// graph and SCC structures. This means the structure the pass manager works
223 /// on is mutating underneath it. In order to support that, there needs to be
224 /// careful communication about the precise nature and ramifications of these
225 /// updates to the pass management infrastructure.
226 ///
227 /// All SCC passes will have to accept a reference to the management layer's
228 /// update result struct and use it to reflect the results of any CG updates
229 /// performed.
230 ///
231 /// Passes which do not change the call graph structure in any way can just
232 /// ignore this argument to their run method.
233 struct CGSCCUpdateResult {
234   /// Worklist of the SCCs queued for processing.
235   ///
236   /// When a pass refines the graph and creates new SCCs or causes them to have
237   /// a different shape or set of component functions it should add the SCCs to
238   /// this worklist so that we visit them in the refined form.
239   ///
240   /// Note that if the SCCs are part of a RefSCC that is added to the \c
241   /// RCWorklist, they don't need to be added here as visiting the RefSCC will
242   /// be sufficient to re-visit the SCCs within it.
243   ///
244   /// This worklist is in reverse post-order, as we pop off the back in order
245   /// to observe SCCs in post-order. When adding SCCs, clients should add them
246   /// in reverse post-order.
247   SmallPriorityWorklist<LazyCallGraph::SCC *, 1> &CWorklist;
248 
249   /// The set of invalidated SCCs which should be skipped if they are found
250   /// in \c CWorklist.
251   ///
252   /// This is used to quickly prune out SCCs when they get deleted and happen
253   /// to already be on the worklist. We use this primarily to avoid scanning
254   /// the list and removing entries from it.
255   SmallPtrSetImpl<LazyCallGraph::SCC *> &InvalidatedSCCs;
256 
257   /// If non-null, the updated current \c SCC being processed.
258   ///
259   /// This is set when a graph refinement takes place and the "current" point
260   /// in the graph moves "down" or earlier in the post-order walk. This will
261   /// often cause the "current" SCC to be a newly created SCC object and the
262   /// old one to be added to the above worklist. When that happens, this
263   /// pointer is non-null and can be used to continue processing the "top" of
264   /// the post-order walk.
265   LazyCallGraph::SCC *UpdatedC;
266 
267   /// Preserved analyses across SCCs.
268   ///
269   /// We specifically want to allow CGSCC passes to mutate ancestor IR
270   /// (changing both the CG structure and the function IR itself). However,
271   /// this means we need to take special care to correctly mark what analyses
272   /// are preserved *across* SCCs. We have to track this out-of-band here
273   /// because within the main `PassManager` infrastructure we need to mark
274   /// everything within an SCC as preserved in order to avoid repeatedly
275   /// invalidating the same analyses as we unnest pass managers and adaptors.
276   /// So we track the cross-SCC version of the preserved analyses here from any
277   /// code that does direct invalidation of SCC analyses, and then use it
278   /// whenever we move forward in the post-order walk of SCCs before running
279   /// passes over the new SCC.
280   PreservedAnalyses CrossSCCPA;
281 
282   /// A hacky area where the inliner can retain history about inlining
283   /// decisions that mutated the call graph's SCC structure in order to avoid
284   /// infinite inlining. See the comments in the inliner's CG update logic.
285   ///
286   /// FIXME: Keeping this here seems like a big layering issue, we should look
287   /// for a better technique.
288   SmallDenseSet<std::pair<LazyCallGraph::Node *, LazyCallGraph::SCC *>, 4>
289       &InlinedInternalEdges;
290 
291   /// Functions that a pass has considered to be dead to be removed at the end
292   /// of the call graph walk in batch.
293   SmallVector<Function *, 4> &DeadFunctions;
294 
295   /// Weak VHs to keep track of indirect calls for the purposes of detecting
296   /// devirtualization.
297   ///
298   /// This is a map to avoid having duplicate entries. If a Value is
299   /// deallocated, its corresponding WeakTrackingVH will be nulled out. When
300   /// checking if a Value is in the map or not, also check if the corresponding
301   /// WeakTrackingVH is null to avoid issues with a new Value sharing the same
302   /// address as a deallocated one.
303   SmallMapVector<Value *, WeakTrackingVH, 16> IndirectVHs;
304 };
305 
306 /// The core module pass which does a post-order walk of the SCCs and
307 /// runs a CGSCC pass over each one.
308 ///
309 /// Designed to allow composition of a CGSCCPass(Manager) and
310 /// a ModulePassManager. Note that this pass must be run with a module analysis
311 /// manager as it uses the LazyCallGraph analysis. It will also run the
312 /// \c CGSCCAnalysisManagerModuleProxy analysis prior to running the CGSCC
313 /// pass over the module to enable a \c FunctionAnalysisManager to be used
314 /// within this run safely.
315 class ModuleToPostOrderCGSCCPassAdaptor
316     : public PassInfoMixin<ModuleToPostOrderCGSCCPassAdaptor> {
317 public:
318   using PassConceptT =
319       detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
320                           LazyCallGraph &, CGSCCUpdateResult &>;
321 
322   explicit ModuleToPostOrderCGSCCPassAdaptor(std::unique_ptr<PassConceptT> Pass)
323       : Pass(std::move(Pass)) {}
324 
325   ModuleToPostOrderCGSCCPassAdaptor(ModuleToPostOrderCGSCCPassAdaptor &&Arg)
326       : Pass(std::move(Arg.Pass)) {}
327 
328   friend void swap(ModuleToPostOrderCGSCCPassAdaptor &LHS,
329                    ModuleToPostOrderCGSCCPassAdaptor &RHS) {
330     std::swap(LHS.Pass, RHS.Pass);
331   }
332 
333   ModuleToPostOrderCGSCCPassAdaptor &
334   operator=(ModuleToPostOrderCGSCCPassAdaptor RHS) {
335     swap(*this, RHS);
336     return *this;
337   }
338 
339   /// Runs the CGSCC pass across every SCC in the module.
340   LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM);
341 
342   void printPipeline(raw_ostream &OS,
343                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
344     OS << "cgscc(";
345     Pass->printPipeline(OS, MapClassName2PassName);
346     OS << ')';
347   }
348 
349   static bool isRequired() { return true; }
350 
351 private:
352   std::unique_ptr<PassConceptT> Pass;
353 };
354 
355 /// A function to deduce a function pass type and wrap it in the
356 /// templated adaptor.
357 template <typename CGSCCPassT>
358 ModuleToPostOrderCGSCCPassAdaptor
359 createModuleToPostOrderCGSCCPassAdaptor(CGSCCPassT &&Pass) {
360   using PassModelT =
361       detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
362                         LazyCallGraph &, CGSCCUpdateResult &>;
363   // Do not use make_unique, it causes too many template instantiations,
364   // causing terrible compile times.
365   return ModuleToPostOrderCGSCCPassAdaptor(
366       std::unique_ptr<ModuleToPostOrderCGSCCPassAdaptor::PassConceptT>(
367           new PassModelT(std::forward<CGSCCPassT>(Pass))));
368 }
369 
370 /// A proxy from a \c FunctionAnalysisManager to an \c SCC.
371 ///
372 /// When a module pass runs and triggers invalidation, both the CGSCC and
373 /// Function analysis manager proxies on the module get an invalidation event.
374 /// We don't want to fully duplicate responsibility for most of the
375 /// invalidation logic. Instead, this layer is only responsible for SCC-local
376 /// invalidation events. We work with the module's FunctionAnalysisManager to
377 /// invalidate function analyses.
378 class FunctionAnalysisManagerCGSCCProxy
379     : public AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy> {
380 public:
381   class Result {
382   public:
383     explicit Result() : FAM(nullptr) {}
384     explicit Result(FunctionAnalysisManager &FAM) : FAM(&FAM) {}
385 
386     void updateFAM(FunctionAnalysisManager &FAM) { this->FAM = &FAM; }
387     /// Accessor for the analysis manager.
388     FunctionAnalysisManager &getManager() {
389       assert(FAM);
390       return *FAM;
391     }
392 
393     LLVM_ABI bool invalidate(LazyCallGraph::SCC &C, const PreservedAnalyses &PA,
394                              CGSCCAnalysisManager::Invalidator &Inv);
395 
396   private:
397     FunctionAnalysisManager *FAM;
398   };
399 
400   /// Computes the \c FunctionAnalysisManager and stores it in the result proxy.
401   LLVM_ABI Result run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &AM,
402                       LazyCallGraph &);
403 
404 private:
405   friend AnalysisInfoMixin<FunctionAnalysisManagerCGSCCProxy>;
406 
407   LLVM_ABI static AnalysisKey Key;
408 };
409 
410 extern template class LLVM_TEMPLATE_ABI
411     OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
412 
413 /// A proxy from a \c CGSCCAnalysisManager to a \c Function.
414 using CGSCCAnalysisManagerFunctionProxy =
415     OuterAnalysisManagerProxy<CGSCCAnalysisManager, Function>;
416 
417 /// Helper to update the call graph after running a function pass.
418 ///
419 /// Function passes can only mutate the call graph in specific ways. This
420 /// routine provides a helper that updates the call graph in those ways
421 /// including returning whether any changes were made and populating a CG
422 /// update result struct for the overall CGSCC walk.
423 LLVM_ABI LazyCallGraph::SCC &updateCGAndAnalysisManagerForFunctionPass(
424     LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
425     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
426     FunctionAnalysisManager &FAM);
427 
428 /// Helper to update the call graph after running a CGSCC pass.
429 ///
430 /// CGSCC passes can only mutate the call graph in specific ways. This
431 /// routine provides a helper that updates the call graph in those ways
432 /// including returning whether any changes were made and populating a CG
433 /// update result struct for the overall CGSCC walk.
434 LLVM_ABI LazyCallGraph::SCC &updateCGAndAnalysisManagerForCGSCCPass(
435     LazyCallGraph &G, LazyCallGraph::SCC &C, LazyCallGraph::Node &N,
436     CGSCCAnalysisManager &AM, CGSCCUpdateResult &UR,
437     FunctionAnalysisManager &FAM);
438 
439 /// Adaptor that maps from a SCC to its functions.
440 ///
441 /// Designed to allow composition of a FunctionPass(Manager) and
442 /// a CGSCCPassManager. Note that if this pass is constructed with a pointer
443 /// to a \c CGSCCAnalysisManager it will run the
444 /// \c FunctionAnalysisManagerCGSCCProxy analysis prior to running the function
445 /// pass over the SCC to enable a \c FunctionAnalysisManager to be used
446 /// within this run safely.
447 class CGSCCToFunctionPassAdaptor
448     : public PassInfoMixin<CGSCCToFunctionPassAdaptor> {
449 public:
450   using PassConceptT = detail::PassConcept<Function, FunctionAnalysisManager>;
451 
452   explicit CGSCCToFunctionPassAdaptor(std::unique_ptr<PassConceptT> Pass,
453                                       bool EagerlyInvalidate, bool NoRerun)
454       : Pass(std::move(Pass)), EagerlyInvalidate(EagerlyInvalidate),
455         NoRerun(NoRerun) {}
456 
457   CGSCCToFunctionPassAdaptor(CGSCCToFunctionPassAdaptor &&Arg)
458       : Pass(std::move(Arg.Pass)), EagerlyInvalidate(Arg.EagerlyInvalidate),
459         NoRerun(Arg.NoRerun) {}
460 
461   friend void swap(CGSCCToFunctionPassAdaptor &LHS,
462                    CGSCCToFunctionPassAdaptor &RHS) {
463     std::swap(LHS.Pass, RHS.Pass);
464   }
465 
466   CGSCCToFunctionPassAdaptor &operator=(CGSCCToFunctionPassAdaptor RHS) {
467     swap(*this, RHS);
468     return *this;
469   }
470 
471   /// Runs the function pass across every function in the module.
472   LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &C,
473                                  CGSCCAnalysisManager &AM, LazyCallGraph &CG,
474                                  CGSCCUpdateResult &UR);
475 
476   void printPipeline(raw_ostream &OS,
477                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
478     OS << "function";
479     if (EagerlyInvalidate || NoRerun) {
480       OS << "<";
481       if (EagerlyInvalidate)
482         OS << "eager-inv";
483       if (EagerlyInvalidate && NoRerun)
484         OS << ";";
485       if (NoRerun)
486         OS << "no-rerun";
487       OS << ">";
488     }
489     OS << '(';
490     Pass->printPipeline(OS, MapClassName2PassName);
491     OS << ')';
492   }
493 
494   static bool isRequired() { return true; }
495 
496 private:
497   std::unique_ptr<PassConceptT> Pass;
498   bool EagerlyInvalidate;
499   bool NoRerun;
500 };
501 
502 /// A function to deduce a function pass type and wrap it in the
503 /// templated adaptor.
504 template <typename FunctionPassT>
505 CGSCCToFunctionPassAdaptor
506 createCGSCCToFunctionPassAdaptor(FunctionPassT &&Pass,
507                                  bool EagerlyInvalidate = false,
508                                  bool NoRerun = false) {
509   using PassModelT =
510       detail::PassModel<Function, FunctionPassT, FunctionAnalysisManager>;
511   // Do not use make_unique, it causes too many template instantiations,
512   // causing terrible compile times.
513   return CGSCCToFunctionPassAdaptor(
514       std::unique_ptr<CGSCCToFunctionPassAdaptor::PassConceptT>(
515           new PassModelT(std::forward<FunctionPassT>(Pass))),
516       EagerlyInvalidate, NoRerun);
517 }
518 
519 // A marker to determine if function passes should be run on a function within a
520 // CGSCCToFunctionPassAdaptor. This is used to prevent running an expensive
521 // function pass (manager) on a function multiple times if SCC mutations cause a
522 // function to be visited multiple times and the function is not modified by
523 // other SCC passes.
524 class ShouldNotRunFunctionPassesAnalysis
525     : public AnalysisInfoMixin<ShouldNotRunFunctionPassesAnalysis> {
526 public:
527   LLVM_ABI static AnalysisKey Key;
528   struct Result {};
529 
530   Result run(Function &F, FunctionAnalysisManager &FAM) { return Result(); }
531 };
532 
533 /// A helper that repeats an SCC pass each time an indirect call is refined to
534 /// a direct call by that pass.
535 ///
536 /// While the CGSCC pass manager works to re-visit SCCs and RefSCCs as they
537 /// change shape, we may also want to repeat an SCC pass if it simply refines
538 /// an indirect call to a direct call, even if doing so does not alter the
539 /// shape of the graph. Note that this only pertains to direct calls to
540 /// functions where IPO across the SCC may be able to compute more precise
541 /// results. For intrinsics, we assume scalar optimizations already can fully
542 /// reason about them.
543 ///
544 /// This repetition has the potential to be very large however, as each one
545 /// might refine a single call site. As a consequence, in practice we use an
546 /// upper bound on the number of repetitions to limit things.
547 class DevirtSCCRepeatedPass : public PassInfoMixin<DevirtSCCRepeatedPass> {
548 public:
549   using PassConceptT =
550       detail::PassConcept<LazyCallGraph::SCC, CGSCCAnalysisManager,
551                           LazyCallGraph &, CGSCCUpdateResult &>;
552 
553   explicit DevirtSCCRepeatedPass(std::unique_ptr<PassConceptT> Pass,
554                                  int MaxIterations)
555       : Pass(std::move(Pass)), MaxIterations(MaxIterations) {}
556 
557   /// Runs the wrapped pass up to \c MaxIterations on the SCC, iterating
558   /// whenever an indirect call is refined.
559   LLVM_ABI PreservedAnalyses run(LazyCallGraph::SCC &InitialC,
560                                  CGSCCAnalysisManager &AM, LazyCallGraph &CG,
561                                  CGSCCUpdateResult &UR);
562 
563   void printPipeline(raw_ostream &OS,
564                      function_ref<StringRef(StringRef)> MapClassName2PassName) {
565     OS << "devirt<" << MaxIterations << ">(";
566     Pass->printPipeline(OS, MapClassName2PassName);
567     OS << ')';
568   }
569 
570 private:
571   std::unique_ptr<PassConceptT> Pass;
572   int MaxIterations;
573 };
574 
575 /// A function to deduce a function pass type and wrap it in the
576 /// templated adaptor.
577 template <typename CGSCCPassT>
578 DevirtSCCRepeatedPass createDevirtSCCRepeatedPass(CGSCCPassT &&Pass,
579                                                   int MaxIterations) {
580   using PassModelT =
581       detail::PassModel<LazyCallGraph::SCC, CGSCCPassT, CGSCCAnalysisManager,
582                         LazyCallGraph &, CGSCCUpdateResult &>;
583   // Do not use make_unique, it causes too many template instantiations,
584   // causing terrible compile times.
585   return DevirtSCCRepeatedPass(
586       std::unique_ptr<DevirtSCCRepeatedPass::PassConceptT>(
587           new PassModelT(std::forward<CGSCCPassT>(Pass))),
588       MaxIterations);
589 }
590 
591 // Clear out the debug logging macro.
592 #undef DEBUG_TYPE
593 
594 } // end namespace llvm
595 
596 #endif // LLVM_ANALYSIS_CGSCCPASSMANAGER_H
597