PassBuilder.h 36 KB

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