Home | History | Annotate | Download | only in Passes
      1 //===- Parsing, selection, and construction of pass pipelines --*- C++ -*--===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 /// \file
     10 ///
     11 /// Interfaces for registering analysis passes, producing common pass manager
     12 /// configurations, and parsing of pass pipelines.
     13 ///
     14 //===----------------------------------------------------------------------===//
     15 
     16 #ifndef LLVM_PASSES_PASSBUILDER_H
     17 #define LLVM_PASSES_PASSBUILDER_H
     18 
     19 #include "llvm/ADT/Optional.h"
     20 #include "llvm/Analysis/CGSCCPassManager.h"
     21 #include "llvm/IR/PassManager.h"
     22 #include "llvm/Transforms/Scalar/LoopPassManager.h"
     23 #include <vector>
     24 
     25 namespace llvm {
     26 class StringRef;
     27 class AAManager;
     28 class TargetMachine;
     29 
     30 /// A struct capturing PGO tunables.
     31 struct PGOOptions {
     32   PGOOptions(std::string ProfileGenFile = "", std::string ProfileUseFile = "",
     33              std::string SampleProfileFile = "", bool RunProfileGen = false,
     34              bool SamplePGOSupport = false)
     35       : ProfileGenFile(ProfileGenFile), ProfileUseFile(ProfileUseFile),
     36         SampleProfileFile(SampleProfileFile), RunProfileGen(RunProfileGen),
     37         SamplePGOSupport(SamplePGOSupport || !SampleProfileFile.empty()) {
     38     assert((RunProfileGen ||
     39             !SampleProfileFile.empty() ||
     40             !ProfileUseFile.empty() ||
     41             SamplePGOSupport) && "Illegal PGOOptions.");
     42   }
     43   std::string ProfileGenFile;
     44   std::string ProfileUseFile;
     45   std::string SampleProfileFile;
     46   bool RunProfileGen;
     47   bool SamplePGOSupport;
     48 };
     49 
     50 /// \brief This class provides access to building LLVM's passes.
     51 ///
     52 /// It's members provide the baseline state available to passes during their
     53 /// construction. The \c PassRegistry.def file specifies how to construct all
     54 /// of the built-in passes, and those may reference these members during
     55 /// construction.
     56 class PassBuilder {
     57   TargetMachine *TM;
     58   Optional<PGOOptions> PGOOpt;
     59 
     60 public:
     61   /// \brief A struct to capture parsed pass pipeline names.
     62   ///
     63   /// A pipeline is defined as a series of names, each of which may in itself
     64   /// recursively contain a nested pipeline. A name is either the name of a pass
     65   /// (e.g. "instcombine") or the name of a pipeline type (e.g. "cgscc"). If the
     66   /// name is the name of a pass, the InnerPipeline is empty, since passes
     67   /// cannot contain inner pipelines. See parsePassPipeline() for a more
     68   /// detailed description of the textual pipeline format.
     69   struct PipelineElement {
     70     StringRef Name;
     71     std::vector<PipelineElement> InnerPipeline;
     72   };
     73 
     74   /// \brief ThinLTO phase.
     75   ///
     76   /// This enumerates the LLVM ThinLTO optimization phases.
     77   enum class ThinLTOPhase {
     78     /// No ThinLTO behavior needed.
     79     None,
     80     // ThinLTO prelink (summary) phase.
     81     PreLink,
     82     // ThinLTO postlink (backend compile) phase.
     83     PostLink
     84   };
     85 
     86   /// \brief LLVM-provided high-level optimization levels.
     87   ///
     88   /// This enumerates the LLVM-provided high-level optimization levels. Each
     89   /// level has a specific goal and rationale.
     90   enum OptimizationLevel {
     91     /// Disable as many optimizations as possible. This doesn't completely
     92     /// disable the optimizer in all cases, for example always_inline functions
     93     /// can be required to be inlined for correctness.
     94     O0,
     95 
     96     /// Optimize quickly without destroying debuggability.
     97     ///
     98     /// FIXME: The current and historical behavior of this level does *not*
     99     /// agree with this goal, but we would like to move toward this goal in the
    100     /// future.
    101     ///
    102     /// This level is tuned to produce a result from the optimizer as quickly
    103     /// as possible and to avoid destroying debuggability. This tends to result
    104     /// in a very good development mode where the compiled code will be
    105     /// immediately executed as part of testing. As a consequence, where
    106     /// possible, we would like to produce efficient-to-execute code, but not
    107     /// if it significantly slows down compilation or would prevent even basic
    108     /// debugging of the resulting binary.
    109     ///
    110     /// As an example, complex loop transformations such as versioning,
    111     /// vectorization, or fusion might not make sense here due to the degree to
    112     /// which the executed code would differ from the source code, and the
    113     /// potential compile time cost.
    114     O1,
    115 
    116     /// Optimize for fast execution as much as possible without triggering
    117     /// significant incremental compile time or code size growth.
    118     ///
    119     /// The key idea is that optimizations at this level should "pay for
    120     /// themselves". So if an optimization increases compile time by 5% or
    121     /// increases code size by 5% for a particular benchmark, that benchmark
    122     /// should also be one which sees a 5% runtime improvement. If the compile
    123     /// time or code size penalties happen on average across a diverse range of
    124     /// LLVM users' benchmarks, then the improvements should as well.
    125     ///
    126     /// And no matter what, the compile time needs to not grow superlinearly
    127     /// with the size of input to LLVM so that users can control the runtime of
    128     /// the optimizer in this mode.
    129     ///
    130     /// This is expected to be a good default optimization level for the vast
    131     /// majority of users.
    132     O2,
    133 
    134     /// Optimize for fast execution as much as possible.
    135     ///
    136     /// This mode is significantly more aggressive in trading off compile time
    137     /// and code size to get execution time improvements. The core idea is that
    138     /// this mode should include any optimization that helps execution time on
    139     /// balance across a diverse collection of benchmarks, even if it increases
    140     /// code size or compile time for some benchmarks without corresponding
    141     /// improvements to execution time.
    142     ///
    143     /// Despite being willing to trade more compile time off to get improved
    144     /// execution time, this mode still tries to avoid superlinear growth in
    145     /// order to make even significantly slower compile times at least scale
    146     /// reasonably. This does not preclude very substantial constant factor
    147     /// costs though.
    148     O3,
    149 
    150     /// Similar to \c O2 but tries to optimize for small code size instead of
    151     /// fast execution without triggering significant incremental execution
    152     /// time slowdowns.
    153     ///
    154     /// The logic here is exactly the same as \c O2, but with code size and
    155     /// execution time metrics swapped.
    156     ///
    157     /// A consequence of the different core goal is that this should in general
    158     /// produce substantially smaller executables that still run in
    159     /// a reasonable amount of time.
    160     Os,
    161 
    162     /// A very specialized mode that will optimize for code size at any and all
    163     /// costs.
    164     ///
    165     /// This is useful primarily when there are absolute size limitations and
    166     /// any effort taken to reduce the size is worth it regardless of the
    167     /// execution time impact. You should expect this level to produce rather
    168     /// slow, but very small, code.
    169     Oz
    170   };
    171 
    172   explicit PassBuilder(TargetMachine *TM = nullptr,
    173                        Optional<PGOOptions> PGOOpt = None)
    174       : TM(TM), PGOOpt(PGOOpt) {}
    175 
    176   /// \brief Cross register the analysis managers through their proxies.
    177   ///
    178   /// This is an interface that can be used to cross register each
    179   // AnalysisManager with all the others analysis managers.
    180   void crossRegisterProxies(LoopAnalysisManager &LAM,
    181                             FunctionAnalysisManager &FAM,
    182                             CGSCCAnalysisManager &CGAM,
    183                             ModuleAnalysisManager &MAM);
    184 
    185   /// \brief Registers all available module analysis passes.
    186   ///
    187   /// This is an interface that can be used to populate a \c
    188   /// ModuleAnalysisManager with all registered module analyses. Callers can
    189   /// still manually register any additional analyses. Callers can also
    190   /// pre-register analyses and this will not override those.
    191   void registerModuleAnalyses(ModuleAnalysisManager &MAM);
    192 
    193   /// \brief Registers all available CGSCC analysis passes.
    194   ///
    195   /// This is an interface that can be used to populate a \c CGSCCAnalysisManager
    196   /// with all registered CGSCC analyses. Callers can still manually register any
    197   /// additional analyses. Callers can also pre-register analyses and this will
    198   /// not override those.
    199   void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM);
    200 
    201   /// \brief Registers all available function analysis passes.
    202   ///
    203   /// This is an interface that can be used to populate a \c
    204   /// FunctionAnalysisManager with all registered function analyses. Callers can
    205   /// still manually register any additional analyses. Callers can also
    206   /// pre-register analyses and this will not override those.
    207   void registerFunctionAnalyses(FunctionAnalysisManager &FAM);
    208 
    209   /// \brief Registers all available loop analysis passes.
    210   ///
    211   /// This is an interface that can be used to populate a \c LoopAnalysisManager
    212   /// with all registered loop analyses. Callers can still manually register any
    213   /// additional analyses.
    214   void registerLoopAnalyses(LoopAnalysisManager &LAM);
    215 
    216   /// Construct the core LLVM function canonicalization and simplification
    217   /// pipeline.
    218   ///
    219   /// This is a long pipeline and uses most of the per-function optimization
    220   /// passes in LLVM to canonicalize and simplify the IR. It is suitable to run
    221   /// repeatedly over the IR and is not expected to destroy important
    222   /// information about the semantics of the IR.
    223   ///
    224   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    225   /// only intended for use when attempting to optimize code. If frontends
    226   /// require some transformations for semantic reasons, they should explicitly
    227   /// build them.
    228   ///
    229   /// \p Phase indicates the current ThinLTO phase.
    230   FunctionPassManager
    231   buildFunctionSimplificationPipeline(OptimizationLevel Level,
    232                                       ThinLTOPhase Phase,
    233                                       bool DebugLogging = false);
    234 
    235   /// Construct the core LLVM module canonicalization and simplification
    236   /// pipeline.
    237   ///
    238   /// This pipeline focuses on canonicalizing and simplifying the entire module
    239   /// of IR. Much like the function simplification pipeline above, it is
    240   /// suitable to run repeatedly over the IR and is not expected to destroy
    241   /// important information. It does, however, perform inlining and other
    242   /// heuristic based simplifications that are not strictly reversible.
    243   ///
    244   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    245   /// only intended for use when attempting to optimize code. If frontends
    246   /// require some transformations for semantic reasons, they should explicitly
    247   /// build them.
    248   ///
    249   /// \p Phase indicates the current ThinLTO phase.
    250   ModulePassManager
    251   buildModuleSimplificationPipeline(OptimizationLevel Level,
    252                                     ThinLTOPhase Phase,
    253                                     bool DebugLogging = false);
    254 
    255   /// Construct the core LLVM module optimization pipeline.
    256   ///
    257   /// This pipeline focuses on optimizing the execution speed of the IR. It
    258   /// uses cost modeling and thresholds to balance code growth against runtime
    259   /// improvements. It includes vectorization and other information destroying
    260   /// transformations. It also cannot generally be run repeatedly on a module
    261   /// without potentially seriously regressing either runtime performance of
    262   /// the code or serious code size growth.
    263   ///
    264   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    265   /// only intended for use when attempting to optimize code. If frontends
    266   /// require some transformations for semantic reasons, they should explicitly
    267   /// build them.
    268   ModulePassManager buildModuleOptimizationPipeline(OptimizationLevel Level,
    269                                                     bool DebugLogging = false);
    270 
    271   /// Build a per-module default optimization pipeline.
    272   ///
    273   /// This provides a good default optimization pipeline for per-module
    274   /// optimization and code generation without any link-time optimization. It
    275   /// typically correspond to frontend "-O[123]" options for optimization
    276   /// levels \c O1, \c O2 and \c O3 resp.
    277   ///
    278   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    279   /// only intended for use when attempting to optimize code. If frontends
    280   /// require some transformations for semantic reasons, they should explicitly
    281   /// build them.
    282   ModulePassManager buildPerModuleDefaultPipeline(OptimizationLevel Level,
    283                                                   bool DebugLogging = false);
    284 
    285   /// Build a pre-link, ThinLTO-targeting default optimization pipeline to
    286   /// a pass manager.
    287   ///
    288   /// This adds the pre-link optimizations tuned to prepare a module for
    289   /// a ThinLTO run. It works to minimize the IR which needs to be analyzed
    290   /// without making irreversible decisions which could be made better during
    291   /// the LTO run.
    292   ///
    293   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    294   /// only intended for use when attempting to optimize code. If frontends
    295   /// require some transformations for semantic reasons, they should explicitly
    296   /// build them.
    297   ModulePassManager
    298   buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
    299                                      bool DebugLogging = false);
    300 
    301   /// Build an ThinLTO default optimization pipeline to a pass manager.
    302   ///
    303   /// This provides a good default optimization pipeline for link-time
    304   /// optimization and code generation. It is particularly tuned to fit well
    305   /// when IR coming into the LTO phase was first run through \c
    306   /// addPreLinkLTODefaultPipeline, and the two coordinate closely.
    307   ///
    308   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    309   /// only intended for use when attempting to optimize code. If frontends
    310   /// require some transformations for semantic reasons, they should explicitly
    311   /// build them.
    312   ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level,
    313                                                 bool DebugLogging = false);
    314 
    315   /// Build a pre-link, LTO-targeting default optimization pipeline to a pass
    316   /// manager.
    317   ///
    318   /// This adds the pre-link optimizations tuned to work well with a later LTO
    319   /// run. It works to minimize the IR which needs to be analyzed without
    320   /// making irreversible decisions which could be made better during the LTO
    321   /// run.
    322   ///
    323   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    324   /// only intended for use when attempting to optimize code. If frontends
    325   /// require some transformations for semantic reasons, they should explicitly
    326   /// build them.
    327   ModulePassManager buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
    328                                                    bool DebugLogging = false);
    329 
    330   /// Build an LTO default optimization pipeline to a pass manager.
    331   ///
    332   /// This provides a good default optimization pipeline for link-time
    333   /// optimization and code generation. It is particularly tuned to fit well
    334   /// when IR coming into the LTO phase was first run through \c
    335   /// addPreLinkLTODefaultPipeline, and the two coordinate closely.
    336   ///
    337   /// Note that \p Level cannot be `O0` here. The pipelines produced are
    338   /// only intended for use when attempting to optimize code. If frontends
    339   /// require some transformations for semantic reasons, they should explicitly
    340   /// build them.
    341   ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level,
    342                                             bool DebugLogging = false);
    343 
    344   /// Build the default `AAManager` with the default alias analysis pipeline
    345   /// registered.
    346   AAManager buildDefaultAAPipeline();
    347 
    348   /// \brief Parse a textual pass pipeline description into a \c
    349   /// ModulePassManager.
    350   ///
    351   /// The format of the textual pass pipeline description looks something like:
    352   ///
    353   ///   module(function(instcombine,sroa),dce,cgscc(inliner,function(...)),...)
    354   ///
    355   /// Pass managers have ()s describing the nest structure of passes. All passes
    356   /// are comma separated. As a special shortcut, if the very first pass is not
    357   /// a module pass (as a module pass manager is), this will automatically form
    358   /// the shortest stack of pass managers that allow inserting that first pass.
    359   /// So, assuming function passes 'fpassN', CGSCC passes 'cgpassN', and loop
    360   /// passes 'lpassN', all of these are valid:
    361   ///
    362   ///   fpass1,fpass2,fpass3
    363   ///   cgpass1,cgpass2,cgpass3
    364   ///   lpass1,lpass2,lpass3
    365   ///
    366   /// And they are equivalent to the following (resp.):
    367   ///
    368   ///   module(function(fpass1,fpass2,fpass3))
    369   ///   module(cgscc(cgpass1,cgpass2,cgpass3))
    370   ///   module(function(loop(lpass1,lpass2,lpass3)))
    371   ///
    372   /// This shortcut is especially useful for debugging and testing small pass
    373   /// combinations. Note that these shortcuts don't introduce any other magic.
    374   /// If the sequence of passes aren't all the exact same kind of pass, it will
    375   /// be an error. You cannot mix different levels implicitly, you must
    376   /// explicitly form a pass manager in which to nest passes.
    377   bool parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText,
    378                          bool VerifyEachPass = true, bool DebugLogging = false);
    379 
    380   /// {{@ Parse a textual pass pipeline description into a specific PassManager
    381   ///
    382   /// Automatic deduction of an appropriate pass manager stack is not supported.
    383   /// For example, to insert a loop pass 'lpass' into a FunctinoPassManager,
    384   /// this is the valid pipeline text:
    385   ///
    386   ///   function(lpass)
    387   bool parsePassPipeline(CGSCCPassManager &CGPM, StringRef PipelineText,
    388                          bool VerifyEachPass = true, bool DebugLogging = false);
    389   bool parsePassPipeline(FunctionPassManager &FPM, StringRef PipelineText,
    390                          bool VerifyEachPass = true, bool DebugLogging = false);
    391   bool parsePassPipeline(LoopPassManager &LPM, StringRef PipelineText,
    392                          bool VerifyEachPass = true, bool DebugLogging = false);
    393   /// @}}
    394 
    395   /// Parse a textual alias analysis pipeline into the provided AA manager.
    396   ///
    397   /// The format of the textual AA pipeline is a comma separated list of AA
    398   /// pass names:
    399   ///
    400   ///   basic-aa,globals-aa,...
    401   ///
    402   /// The AA manager is set up such that the provided alias analyses are tried
    403   /// in the order specified. See the \c AAManaager documentation for details
    404   /// about the logic used. This routine just provides the textual mapping
    405   /// between AA names and the analyses to register with the manager.
    406   ///
    407   /// Returns false if the text cannot be parsed cleanly. The specific state of
    408   /// the \p AA manager is unspecified if such an error is encountered and this
    409   /// returns false.
    410   bool parseAAPipeline(AAManager &AA, StringRef PipelineText);
    411 
    412   /// \brief Register a callback for a default optimizer pipeline extension
    413   /// point
    414   ///
    415   /// This extension point allows adding passes that perform peephole
    416   /// optimizations similar to the instruction combiner. These passes will be
    417   /// inserted after each instance of the instruction combiner pass.
    418   void registerPeepholeEPCallback(
    419       const std::function<void(FunctionPassManager &, OptimizationLevel)> &C) {
    420     PeepholeEPCallbacks.push_back(C);
    421   }
    422 
    423   /// \brief Register a callback for a default optimizer pipeline extension
    424   /// point
    425   ///
    426   /// This extension point allows adding late loop canonicalization and
    427   /// simplification passes. This is the last point in the loop optimization
    428   /// pipeline before loop deletion. Each pass added
    429   /// here must be an instance of LoopPass.
    430   /// This is the place to add passes that can remove loops, such as target-
    431   /// specific loop idiom recognition.
    432   void registerLateLoopOptimizationsEPCallback(
    433       const std::function<void(LoopPassManager &, OptimizationLevel)> &C) {
    434     LateLoopOptimizationsEPCallbacks.push_back(C);
    435   }
    436 
    437   /// \brief Register a callback for a default optimizer pipeline extension
    438   /// point
    439   ///
    440   /// This extension point allows adding loop passes to the end of the loop
    441   /// optimizer.
    442   void registerLoopOptimizerEndEPCallback(
    443       const std::function<void(LoopPassManager &, OptimizationLevel)> &C) {
    444     LoopOptimizerEndEPCallbacks.push_back(C);
    445   }
    446 
    447   /// \brief Register a callback for a default optimizer pipeline extension
    448   /// point
    449   ///
    450   /// This extension point allows adding optimization passes after most of the
    451   /// main optimizations, but before the last cleanup-ish optimizations.
    452   void registerScalarOptimizerLateEPCallback(
    453       const std::function<void(FunctionPassManager &, OptimizationLevel)> &C) {
    454     ScalarOptimizerLateEPCallbacks.push_back(C);
    455   }
    456 
    457   /// \brief Register a callback for a default optimizer pipeline extension
    458   /// point
    459   ///
    460   /// This extension point allows adding CallGraphSCC passes at the end of the
    461   /// main CallGraphSCC passes and before any function simplification passes run
    462   /// by CGPassManager.
    463   void registerCGSCCOptimizerLateEPCallback(
    464       const std::function<void(CGSCCPassManager &, OptimizationLevel)> &C) {
    465     CGSCCOptimizerLateEPCallbacks.push_back(C);
    466   }
    467 
    468   /// \brief Register a callback for a default optimizer pipeline extension
    469   /// point
    470   ///
    471   /// This extension point allows adding optimization passes before the
    472   /// vectorizer and other highly target specific optimization passes are
    473   /// executed.
    474   void registerVectorizerStartEPCallback(
    475       const std::function<void(FunctionPassManager &, OptimizationLevel)> &C) {
    476     VectorizerStartEPCallbacks.push_back(C);
    477   }
    478 
    479   /// \brief Register a callback for parsing an AliasAnalysis Name to populate
    480   /// the given AAManager \p AA
    481   void registerParseAACallback(
    482       const std::function<bool(StringRef Name, AAManager &AA)> &C) {
    483     AAParsingCallbacks.push_back(C);
    484   }
    485 
    486   /// {{@ Register callbacks for analysis registration with this PassBuilder
    487   /// instance.
    488   /// Callees register their analyses with the given AnalysisManager objects.
    489   void registerAnalysisRegistrationCallback(
    490       const std::function<void(CGSCCAnalysisManager &)> &C) {
    491     CGSCCAnalysisRegistrationCallbacks.push_back(C);
    492   }
    493   void registerAnalysisRegistrationCallback(
    494       const std::function<void(FunctionAnalysisManager &)> &C) {
    495     FunctionAnalysisRegistrationCallbacks.push_back(C);
    496   }
    497   void registerAnalysisRegistrationCallback(
    498       const std::function<void(LoopAnalysisManager &)> &C) {
    499     LoopAnalysisRegistrationCallbacks.push_back(C);
    500   }
    501   void registerAnalysisRegistrationCallback(
    502       const std::function<void(ModuleAnalysisManager &)> &C) {
    503     ModuleAnalysisRegistrationCallbacks.push_back(C);
    504   }
    505   /// @}}
    506 
    507   /// {{@ Register pipeline parsing callbacks with this pass builder instance.
    508   /// Using these callbacks, callers can parse both a single pass name, as well
    509   /// as entire sub-pipelines, and populate the PassManager instance
    510   /// accordingly.
    511   void registerPipelineParsingCallback(
    512       const std::function<bool(StringRef Name, CGSCCPassManager &,
    513                                ArrayRef<PipelineElement>)> &C) {
    514     CGSCCPipelineParsingCallbacks.push_back(C);
    515   }
    516   void registerPipelineParsingCallback(
    517       const std::function<bool(StringRef Name, FunctionPassManager &,
    518                                ArrayRef<PipelineElement>)> &C) {
    519     FunctionPipelineParsingCallbacks.push_back(C);
    520   }
    521   void registerPipelineParsingCallback(
    522       const std::function<bool(StringRef Name, LoopPassManager &,
    523                                ArrayRef<PipelineElement>)> &C) {
    524     LoopPipelineParsingCallbacks.push_back(C);
    525   }
    526   void registerPipelineParsingCallback(
    527       const std::function<bool(StringRef Name, ModulePassManager &,
    528                                ArrayRef<PipelineElement>)> &C) {
    529     ModulePipelineParsingCallbacks.push_back(C);
    530   }
    531   /// @}}
    532 
    533   /// \brief Register a callback for a top-level pipeline entry.
    534   ///
    535   /// If the PassManager type is not given at the top level of the pipeline
    536   /// text, this Callback should be used to determine the appropriate stack of
    537   /// PassManagers and populate the passed ModulePassManager.
    538   void registerParseTopLevelPipelineCallback(
    539       const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>,
    540                                bool VerifyEachPass, bool DebugLogging)> &C) {
    541     TopLevelPipelineParsingCallbacks.push_back(C);
    542   }
    543 
    544 private:
    545   static Optional<std::vector<PipelineElement>>
    546   parsePipelineText(StringRef Text);
    547 
    548   bool parseModulePass(ModulePassManager &MPM, const PipelineElement &E,
    549                        bool VerifyEachPass, bool DebugLogging);
    550   bool parseCGSCCPass(CGSCCPassManager &CGPM, const PipelineElement &E,
    551                       bool VerifyEachPass, bool DebugLogging);
    552   bool parseFunctionPass(FunctionPassManager &FPM, const PipelineElement &E,
    553                      bool VerifyEachPass, bool DebugLogging);
    554   bool parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
    555                      bool VerifyEachPass, bool DebugLogging);
    556   bool parseAAPassName(AAManager &AA, StringRef Name);
    557 
    558   bool parseLoopPassPipeline(LoopPassManager &LPM,
    559                              ArrayRef<PipelineElement> Pipeline,
    560                              bool VerifyEachPass, bool DebugLogging);
    561   bool parseFunctionPassPipeline(FunctionPassManager &FPM,
    562                                  ArrayRef<PipelineElement> Pipeline,
    563                                  bool VerifyEachPass, bool DebugLogging);
    564   bool parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
    565                               ArrayRef<PipelineElement> Pipeline,
    566                               bool VerifyEachPass, bool DebugLogging);
    567   bool parseModulePassPipeline(ModulePassManager &MPM,
    568                                ArrayRef<PipelineElement> Pipeline,
    569                                bool VerifyEachPass, bool DebugLogging);
    570 
    571   void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
    572                          OptimizationLevel Level, bool RunProfileGen,
    573                          std::string ProfileGenFile,
    574                          std::string ProfileUseFile);
    575 
    576   void invokePeepholeEPCallbacks(FunctionPassManager &, OptimizationLevel);
    577 
    578   // Extension Point callbacks
    579   SmallVector<std::function<void(FunctionPassManager &, OptimizationLevel)>, 2>
    580       PeepholeEPCallbacks;
    581   SmallVector<std::function<void(LoopPassManager &, OptimizationLevel)>, 2>
    582       LateLoopOptimizationsEPCallbacks;
    583   SmallVector<std::function<void(LoopPassManager &, OptimizationLevel)>, 2>
    584       LoopOptimizerEndEPCallbacks;
    585   SmallVector<std::function<void(FunctionPassManager &, OptimizationLevel)>, 2>
    586       ScalarOptimizerLateEPCallbacks;
    587   SmallVector<std::function<void(CGSCCPassManager &, OptimizationLevel)>, 2>
    588       CGSCCOptimizerLateEPCallbacks;
    589   SmallVector<std::function<void(FunctionPassManager &, OptimizationLevel)>, 2>
    590       VectorizerStartEPCallbacks;
    591   // Module callbacks
    592   SmallVector<std::function<void(ModuleAnalysisManager &)>, 2>
    593       ModuleAnalysisRegistrationCallbacks;
    594   SmallVector<std::function<bool(StringRef, ModulePassManager &,
    595                                  ArrayRef<PipelineElement>)>,
    596               2>
    597       ModulePipelineParsingCallbacks;
    598   SmallVector<std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>,
    599                                  bool VerifyEachPass, bool DebugLogging)>,
    600               2>
    601       TopLevelPipelineParsingCallbacks;
    602   // CGSCC callbacks
    603   SmallVector<std::function<void(CGSCCAnalysisManager &)>, 2>
    604       CGSCCAnalysisRegistrationCallbacks;
    605   SmallVector<std::function<bool(StringRef, CGSCCPassManager &,
    606                                  ArrayRef<PipelineElement>)>,
    607               2>
    608       CGSCCPipelineParsingCallbacks;
    609   // Function callbacks
    610   SmallVector<std::function<void(FunctionAnalysisManager &)>, 2>
    611       FunctionAnalysisRegistrationCallbacks;
    612   SmallVector<std::function<bool(StringRef, FunctionPassManager &,
    613                                  ArrayRef<PipelineElement>)>,
    614               2>
    615       FunctionPipelineParsingCallbacks;
    616   // Loop callbacks
    617   SmallVector<std::function<void(LoopAnalysisManager &)>, 2>
    618       LoopAnalysisRegistrationCallbacks;
    619   SmallVector<std::function<bool(StringRef, LoopPassManager &,
    620                                  ArrayRef<PipelineElement>)>,
    621               2>
    622       LoopPipelineParsingCallbacks;
    623   // AA callbacks
    624   SmallVector<std::function<bool(StringRef Name, AAManager &AA)>, 2>
    625       AAParsingCallbacks;
    626 };
    627 
    628 /// This utility template takes care of adding require<> and invalidate<>
    629 /// passes for an analysis to a given \c PassManager. It is intended to be used
    630 /// during parsing of a pass pipeline when parsing a single PipelineName.
    631 /// When registering a new function analysis FancyAnalysis with the pass
    632 /// pipeline name "fancy-analysis", a matching ParsePipelineCallback could look
    633 /// like this:
    634 ///
    635 /// static bool parseFunctionPipeline(StringRef Name, FunctionPassManager &FPM,
    636 ///                                   ArrayRef<PipelineElement> P) {
    637 ///   if (parseAnalysisUtilityPasses<FancyAnalysis>("fancy-analysis", Name,
    638 ///                                                 FPM))
    639 ///     return true;
    640 ///   return false;
    641 /// }
    642 template <typename AnalysisT, typename IRUnitT, typename AnalysisManagerT,
    643           typename... ExtraArgTs>
    644 bool parseAnalysisUtilityPasses(
    645     StringRef AnalysisName, StringRef PipelineName,
    646     PassManager<IRUnitT, AnalysisManagerT, ExtraArgTs...> &PM) {
    647   if (!PipelineName.endswith(">"))
    648     return false;
    649   // See if this is an invalidate<> pass name
    650   if (PipelineName.startswith("invalidate<")) {
    651     PipelineName = PipelineName.substr(11, PipelineName.size() - 12);
    652     if (PipelineName != AnalysisName)
    653       return false;
    654     PM.addPass(InvalidateAnalysisPass<AnalysisT>());
    655     return true;
    656   }
    657 
    658   // See if this is a require<> pass name
    659   if (PipelineName.startswith("require<")) {
    660     PipelineName = PipelineName.substr(8, PipelineName.size() - 9);
    661     if (PipelineName != AnalysisName)
    662       return false;
    663     PM.addPass(RequireAnalysisPass<AnalysisT, IRUnitT, AnalysisManagerT,
    664                                    ExtraArgTs...>());
    665     return true;
    666   }
    667 
    668   return false;
    669 }
    670 }
    671 
    672 #endif
    673