1 //===- Parsing, selection, and construction of pass pipelines -------------===//
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 file provides the implementation of the PassBuilder based on our
11 /// static pass registry as well as related functionality. It also provides
12 /// helpers to aid in analyzing, debugging, and testing passes and pass
13 /// pipelines.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Passes/PassBuilder.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/CFGPrinter.h"
26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
28 #include "llvm/Analysis/CGSCCPassManager.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/DDG.h"
31 #include "llvm/Analysis/DemandedBits.h"
32 #include "llvm/Analysis/DependenceAnalysis.h"
33 #include "llvm/Analysis/DominanceFrontier.h"
34 #include "llvm/Analysis/GlobalsModRef.h"
35 #include "llvm/Analysis/IVUsers.h"
36 #include "llvm/Analysis/LazyCallGraph.h"
37 #include "llvm/Analysis/LazyValueInfo.h"
38 #include "llvm/Analysis/LoopAccessAnalysis.h"
39 #include "llvm/Analysis/LoopCacheAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/LoopNestAnalysis.h"
42 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
43 #include "llvm/Analysis/MemorySSA.h"
44 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
45 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
46 #include "llvm/Analysis/PhiValues.h"
47 #include "llvm/Analysis/PostDominators.h"
48 #include "llvm/Analysis/ProfileSummaryInfo.h"
49 #include "llvm/Analysis/RegionInfo.h"
50 #include "llvm/Analysis/ScalarEvolution.h"
51 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
52 #include "llvm/Analysis/ScopedNoAliasAA.h"
53 #include "llvm/Analysis/StackSafetyAnalysis.h"
54 #include "llvm/Analysis/TargetLibraryInfo.h"
55 #include "llvm/Analysis/TargetTransformInfo.h"
56 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
57 #include "llvm/CodeGen/MachineModuleInfo.h"
58 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
59 #include "llvm/CodeGen/UnreachableBlockElim.h"
60 #include "llvm/IR/Dominators.h"
61 #include "llvm/IR/IRPrintingPasses.h"
62 #include "llvm/IR/PassManager.h"
63 #include "llvm/IR/SafepointIRVerifier.h"
64 #include "llvm/IR/Verifier.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/FormatVariadic.h"
68 #include "llvm/Support/Regex.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
71 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
72 #include "llvm/Transforms/Coroutines/CoroEarly.h"
73 #include "llvm/Transforms/Coroutines/CoroElide.h"
74 #include "llvm/Transforms/Coroutines/CoroSplit.h"
75 #include "llvm/Transforms/IPO/AlwaysInliner.h"
76 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
77 #include "llvm/Transforms/IPO/Attributor.h"
78 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
79 #include "llvm/Transforms/IPO/ConstantMerge.h"
80 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
81 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
82 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
83 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
84 #include "llvm/Transforms/IPO/FunctionAttrs.h"
85 #include "llvm/Transforms/IPO/FunctionImport.h"
86 #include "llvm/Transforms/IPO/GlobalDCE.h"
87 #include "llvm/Transforms/IPO/GlobalOpt.h"
88 #include "llvm/Transforms/IPO/GlobalSplit.h"
89 #include "llvm/Transforms/IPO/HotColdSplitting.h"
90 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
91 #include "llvm/Transforms/IPO/Inliner.h"
92 #include "llvm/Transforms/IPO/Internalize.h"
93 #include "llvm/Transforms/IPO/LowerTypeTests.h"
94 #include "llvm/Transforms/IPO/MergeFunctions.h"
95 #include "llvm/Transforms/IPO/OpenMPOpt.h"
96 #include "llvm/Transforms/IPO/PartialInlining.h"
97 #include "llvm/Transforms/IPO/SCCP.h"
98 #include "llvm/Transforms/IPO/SampleProfile.h"
99 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
100 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
101 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
102 #include "llvm/Transforms/InstCombine/InstCombine.h"
103 #include "llvm/Transforms/Instrumentation.h"
104 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
105 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
106 #include "llvm/Transforms/Instrumentation/CGProfile.h"
107 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
108 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
109 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
110 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
111 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
112 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
113 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
114 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
115 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
116 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
117 #include "llvm/Transforms/Scalar/ADCE.h"
118 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
119 #include "llvm/Transforms/Scalar/BDCE.h"
120 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
121 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
122 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
123 #include "llvm/Transforms/Scalar/DCE.h"
124 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
125 #include "llvm/Transforms/Scalar/DivRemPairs.h"
126 #include "llvm/Transforms/Scalar/EarlyCSE.h"
127 #include "llvm/Transforms/Scalar/Float2Int.h"
128 #include "llvm/Transforms/Scalar/GVN.h"
129 #include "llvm/Transforms/Scalar/GuardWidening.h"
130 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
131 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
132 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
133 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
134 #include "llvm/Transforms/Scalar/JumpThreading.h"
135 #include "llvm/Transforms/Scalar/LICM.h"
136 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
137 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
138 #include "llvm/Transforms/Scalar/LoopDeletion.h"
139 #include "llvm/Transforms/Scalar/LoopDistribute.h"
140 #include "llvm/Transforms/Scalar/LoopFuse.h"
141 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
142 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
143 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
144 #include "llvm/Transforms/Scalar/LoopPassManager.h"
145 #include "llvm/Transforms/Scalar/LoopPredication.h"
146 #include "llvm/Transforms/Scalar/LoopRotation.h"
147 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
148 #include "llvm/Transforms/Scalar/LoopSink.h"
149 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
150 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
151 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
152 #include "llvm/Transforms/Scalar/LowerAtomic.h"
153 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
154 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
155 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
156 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
157 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
158 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
159 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
160 #include "llvm/Transforms/Scalar/MergeICmps.h"
161 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
162 #include "llvm/Transforms/Scalar/NaryReassociate.h"
163 #include "llvm/Transforms/Scalar/NewGVN.h"
164 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
165 #include "llvm/Transforms/Scalar/Reassociate.h"
166 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
167 #include "llvm/Transforms/Scalar/SCCP.h"
168 #include "llvm/Transforms/Scalar/SROA.h"
169 #include "llvm/Transforms/Scalar/Scalarizer.h"
170 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
171 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
172 #include "llvm/Transforms/Scalar/Sink.h"
173 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
174 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
175 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
176 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
177 #include "llvm/Transforms/Utils/AddDiscriminators.h"
178 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
179 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
180 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
181 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
182 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
183 #include "llvm/Transforms/Utils/LCSSA.h"
184 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
185 #include "llvm/Transforms/Utils/LoopSimplify.h"
186 #include "llvm/Transforms/Utils/LowerInvoke.h"
187 #include "llvm/Transforms/Utils/Mem2Reg.h"
188 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
189 #include "llvm/Transforms/Utils/SymbolRewriter.h"
190 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
191 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
192 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
193 #include "llvm/Transforms/Vectorize/VectorCombine.h"
194 
195 using namespace llvm;
196 
197 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
198                                              cl::ReallyHidden, cl::init(4));
199 static cl::opt<bool>
200     RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
201                        cl::Hidden, cl::ZeroOrMore,
202                        cl::desc("Run Partial inlinining pass"));
203 
204 static cl::opt<int> PreInlineThreshold(
205     "npm-preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
206     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
207              "(default = 75)"));
208 
209 static cl::opt<bool>
210     RunNewGVN("enable-npm-newgvn", cl::init(false),
211               cl::Hidden, cl::ZeroOrMore,
212               cl::desc("Run NewGVN instead of GVN"));
213 
214 static cl::opt<bool> EnableGVNHoist(
215     "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
216     cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
217 
218 static cl::opt<bool> EnableGVNSink(
219     "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
220     cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
221 
222 static cl::opt<bool> EnableUnrollAndJam(
223     "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
224     cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
225 
226 static cl::opt<bool> EnableSyntheticCounts(
227     "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
228     cl::desc("Run synthetic function entry count generation "
229              "pass"));
230 
231 static const Regex DefaultAliasRegex(
232     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
233 
234 // This option is used in simplifying testing SampleFDO optimizations for
235 // profile loading.
236 static cl::opt<bool>
237     EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
238               cl::desc("Enable control height reduction optimization (CHR)"));
239 
240 static cl::opt<bool> EnableCallGraphProfile(
241     "enable-npm-call-graph-profile", cl::init(true), cl::Hidden,
242     cl::desc("Enable call graph profile pass for the new PM (default = on)"));
243 
244 PipelineTuningOptions::PipelineTuningOptions() {
245   LoopInterleaving = true;
246   LoopVectorization = true;
247   SLPVectorization = false;
248   LoopUnrolling = true;
249   ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
250   Coroutines = false;
251   LicmMssaOptCap = SetLicmMssaOptCap;
252   LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
253   CallGraphProfile = EnableCallGraphProfile;
254 }
255 
256 extern cl::opt<bool> EnableHotColdSplit;
257 extern cl::opt<bool> EnableOrderFileInstrumentation;
258 
259 extern cl::opt<bool> FlattenedProfileUsed;
260 
261 extern cl::opt<AttributorRunOption> AttributorRun;
262 
263 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O0 = {
264     /*SpeedLevel*/ 0,
265     /*SizeLevel*/ 0};
266 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O1 = {
267     /*SpeedLevel*/ 1,
268     /*SizeLevel*/ 0};
269 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O2 = {
270     /*SpeedLevel*/ 2,
271     /*SizeLevel*/ 0};
272 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O3 = {
273     /*SpeedLevel*/ 3,
274     /*SizeLevel*/ 0};
275 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Os = {
276     /*SpeedLevel*/ 2,
277     /*SizeLevel*/ 1};
278 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Oz = {
279     /*SpeedLevel*/ 2,
280     /*SizeLevel*/ 2};
281 
282 namespace {
283 
284 /// No-op module pass which does nothing.
285 struct NoOpModulePass {
286   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
287     return PreservedAnalyses::all();
288   }
289   static StringRef name() { return "NoOpModulePass"; }
290 };
291 
292 /// No-op module analysis.
293 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
294   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
295   static AnalysisKey Key;
296 
297 public:
298   struct Result {};
299   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
300   static StringRef name() { return "NoOpModuleAnalysis"; }
301 };
302 
303 /// No-op CGSCC pass which does nothing.
304 struct NoOpCGSCCPass {
305   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
306                         LazyCallGraph &, CGSCCUpdateResult &UR) {
307     return PreservedAnalyses::all();
308   }
309   static StringRef name() { return "NoOpCGSCCPass"; }
310 };
311 
312 /// No-op CGSCC analysis.
313 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
314   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
315   static AnalysisKey Key;
316 
317 public:
318   struct Result {};
319   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
320     return Result();
321   }
322   static StringRef name() { return "NoOpCGSCCAnalysis"; }
323 };
324 
325 /// No-op function pass which does nothing.
326 struct NoOpFunctionPass {
327   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
328     return PreservedAnalyses::all();
329   }
330   static StringRef name() { return "NoOpFunctionPass"; }
331 };
332 
333 /// No-op function analysis.
334 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
335   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
336   static AnalysisKey Key;
337 
338 public:
339   struct Result {};
340   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
341   static StringRef name() { return "NoOpFunctionAnalysis"; }
342 };
343 
344 /// No-op loop pass which does nothing.
345 struct NoOpLoopPass {
346   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
347                         LoopStandardAnalysisResults &, LPMUpdater &) {
348     return PreservedAnalyses::all();
349   }
350   static StringRef name() { return "NoOpLoopPass"; }
351 };
352 
353 /// No-op loop analysis.
354 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
355   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
356   static AnalysisKey Key;
357 
358 public:
359   struct Result {};
360   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
361     return Result();
362   }
363   static StringRef name() { return "NoOpLoopAnalysis"; }
364 };
365 
366 AnalysisKey NoOpModuleAnalysis::Key;
367 AnalysisKey NoOpCGSCCAnalysis::Key;
368 AnalysisKey NoOpFunctionAnalysis::Key;
369 AnalysisKey NoOpLoopAnalysis::Key;
370 
371 } // End anonymous namespace.
372 
373 void PassBuilder::invokePeepholeEPCallbacks(
374     FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
375   for (auto &C : PeepholeEPCallbacks)
376     C(FPM, Level);
377 }
378 
379 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
380 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
381   MAM.registerPass([&] { return CREATE_PASS; });
382 #include "PassRegistry.def"
383 
384   for (auto &C : ModuleAnalysisRegistrationCallbacks)
385     C(MAM);
386 }
387 
388 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
389 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
390   CGAM.registerPass([&] { return CREATE_PASS; });
391 #include "PassRegistry.def"
392 
393   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
394     C(CGAM);
395 }
396 
397 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
398 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
399   FAM.registerPass([&] { return CREATE_PASS; });
400 #include "PassRegistry.def"
401 
402   for (auto &C : FunctionAnalysisRegistrationCallbacks)
403     C(FAM);
404 }
405 
406 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
407 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
408   LAM.registerPass([&] { return CREATE_PASS; });
409 #include "PassRegistry.def"
410 
411   for (auto &C : LoopAnalysisRegistrationCallbacks)
412     C(LAM);
413 }
414 
415 FunctionPassManager
416 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
417                                                  ThinLTOPhase Phase,
418                                                  bool DebugLogging) {
419   assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
420   FunctionPassManager FPM(DebugLogging);
421 
422   // Form SSA out of local memory accesses after breaking apart aggregates into
423   // scalars.
424   FPM.addPass(SROA());
425 
426   // Catch trivial redundancies
427   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
428 
429   // Hoisting of scalars and load expressions.
430   if (Level.getSpeedupLevel() > 1) {
431     if (EnableGVNHoist)
432       FPM.addPass(GVNHoistPass());
433 
434     // Global value numbering based sinking.
435     if (EnableGVNSink) {
436       FPM.addPass(GVNSinkPass());
437       FPM.addPass(SimplifyCFGPass());
438     }
439   }
440 
441   // Speculative execution if the target has divergent branches; otherwise nop.
442   if (Level.getSpeedupLevel() > 1) {
443     FPM.addPass(SpeculativeExecutionPass());
444 
445     // Optimize based on known information about branches, and cleanup afterward.
446     FPM.addPass(JumpThreadingPass());
447     FPM.addPass(CorrelatedValuePropagationPass());
448   }
449   FPM.addPass(SimplifyCFGPass());
450   if (Level == OptimizationLevel::O3)
451     FPM.addPass(AggressiveInstCombinePass());
452   FPM.addPass(InstCombinePass());
453 
454   if (!Level.isOptimizingForSize())
455     FPM.addPass(LibCallsShrinkWrapPass());
456 
457   invokePeepholeEPCallbacks(FPM, Level);
458 
459   // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
460   // using the size value profile. Don't perform this when optimizing for size.
461   if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
462       (Level.getSpeedupLevel() > 1 && !Level.isOptimizingForSize()))
463     FPM.addPass(PGOMemOPSizeOpt());
464 
465   // TODO: Investigate the cost/benefit of tail call elimination on debugging.
466   if (Level.getSpeedupLevel() > 1)
467     FPM.addPass(TailCallElimPass());
468   FPM.addPass(SimplifyCFGPass());
469 
470   // Form canonically associated expression trees, and simplify the trees using
471   // basic mathematical properties. For example, this will form (nearly)
472   // minimal multiplication trees.
473   FPM.addPass(ReassociatePass());
474 
475   // Add the primary loop simplification pipeline.
476   // FIXME: Currently this is split into two loop pass pipelines because we run
477   // some function passes in between them. These can and should be removed
478   // and/or replaced by scheduling the loop pass equivalents in the correct
479   // positions. But those equivalent passes aren't powerful enough yet.
480   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
481   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
482   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
483   // `LoopInstSimplify`.
484   LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
485 
486   // Simplify the loop body. We do this initially to clean up after other loop
487   // passes run, either when iterating on a loop or on inner loops with
488   // implications on the outer loop.
489   LPM1.addPass(LoopInstSimplifyPass());
490   LPM1.addPass(LoopSimplifyCFGPass());
491 
492   // Rotate Loop - disable header duplication at -Oz
493   LPM1.addPass(LoopRotatePass(Level != OptimizationLevel::Oz));
494   // TODO: Investigate promotion cap for O1.
495   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
496   LPM1.addPass(SimpleLoopUnswitchPass());
497   LPM2.addPass(IndVarSimplifyPass());
498   LPM2.addPass(LoopIdiomRecognizePass());
499 
500   for (auto &C : LateLoopOptimizationsEPCallbacks)
501     C(LPM2, Level);
502 
503   LPM2.addPass(LoopDeletionPass());
504   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
505   // because it changes IR to makes profile annotation in back compile
506   // inaccurate.
507   if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
508        PGOOpt->Action != PGOOptions::SampleUse) &&
509       PTO.LoopUnrolling)
510     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
511                                     /*OnlyWhenForced=*/false,
512                                     PTO.ForgetAllSCEVInLoopUnroll));
513 
514   for (auto &C : LoopOptimizerEndEPCallbacks)
515     C(LPM2, Level);
516 
517   // We provide the opt remark emitter pass for LICM to use. We only need to do
518   // this once as it is immutable.
519   FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
520   FPM.addPass(createFunctionToLoopPassAdaptor(
521       std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
522   FPM.addPass(SimplifyCFGPass());
523   FPM.addPass(InstCombinePass());
524   // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
525   // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
526   // *All* loop passes must preserve it, in order to be able to use it.
527   FPM.addPass(createFunctionToLoopPassAdaptor(
528       std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
529 
530   // Delete small array after loop unroll.
531   FPM.addPass(SROA());
532 
533   // Eliminate redundancies.
534   if (Level != OptimizationLevel::O1) {
535     // These passes add substantial compile time so skip them at O1.
536     FPM.addPass(MergedLoadStoreMotionPass());
537     if (RunNewGVN)
538       FPM.addPass(NewGVNPass());
539     else
540       FPM.addPass(GVN());
541   }
542 
543   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
544   FPM.addPass(MemCpyOptPass());
545 
546   // Sparse conditional constant propagation.
547   // FIXME: It isn't clear why we do this *after* loop passes rather than
548   // before...
549   FPM.addPass(SCCPPass());
550 
551   // Delete dead bit computations (instcombine runs after to fold away the dead
552   // computations, and then ADCE will run later to exploit any new DCE
553   // opportunities that creates).
554   FPM.addPass(BDCEPass());
555 
556   // Run instcombine after redundancy and dead bit elimination to exploit
557   // opportunities opened up by them.
558   FPM.addPass(InstCombinePass());
559   invokePeepholeEPCallbacks(FPM, Level);
560 
561   // Re-consider control flow based optimizations after redundancy elimination,
562   // redo DCE, etc.
563   if (Level.getSpeedupLevel() > 1) {
564     FPM.addPass(JumpThreadingPass());
565     FPM.addPass(CorrelatedValuePropagationPass());
566     FPM.addPass(DSEPass());
567     FPM.addPass(createFunctionToLoopPassAdaptor(
568         LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
569         EnableMSSALoopDependency, DebugLogging));
570   }
571 
572   if (PTO.Coroutines)
573     FPM.addPass(CoroElidePass());
574 
575   for (auto &C : ScalarOptimizerLateEPCallbacks)
576     C(FPM, Level);
577 
578   // Finally, do an expensive DCE pass to catch all the dead code exposed by
579   // the simplifications and basic cleanup after all the simplifications.
580   // TODO: Investigate if this is too expensive.
581   FPM.addPass(ADCEPass());
582   FPM.addPass(SimplifyCFGPass());
583   FPM.addPass(InstCombinePass());
584   invokePeepholeEPCallbacks(FPM, Level);
585 
586   if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt &&
587       (PGOOpt->Action == PGOOptions::IRUse ||
588        PGOOpt->Action == PGOOptions::SampleUse))
589     FPM.addPass(ControlHeightReductionPass());
590 
591   return FPM;
592 }
593 
594 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
595                                     PassBuilder::OptimizationLevel Level,
596                                     bool RunProfileGen, bool IsCS,
597                                     std::string ProfileFile,
598                                     std::string ProfileRemappingFile) {
599   assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
600   // Generally running simplification passes and the inliner with an high
601   // threshold results in smaller executables, but there may be cases where
602   // the size grows, so let's be conservative here and skip this simplification
603   // at -Os/Oz. We will not do this  inline for context sensistive PGO (when
604   // IsCS is true).
605   if (!Level.isOptimizingForSize() && !IsCS) {
606     InlineParams IP;
607 
608     IP.DefaultThreshold = PreInlineThreshold;
609 
610     // FIXME: The hint threshold has the same value used by the regular inliner.
611     // This should probably be lowered after performance testing.
612     // FIXME: this comment is cargo culted from the old pass manager, revisit).
613     IP.HintThreshold = 325;
614 
615     CGSCCPassManager CGPipeline(DebugLogging);
616 
617     CGPipeline.addPass(InlinerPass(IP));
618 
619     FunctionPassManager FPM;
620     FPM.addPass(SROA());
621     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
622     FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
623     FPM.addPass(InstCombinePass()); // Combine silly sequences.
624     invokePeepholeEPCallbacks(FPM, Level);
625 
626     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
627 
628     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
629 
630     // Delete anything that is now dead to make sure that we don't instrument
631     // dead code. Instrumentation can end up keeping dead code around and
632     // dramatically increase code size.
633     MPM.addPass(GlobalDCEPass());
634   }
635 
636   if (!RunProfileGen) {
637     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
638     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
639     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
640     // RequireAnalysisPass for PSI before subsequent non-module passes.
641     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
642     return;
643   }
644 
645   // Perform PGO instrumentation.
646   MPM.addPass(PGOInstrumentationGen(IsCS));
647 
648   FunctionPassManager FPM;
649   FPM.addPass(createFunctionToLoopPassAdaptor(
650       LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
651   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
652 
653   // Add the profile lowering pass.
654   InstrProfOptions Options;
655   if (!ProfileFile.empty())
656     Options.InstrProfileOutput = ProfileFile;
657   // Do counter promotion at Level greater than O0.
658   Options.DoCounterPromotion = true;
659   Options.UseBFIInPromotion = IsCS;
660   MPM.addPass(InstrProfiling(Options, IsCS));
661 }
662 
663 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
664                                          bool DebugLogging, bool RunProfileGen,
665                                          bool IsCS, std::string ProfileFile,
666                                          std::string ProfileRemappingFile) {
667   if (!RunProfileGen) {
668     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
669     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
670     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
671     // RequireAnalysisPass for PSI before subsequent non-module passes.
672     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
673     return;
674   }
675 
676   // Perform PGO instrumentation.
677   MPM.addPass(PGOInstrumentationGen(IsCS));
678   // Add the profile lowering pass.
679   InstrProfOptions Options;
680   if (!ProfileFile.empty())
681     Options.InstrProfileOutput = ProfileFile;
682   // Do not do counter promotion at O0.
683   Options.DoCounterPromotion = false;
684   Options.UseBFIInPromotion = IsCS;
685   MPM.addPass(InstrProfiling(Options, IsCS));
686 }
687 
688 static InlineParams
689 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
690   return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
691 }
692 
693 ModulePassManager PassBuilder::buildInlinerPipeline(OptimizationLevel Level,
694                                                     ThinLTOPhase Phase,
695                                                     bool DebugLogging) {
696   ModulePassManager MPM(DebugLogging);
697 
698   // Now begin the main postorder CGSCC pipeline.
699   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
700   // manager and trying to emulate its precise behavior. Much of this doesn't
701   // make a lot of sense and we should revisit the core CGSCC structure.
702   CGSCCPassManager MainCGPipeline(DebugLogging);
703 
704   // Note: historically, the PruneEH pass was run first to deduce nounwind and
705   // generally clean up exception handling overhead. It isn't clear this is
706   // valuable as the inliner doesn't currently care whether it is inlining an
707   // invoke or a call.
708 
709   // Run the inliner first. The theory is that we are walking bottom-up and so
710   // the callees have already been fully optimized, and we want to inline them
711   // into the callers so that our optimizations can reflect that.
712   // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
713   // because it makes profile annotation in the backend inaccurate.
714   InlineParams IP = getInlineParamsFromOptLevel(Level);
715   if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
716       PGOOpt->Action == PGOOptions::SampleUse)
717     IP.HotCallSiteThreshold = 0;
718   MainCGPipeline.addPass(InlinerPass(IP));
719 
720   if (AttributorRun & AttributorRunOption::CGSCC)
721     MainCGPipeline.addPass(AttributorCGSCCPass());
722 
723   if (PTO.Coroutines)
724     MainCGPipeline.addPass(CoroSplitPass());
725 
726   // Now deduce any function attributes based in the current code.
727   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
728 
729   // When at O3 add argument promotion to the pass pipeline.
730   // FIXME: It isn't at all clear why this should be limited to O3.
731   if (Level == OptimizationLevel::O3)
732     MainCGPipeline.addPass(ArgumentPromotionPass());
733 
734   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
735   // there are no OpenMP runtime calls present in the module.
736   if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
737     MainCGPipeline.addPass(OpenMPOptPass());
738 
739   // Lastly, add the core function simplification pipeline nested inside the
740   // CGSCC walk.
741   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
742       buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
743 
744   for (auto &C : CGSCCOptimizerLateEPCallbacks)
745     C(MainCGPipeline, Level);
746 
747   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
748   // to detect when we devirtualize indirect calls and iterate the SCC passes
749   // in that case to try and catch knock-on inlining or function attrs
750   // opportunities. Then we add it to the module pipeline by walking the SCCs
751   // in postorder (or bottom-up).
752   MPM.addPass(
753       createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
754           std::move(MainCGPipeline), MaxDevirtIterations)));
755   return MPM;
756 }
757 
758 ModulePassManager PassBuilder::buildModuleSimplificationPipeline(
759     OptimizationLevel Level, ThinLTOPhase Phase, bool DebugLogging) {
760   ModulePassManager MPM(DebugLogging);
761 
762   bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
763 
764   // In ThinLTO mode, when flattened profile is used, all the available
765   // profile information will be annotated in PreLink phase so there is
766   // no need to load the profile again in PostLink.
767   bool LoadSampleProfile =
768       HasSampleProfile &&
769       !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
770 
771   // During the ThinLTO backend phase we perform early indirect call promotion
772   // here, before globalopt. Otherwise imported available_externally functions
773   // look unreferenced and are removed. If we are going to load the sample
774   // profile then defer until later.
775   // TODO: See if we can move later and consolidate with the location where
776   // we perform ICP when we are loading a sample profile.
777   // TODO: We pass HasSampleProfile (whether there was a sample profile file
778   // passed to the compile) to the SamplePGO flag of ICP. This is used to
779   // determine whether the new direct calls are annotated with prof metadata.
780   // Ideally this should be determined from whether the IR is annotated with
781   // sample profile, and not whether the a sample profile was provided on the
782   // command line. E.g. for flattened profiles where we will not be reloading
783   // the sample profile in the ThinLTO backend, we ideally shouldn't have to
784   // provide the sample profile file.
785   if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
786     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
787 
788   // Do basic inference of function attributes from known properties of system
789   // libraries and other oracles.
790   MPM.addPass(InferFunctionAttrsPass());
791 
792   // Create an early function pass manager to cleanup the output of the
793   // frontend.
794   FunctionPassManager EarlyFPM(DebugLogging);
795   EarlyFPM.addPass(SimplifyCFGPass());
796   EarlyFPM.addPass(SROA());
797   EarlyFPM.addPass(EarlyCSEPass());
798   EarlyFPM.addPass(LowerExpectIntrinsicPass());
799   if (PTO.Coroutines)
800     EarlyFPM.addPass(CoroEarlyPass());
801   if (Level == OptimizationLevel::O3)
802     EarlyFPM.addPass(CallSiteSplittingPass());
803 
804   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
805   // to convert bitcast to direct calls so that they can be inlined during the
806   // profile annotation prepration step.
807   // More details about SamplePGO design can be found in:
808   // https://research.google.com/pubs/pub45290.html
809   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
810   if (LoadSampleProfile)
811     EarlyFPM.addPass(InstCombinePass());
812   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
813 
814   if (LoadSampleProfile) {
815     // Annotate sample profile right after early FPM to ensure freshness of
816     // the debug info.
817     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
818                                         PGOOpt->ProfileRemappingFile,
819                                         Phase == ThinLTOPhase::PreLink));
820     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
821     // RequireAnalysisPass for PSI before subsequent non-module passes.
822     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
823     // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
824     // for the profile annotation to be accurate in the ThinLTO backend.
825     if (Phase != ThinLTOPhase::PreLink)
826       // We perform early indirect call promotion here, before globalopt.
827       // This is important for the ThinLTO backend phase because otherwise
828       // imported available_externally functions look unreferenced and are
829       // removed.
830       MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
831                                            true /* SamplePGO */));
832   }
833 
834   if (AttributorRun & AttributorRunOption::MODULE)
835     MPM.addPass(AttributorPass());
836 
837   // Interprocedural constant propagation now that basic cleanup has occurred
838   // and prior to optimizing globals.
839   // FIXME: This position in the pipeline hasn't been carefully considered in
840   // years, it should be re-analyzed.
841   MPM.addPass(IPSCCPPass());
842 
843   // Attach metadata to indirect call sites indicating the set of functions
844   // they may target at run-time. This should follow IPSCCP.
845   MPM.addPass(CalledValuePropagationPass());
846 
847   // Optimize globals to try and fold them into constants.
848   MPM.addPass(GlobalOptPass());
849 
850   // Promote any localized globals to SSA registers.
851   // FIXME: Should this instead by a run of SROA?
852   // FIXME: We should probably run instcombine and simplify-cfg afterward to
853   // delete control flows that are dead once globals have been folded to
854   // constants.
855   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
856 
857   // Remove any dead arguments exposed by cleanups and constand folding
858   // globals.
859   MPM.addPass(DeadArgumentEliminationPass());
860 
861   // Create a small function pass pipeline to cleanup after all the global
862   // optimizations.
863   FunctionPassManager GlobalCleanupPM(DebugLogging);
864   GlobalCleanupPM.addPass(InstCombinePass());
865   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
866 
867   GlobalCleanupPM.addPass(SimplifyCFGPass());
868   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
869 
870   // Add all the requested passes for instrumentation PGO, if requested.
871   if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
872       (PGOOpt->Action == PGOOptions::IRInstr ||
873        PGOOpt->Action == PGOOptions::IRUse)) {
874     addPGOInstrPasses(MPM, DebugLogging, Level,
875                       /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
876                       /* IsCS */ false, PGOOpt->ProfileFile,
877                       PGOOpt->ProfileRemappingFile);
878     MPM.addPass(PGOIndirectCallPromotion(false, false));
879   }
880   if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
881       PGOOpt->CSAction == PGOOptions::CSIRInstr)
882     MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
883 
884   // Synthesize function entry counts for non-PGO compilation.
885   if (EnableSyntheticCounts && !PGOOpt)
886     MPM.addPass(SyntheticCountsPropagation());
887 
888   // Require the GlobalsAA analysis for the module so we can query it within
889   // the CGSCC pipeline.
890   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
891 
892   // Require the ProfileSummaryAnalysis for the module so we can query it within
893   // the inliner pass.
894   MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
895 
896   MPM.addPass(buildInlinerPipeline(Level, Phase, DebugLogging));
897   return MPM;
898 }
899 
900 ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
901     OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
902   ModulePassManager MPM(DebugLogging);
903 
904   // Optimize globals now that the module is fully simplified.
905   MPM.addPass(GlobalOptPass());
906   MPM.addPass(GlobalDCEPass());
907 
908   // Run partial inlining pass to partially inline functions that have
909   // large bodies.
910   if (RunPartialInlining)
911     MPM.addPass(PartialInlinerPass());
912 
913   // Remove avail extern fns and globals definitions since we aren't compiling
914   // an object file for later LTO. For LTO we want to preserve these so they
915   // are eligible for inlining at link-time. Note if they are unreferenced they
916   // will be removed by GlobalDCE later, so this only impacts referenced
917   // available externally globals. Eventually they will be suppressed during
918   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
919   // may make globals referenced by available external functions dead and saves
920   // running remaining passes on the eliminated functions. These should be
921   // preserved during prelinking for link-time inlining decisions.
922   if (!LTOPreLink)
923     MPM.addPass(EliminateAvailableExternallyPass());
924 
925   if (EnableOrderFileInstrumentation)
926     MPM.addPass(InstrOrderFilePass());
927 
928   // Do RPO function attribute inference across the module to forward-propagate
929   // attributes where applicable.
930   // FIXME: Is this really an optimization rather than a canonicalization?
931   MPM.addPass(ReversePostOrderFunctionAttrsPass());
932 
933   // Do a post inline PGO instrumentation and use pass. This is a context
934   // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
935   // cross-module inline has not been done yet. The context sensitive
936   // instrumentation is after all the inlines are done.
937   if (!LTOPreLink && PGOOpt) {
938     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
939       addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
940                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
941                         PGOOpt->ProfileRemappingFile);
942     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
943       addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
944                         /* IsCS */ true, PGOOpt->ProfileFile,
945                         PGOOpt->ProfileRemappingFile);
946   }
947 
948   // Re-require GloblasAA here prior to function passes. This is particularly
949   // useful as the above will have inlined, DCE'ed, and function-attr
950   // propagated everything. We should at this point have a reasonably minimal
951   // and richly annotated call graph. By computing aliasing and mod/ref
952   // information for all local globals here, the late loop passes and notably
953   // the vectorizer will be able to use them to help recognize vectorizable
954   // memory operations.
955   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
956 
957   FunctionPassManager OptimizePM(DebugLogging);
958   OptimizePM.addPass(Float2IntPass());
959   OptimizePM.addPass(LowerConstantIntrinsicsPass());
960 
961   // FIXME: We need to run some loop optimizations to re-rotate loops after
962   // simplify-cfg and others undo their rotation.
963 
964   // Optimize the loop execution. These passes operate on entire loop nests
965   // rather than on each loop in an inside-out manner, and so they are actually
966   // function passes.
967 
968   for (auto &C : VectorizerStartEPCallbacks)
969     C(OptimizePM, Level);
970 
971   // First rotate loops that may have been un-rotated by prior passes.
972   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
973       LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
974 
975   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
976   // into separate loop that would otherwise inhibit vectorization.  This is
977   // currently only performed for loops marked with the metadata
978   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
979   OptimizePM.addPass(LoopDistributePass());
980 
981   // Populates the VFABI attribute with the scalar-to-vector mappings
982   // from the TargetLibraryInfo.
983   OptimizePM.addPass(InjectTLIMappings());
984 
985   // Now run the core loop vectorizer.
986   OptimizePM.addPass(LoopVectorizePass(
987       LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
988 
989   // Enhance/cleanup vector code.
990   OptimizePM.addPass(VectorCombinePass());
991   OptimizePM.addPass(EarlyCSEPass());
992 
993   // Eliminate loads by forwarding stores from the previous iteration to loads
994   // of the current iteration.
995   OptimizePM.addPass(LoopLoadEliminationPass());
996 
997   // Cleanup after the loop optimization passes.
998   OptimizePM.addPass(InstCombinePass());
999 
1000   // Now that we've formed fast to execute loop structures, we do further
1001   // optimizations. These are run afterward as they might block doing complex
1002   // analyses and transforms such as what are needed for loop vectorization.
1003 
1004   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1005   // GVN, loop transforms, and others have already run, so it's now better to
1006   // convert to more optimized IR using more aggressive simplify CFG options.
1007   // The extra sinking transform can create larger basic blocks, so do this
1008   // before SLP vectorization.
1009   OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
1010                                      forwardSwitchCondToPhi(true).
1011                                      convertSwitchToLookupTable(true).
1012                                      needCanonicalLoops(false).
1013                                      sinkCommonInsts(true)));
1014 
1015   // Optimize parallel scalar instruction chains into SIMD instructions.
1016   if (PTO.SLPVectorization)
1017     OptimizePM.addPass(SLPVectorizerPass());
1018 
1019   OptimizePM.addPass(InstCombinePass());
1020 
1021   // Unroll small loops to hide loop backedge latency and saturate any parallel
1022   // execution resources of an out-of-order processor. We also then need to
1023   // clean up redundancies and loop invariant code.
1024   // FIXME: It would be really good to use a loop-integrated instruction
1025   // combiner for cleanup here so that the unrolling and LICM can be pipelined
1026   // across the loop nests.
1027   // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1028   if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1029     OptimizePM.addPass(LoopUnrollAndJamPass(Level.getSpeedupLevel()));
1030   }
1031   OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions(
1032       Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1033       PTO.ForgetAllSCEVInLoopUnroll)));
1034   OptimizePM.addPass(WarnMissedTransformationsPass());
1035   OptimizePM.addPass(InstCombinePass());
1036   OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1037   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
1038       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
1039       EnableMSSALoopDependency, DebugLogging));
1040 
1041   // Now that we've vectorized and unrolled loops, we may have more refined
1042   // alignment information, try to re-derive it here.
1043   OptimizePM.addPass(AlignmentFromAssumptionsPass());
1044 
1045   // Split out cold code. Splitting is done late to avoid hiding context from
1046   // other optimizations and inadvertently regressing performance. The tradeoff
1047   // is that this has a higher code size cost than splitting early.
1048   if (EnableHotColdSplit && !LTOPreLink)
1049     MPM.addPass(HotColdSplittingPass());
1050 
1051   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1052   // canonicalization pass that enables other optimizations. As a result,
1053   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1054   // result too early.
1055   OptimizePM.addPass(LoopSinkPass());
1056 
1057   // And finally clean up LCSSA form before generating code.
1058   OptimizePM.addPass(InstSimplifyPass());
1059 
1060   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1061   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1062   // flattening of blocks.
1063   OptimizePM.addPass(DivRemPairsPass());
1064 
1065   // LoopSink (and other loop passes since the last simplifyCFG) might have
1066   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1067   OptimizePM.addPass(SimplifyCFGPass());
1068 
1069   // Optimize PHIs by speculating around them when profitable. Note that this
1070   // pass needs to be run after any PRE or similar pass as it is essentially
1071   // inserting redundancies into the program. This even includes SimplifyCFG.
1072   OptimizePM.addPass(SpeculateAroundPHIsPass());
1073 
1074   if (PTO.Coroutines)
1075     OptimizePM.addPass(CoroCleanupPass());
1076 
1077   for (auto &C : OptimizerLastEPCallbacks)
1078     C(OptimizePM, Level);
1079 
1080   // Add the core optimizing pipeline.
1081   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1082 
1083   if (PTO.CallGraphProfile)
1084     MPM.addPass(CGProfilePass());
1085 
1086   // Now we need to do some global optimization transforms.
1087   // FIXME: It would seem like these should come first in the optimization
1088   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1089   // ordering here.
1090   MPM.addPass(GlobalDCEPass());
1091   MPM.addPass(ConstantMergePass());
1092 
1093   return MPM;
1094 }
1095 
1096 ModulePassManager
1097 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1098                                            bool DebugLogging, bool LTOPreLink) {
1099   assert(Level != OptimizationLevel::O0 &&
1100          "Must request optimizations for the default pipeline!");
1101 
1102   ModulePassManager MPM(DebugLogging);
1103 
1104   // Force any function attributes we want the rest of the pipeline to observe.
1105   MPM.addPass(ForceFunctionAttrsPass());
1106 
1107   // Apply module pipeline start EP callback.
1108   for (auto &C : PipelineStartEPCallbacks)
1109     C(MPM);
1110 
1111   if (PGOOpt && PGOOpt->SamplePGOSupport)
1112     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1113 
1114   // Add the core simplification pipeline.
1115   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1116                                                 DebugLogging));
1117 
1118   // Now add the optimization pipeline.
1119   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
1120 
1121   return MPM;
1122 }
1123 
1124 ModulePassManager
1125 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1126                                                 bool DebugLogging) {
1127   assert(Level != OptimizationLevel::O0 &&
1128          "Must request optimizations for the default pipeline!");
1129 
1130   ModulePassManager MPM(DebugLogging);
1131 
1132   // Force any function attributes we want the rest of the pipeline to observe.
1133   MPM.addPass(ForceFunctionAttrsPass());
1134 
1135   if (PGOOpt && PGOOpt->SamplePGOSupport)
1136     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1137 
1138   // Apply module pipeline start EP callback.
1139   for (auto &C : PipelineStartEPCallbacks)
1140     C(MPM);
1141 
1142   // If we are planning to perform ThinLTO later, we don't bloat the code with
1143   // unrolling/vectorization/... now. Just simplify the module as much as we
1144   // can.
1145   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1146                                                 DebugLogging));
1147 
1148   // Run partial inlining pass to partially inline functions that have
1149   // large bodies.
1150   // FIXME: It isn't clear whether this is really the right place to run this
1151   // in ThinLTO. Because there is another canonicalization and simplification
1152   // phase that will run after the thin link, running this here ends up with
1153   // less information than will be available later and it may grow functions in
1154   // ways that aren't beneficial.
1155   if (RunPartialInlining)
1156     MPM.addPass(PartialInlinerPass());
1157 
1158   // Reduce the size of the IR as much as possible.
1159   MPM.addPass(GlobalOptPass());
1160 
1161   // Module simplification splits coroutines, but does not fully clean up
1162   // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up
1163   // on these, we schedule the cleanup here.
1164   if (PTO.Coroutines)
1165     MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1166 
1167   return MPM;
1168 }
1169 
1170 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1171     OptimizationLevel Level, bool DebugLogging,
1172     const ModuleSummaryIndex *ImportSummary) {
1173   ModulePassManager MPM(DebugLogging);
1174 
1175   if (ImportSummary) {
1176     // These passes import type identifier resolutions for whole-program
1177     // devirtualization and CFI. They must run early because other passes may
1178     // disturb the specific instruction patterns that these passes look for,
1179     // creating dependencies on resolutions that may not appear in the summary.
1180     //
1181     // For example, GVN may transform the pattern assume(type.test) appearing in
1182     // two basic blocks into assume(phi(type.test, type.test)), which would
1183     // transform a dependency on a WPD resolution into a dependency on a type
1184     // identifier resolution for CFI.
1185     //
1186     // Also, WPD has access to more precise information than ICP and can
1187     // devirtualize more effectively, so it should operate on the IR first.
1188     //
1189     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1190     // metadata and intrinsics.
1191     MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1192     MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1193   }
1194 
1195   if (Level == OptimizationLevel::O0)
1196     return MPM;
1197 
1198   // Force any function attributes we want the rest of the pipeline to observe.
1199   MPM.addPass(ForceFunctionAttrsPass());
1200 
1201   // Add the core simplification pipeline.
1202   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1203                                                 DebugLogging));
1204 
1205   // Now add the optimization pipeline.
1206   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1207 
1208   return MPM;
1209 }
1210 
1211 ModulePassManager
1212 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1213                                             bool DebugLogging) {
1214   assert(Level != OptimizationLevel::O0 &&
1215          "Must request optimizations for the default pipeline!");
1216   // FIXME: We should use a customized pre-link pipeline!
1217   return buildPerModuleDefaultPipeline(Level, DebugLogging,
1218                                        /* LTOPreLink */ true);
1219 }
1220 
1221 ModulePassManager
1222 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1223                                      ModuleSummaryIndex *ExportSummary) {
1224   ModulePassManager MPM(DebugLogging);
1225 
1226   if (Level == OptimizationLevel::O0) {
1227     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1228     // metadata and intrinsics.
1229     MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1230     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1231     return MPM;
1232   }
1233 
1234   if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1235     // Load sample profile before running the LTO optimization pipeline.
1236     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1237                                         PGOOpt->ProfileRemappingFile,
1238                                         false /* ThinLTOPhase::PreLink */));
1239     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1240     // RequireAnalysisPass for PSI before subsequent non-module passes.
1241     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1242   }
1243 
1244   // Remove unused virtual tables to improve the quality of code generated by
1245   // whole-program devirtualization and bitset lowering.
1246   MPM.addPass(GlobalDCEPass());
1247 
1248   // Force any function attributes we want the rest of the pipeline to observe.
1249   MPM.addPass(ForceFunctionAttrsPass());
1250 
1251   // Do basic inference of function attributes from known properties of system
1252   // libraries and other oracles.
1253   MPM.addPass(InferFunctionAttrsPass());
1254 
1255   if (Level.getSpeedupLevel() > 1) {
1256     FunctionPassManager EarlyFPM(DebugLogging);
1257     EarlyFPM.addPass(CallSiteSplittingPass());
1258     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1259 
1260     // Indirect call promotion. This should promote all the targets that are
1261     // left by the earlier promotion pass that promotes intra-module targets.
1262     // This two-step promotion is to save the compile time. For LTO, it should
1263     // produce the same result as if we only do promotion here.
1264     MPM.addPass(PGOIndirectCallPromotion(
1265         true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1266     // Propagate constants at call sites into the functions they call.  This
1267     // opens opportunities for globalopt (and inlining) by substituting function
1268     // pointers passed as arguments to direct uses of functions.
1269     MPM.addPass(IPSCCPPass());
1270 
1271     // Attach metadata to indirect call sites indicating the set of functions
1272     // they may target at run-time. This should follow IPSCCP.
1273     MPM.addPass(CalledValuePropagationPass());
1274   }
1275 
1276   // Now deduce any function attributes based in the current code.
1277   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1278               PostOrderFunctionAttrsPass()));
1279 
1280   // Do RPO function attribute inference across the module to forward-propagate
1281   // attributes where applicable.
1282   // FIXME: Is this really an optimization rather than a canonicalization?
1283   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1284 
1285   // Use in-range annotations on GEP indices to split globals where beneficial.
1286   MPM.addPass(GlobalSplitPass());
1287 
1288   // Run whole program optimization of virtual call when the list of callees
1289   // is fixed.
1290   MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1291 
1292   // Stop here at -O1.
1293   if (Level == OptimizationLevel::O1) {
1294     // The LowerTypeTestsPass needs to run to lower type metadata and the
1295     // type.test intrinsics. The pass does nothing if CFI is disabled.
1296     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1297     return MPM;
1298   }
1299 
1300   // Optimize globals to try and fold them into constants.
1301   MPM.addPass(GlobalOptPass());
1302 
1303   // Promote any localized globals to SSA registers.
1304   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1305 
1306   // Linking modules together can lead to duplicate global constant, only
1307   // keep one copy of each constant.
1308   MPM.addPass(ConstantMergePass());
1309 
1310   // Remove unused arguments from functions.
1311   MPM.addPass(DeadArgumentEliminationPass());
1312 
1313   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1314   // simplification opportunities, and both can propagate functions through
1315   // function pointers.  When this happens, we often have to resolve varargs
1316   // calls, etc, so let instcombine do this.
1317   FunctionPassManager PeepholeFPM(DebugLogging);
1318   if (Level == OptimizationLevel::O3)
1319     PeepholeFPM.addPass(AggressiveInstCombinePass());
1320   PeepholeFPM.addPass(InstCombinePass());
1321   invokePeepholeEPCallbacks(PeepholeFPM, Level);
1322 
1323   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1324 
1325   // Note: historically, the PruneEH pass was run first to deduce nounwind and
1326   // generally clean up exception handling overhead. It isn't clear this is
1327   // valuable as the inliner doesn't currently care whether it is inlining an
1328   // invoke or a call.
1329   // Run the inliner now.
1330   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1331       InlinerPass(getInlineParamsFromOptLevel(Level))));
1332 
1333   // Optimize globals again after we ran the inliner.
1334   MPM.addPass(GlobalOptPass());
1335 
1336   // Garbage collect dead functions.
1337   // FIXME: Add ArgumentPromotion pass after once it's ported.
1338   MPM.addPass(GlobalDCEPass());
1339 
1340   FunctionPassManager FPM(DebugLogging);
1341   // The IPO Passes may leave cruft around. Clean up after them.
1342   FPM.addPass(InstCombinePass());
1343   invokePeepholeEPCallbacks(FPM, Level);
1344 
1345   FPM.addPass(JumpThreadingPass());
1346 
1347   // Do a post inline PGO instrumentation and use pass. This is a context
1348   // sensitive PGO pass.
1349   if (PGOOpt) {
1350     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1351       addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1352                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1353                         PGOOpt->ProfileRemappingFile);
1354     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1355       addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1356                         /* IsCS */ true, PGOOpt->ProfileFile,
1357                         PGOOpt->ProfileRemappingFile);
1358   }
1359 
1360   // Break up allocas
1361   FPM.addPass(SROA());
1362 
1363   // LTO provides additional opportunities for tailcall elimination due to
1364   // link-time inlining, and visibility of nocapture attribute.
1365   FPM.addPass(TailCallElimPass());
1366 
1367   // Run a few AA driver optimizations here and now to cleanup the code.
1368   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1369 
1370   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1371               PostOrderFunctionAttrsPass()));
1372   // FIXME: here we run IP alias analysis in the legacy PM.
1373 
1374   FunctionPassManager MainFPM;
1375 
1376   // FIXME: once we fix LoopPass Manager, add LICM here.
1377   // FIXME: once we provide support for enabling MLSM, add it here.
1378   if (RunNewGVN)
1379     MainFPM.addPass(NewGVNPass());
1380   else
1381     MainFPM.addPass(GVN());
1382 
1383   // Remove dead memcpy()'s.
1384   MainFPM.addPass(MemCpyOptPass());
1385 
1386   // Nuke dead stores.
1387   MainFPM.addPass(DSEPass());
1388 
1389   // FIXME: at this point, we run a bunch of loop passes:
1390   // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
1391   // loopVectorize. Enable them once the remaining issue with LPM
1392   // are sorted out.
1393 
1394   MainFPM.addPass(InstCombinePass());
1395   MainFPM.addPass(SimplifyCFGPass());
1396   MainFPM.addPass(SCCPPass());
1397   MainFPM.addPass(InstCombinePass());
1398   MainFPM.addPass(BDCEPass());
1399 
1400   // FIXME: We may want to run SLPVectorizer here.
1401   // After vectorization, assume intrinsics may tell us more
1402   // about pointer alignments.
1403 #if 0
1404   MainFPM.add(AlignmentFromAssumptionsPass());
1405 #endif
1406 
1407   // FIXME: Conditionally run LoadCombine here, after it's ported
1408   // (in case we still have this pass, given its questionable usefulness).
1409 
1410   MainFPM.addPass(InstCombinePass());
1411   invokePeepholeEPCallbacks(MainFPM, Level);
1412   MainFPM.addPass(JumpThreadingPass());
1413   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1414 
1415   // Create a function that performs CFI checks for cross-DSO calls with
1416   // targets in the current module.
1417   MPM.addPass(CrossDSOCFIPass());
1418 
1419   // Lower type metadata and the type.test intrinsic. This pass supports
1420   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1421   // to be run at link time if CFI is enabled. This pass does nothing if
1422   // CFI is disabled.
1423   MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1424 
1425   // Enable splitting late in the FullLTO post-link pipeline. This is done in
1426   // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1427   if (EnableHotColdSplit)
1428     MPM.addPass(HotColdSplittingPass());
1429 
1430   // Add late LTO optimization passes.
1431   // Delete basic blocks, which optimization passes may have killed.
1432   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1433 
1434   // Drop bodies of available eternally objects to improve GlobalDCE.
1435   MPM.addPass(EliminateAvailableExternallyPass());
1436 
1437   // Now that we have optimized the program, discard unreachable functions.
1438   MPM.addPass(GlobalDCEPass());
1439 
1440   // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
1441   return MPM;
1442 }
1443 
1444 AAManager PassBuilder::buildDefaultAAPipeline() {
1445   AAManager AA;
1446 
1447   // The order in which these are registered determines their priority when
1448   // being queried.
1449 
1450   // First we register the basic alias analysis that provides the majority of
1451   // per-function local AA logic. This is a stateless, on-demand local set of
1452   // AA techniques.
1453   AA.registerFunctionAnalysis<BasicAA>();
1454 
1455   // Next we query fast, specialized alias analyses that wrap IR-embedded
1456   // information about aliasing.
1457   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1458   AA.registerFunctionAnalysis<TypeBasedAA>();
1459 
1460   // Add support for querying global aliasing information when available.
1461   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1462   // analysis, all that the `AAManager` can do is query for any *cached*
1463   // results from `GlobalsAA` through a readonly proxy.
1464   AA.registerModuleAnalysis<GlobalsAA>();
1465 
1466   return AA;
1467 }
1468 
1469 static Optional<int> parseRepeatPassName(StringRef Name) {
1470   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1471     return None;
1472   int Count;
1473   if (Name.getAsInteger(0, Count) || Count <= 0)
1474     return None;
1475   return Count;
1476 }
1477 
1478 static Optional<int> parseDevirtPassName(StringRef Name) {
1479   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1480     return None;
1481   int Count;
1482   if (Name.getAsInteger(0, Count) || Count <= 0)
1483     return None;
1484   return Count;
1485 }
1486 
1487 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1488   if (!Name.consume_front(PassName))
1489     return false;
1490   // normal pass name w/o parameters == default parameters
1491   if (Name.empty())
1492     return true;
1493   return Name.startswith("<") && Name.endswith(">");
1494 }
1495 
1496 namespace {
1497 
1498 /// This performs customized parsing of pass name with parameters.
1499 ///
1500 /// We do not need parametrization of passes in textual pipeline very often,
1501 /// yet on a rare occasion ability to specify parameters right there can be
1502 /// useful.
1503 ///
1504 /// \p Name - parameterized specification of a pass from a textual pipeline
1505 /// is a string in a form of :
1506 ///      PassName '<' parameter-list '>'
1507 ///
1508 /// Parameter list is being parsed by the parser callable argument, \p Parser,
1509 /// It takes a string-ref of parameters and returns either StringError or a
1510 /// parameter list in a form of a custom parameters type, all wrapped into
1511 /// Expected<> template class.
1512 ///
1513 template <typename ParametersParseCallableT>
1514 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1515                          StringRef PassName) -> decltype(Parser(StringRef{})) {
1516   using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1517 
1518   StringRef Params = Name;
1519   if (!Params.consume_front(PassName)) {
1520     assert(false &&
1521            "unable to strip pass name from parametrized pass specification");
1522   }
1523   if (Params.empty())
1524     return ParametersT{};
1525   if (!Params.consume_front("<") || !Params.consume_back(">")) {
1526     assert(false && "invalid format for parametrized pass name");
1527   }
1528 
1529   Expected<ParametersT> Result = Parser(Params);
1530   assert((Result || Result.template errorIsA<StringError>()) &&
1531          "Pass parameter parser can only return StringErrors.");
1532   return Result;
1533 }
1534 
1535 /// Parser of parameters for LoopUnroll pass.
1536 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1537   LoopUnrollOptions UnrollOpts;
1538   while (!Params.empty()) {
1539     StringRef ParamName;
1540     std::tie(ParamName, Params) = Params.split(';');
1541     int OptLevel = StringSwitch<int>(ParamName)
1542                        .Case("O0", 0)
1543                        .Case("O1", 1)
1544                        .Case("O2", 2)
1545                        .Case("O3", 3)
1546                        .Default(-1);
1547     if (OptLevel >= 0) {
1548       UnrollOpts.setOptLevel(OptLevel);
1549       continue;
1550     }
1551     if (ParamName.consume_front("full-unroll-max=")) {
1552       int Count;
1553       if (ParamName.getAsInteger(0, Count))
1554         return make_error<StringError>(
1555             formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1556             inconvertibleErrorCode());
1557       UnrollOpts.setFullUnrollMaxCount(Count);
1558       continue;
1559     }
1560 
1561     bool Enable = !ParamName.consume_front("no-");
1562     if (ParamName == "partial") {
1563       UnrollOpts.setPartial(Enable);
1564     } else if (ParamName == "peeling") {
1565       UnrollOpts.setPeeling(Enable);
1566     } else if (ParamName == "profile-peeling") {
1567       UnrollOpts.setProfileBasedPeeling(Enable);
1568     } else if (ParamName == "runtime") {
1569       UnrollOpts.setRuntime(Enable);
1570     } else if (ParamName == "upperbound") {
1571       UnrollOpts.setUpperBound(Enable);
1572     } else {
1573       return make_error<StringError>(
1574           formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1575           inconvertibleErrorCode());
1576     }
1577   }
1578   return UnrollOpts;
1579 }
1580 
1581 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1582   MemorySanitizerOptions Result;
1583   while (!Params.empty()) {
1584     StringRef ParamName;
1585     std::tie(ParamName, Params) = Params.split(';');
1586 
1587     if (ParamName == "recover") {
1588       Result.Recover = true;
1589     } else if (ParamName == "kernel") {
1590       Result.Kernel = true;
1591     } else if (ParamName.consume_front("track-origins=")) {
1592       if (ParamName.getAsInteger(0, Result.TrackOrigins))
1593         return make_error<StringError>(
1594             formatv("invalid argument to MemorySanitizer pass track-origins "
1595                     "parameter: '{0}' ",
1596                     ParamName)
1597                 .str(),
1598             inconvertibleErrorCode());
1599     } else {
1600       return make_error<StringError>(
1601           formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1602               .str(),
1603           inconvertibleErrorCode());
1604     }
1605   }
1606   return Result;
1607 }
1608 
1609 /// Parser of parameters for SimplifyCFG pass.
1610 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1611   SimplifyCFGOptions Result;
1612   while (!Params.empty()) {
1613     StringRef ParamName;
1614     std::tie(ParamName, Params) = Params.split(';');
1615 
1616     bool Enable = !ParamName.consume_front("no-");
1617     if (ParamName == "forward-switch-cond") {
1618       Result.forwardSwitchCondToPhi(Enable);
1619     } else if (ParamName == "switch-to-lookup") {
1620       Result.convertSwitchToLookupTable(Enable);
1621     } else if (ParamName == "keep-loops") {
1622       Result.needCanonicalLoops(Enable);
1623     } else if (ParamName == "sink-common-insts") {
1624       Result.sinkCommonInsts(Enable);
1625     } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1626       APInt BonusInstThreshold;
1627       if (ParamName.getAsInteger(0, BonusInstThreshold))
1628         return make_error<StringError>(
1629             formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1630                     "parameter: '{0}' ",
1631                     ParamName).str(),
1632             inconvertibleErrorCode());
1633       Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1634     } else {
1635       return make_error<StringError>(
1636           formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1637           inconvertibleErrorCode());
1638     }
1639   }
1640   return Result;
1641 }
1642 
1643 /// Parser of parameters for LoopVectorize pass.
1644 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1645   LoopVectorizeOptions Opts;
1646   while (!Params.empty()) {
1647     StringRef ParamName;
1648     std::tie(ParamName, Params) = Params.split(';');
1649 
1650     bool Enable = !ParamName.consume_front("no-");
1651     if (ParamName == "interleave-forced-only") {
1652       Opts.setInterleaveOnlyWhenForced(Enable);
1653     } else if (ParamName == "vectorize-forced-only") {
1654       Opts.setVectorizeOnlyWhenForced(Enable);
1655     } else {
1656       return make_error<StringError>(
1657           formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1658           inconvertibleErrorCode());
1659     }
1660   }
1661   return Opts;
1662 }
1663 
1664 Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1665   bool Result = false;
1666   while (!Params.empty()) {
1667     StringRef ParamName;
1668     std::tie(ParamName, Params) = Params.split(';');
1669 
1670     bool Enable = !ParamName.consume_front("no-");
1671     if (ParamName == "nontrivial") {
1672       Result = Enable;
1673     } else {
1674       return make_error<StringError>(
1675           formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1676               .str(),
1677           inconvertibleErrorCode());
1678     }
1679   }
1680   return Result;
1681 }
1682 
1683 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
1684   bool Result = false;
1685   while (!Params.empty()) {
1686     StringRef ParamName;
1687     std::tie(ParamName, Params) = Params.split(';');
1688 
1689     bool Enable = !ParamName.consume_front("no-");
1690     if (ParamName == "split-footer-bb") {
1691       Result = Enable;
1692     } else {
1693       return make_error<StringError>(
1694           formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1695                   ParamName)
1696               .str(),
1697           inconvertibleErrorCode());
1698     }
1699   }
1700   return Result;
1701 }
1702 
1703 Expected<GVNOptions> parseGVNOptions(StringRef Params) {
1704   GVNOptions Result;
1705   while (!Params.empty()) {
1706     StringRef ParamName;
1707     std::tie(ParamName, Params) = Params.split(';');
1708 
1709     bool Enable = !ParamName.consume_front("no-");
1710     if (ParamName == "pre") {
1711       Result.setPRE(Enable);
1712     } else if (ParamName == "load-pre") {
1713       Result.setLoadPRE(Enable);
1714     } else if (ParamName == "memdep") {
1715       Result.setMemDep(Enable);
1716     } else {
1717       return make_error<StringError>(
1718           formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
1719           inconvertibleErrorCode());
1720     }
1721   }
1722   return Result;
1723 }
1724 
1725 } // namespace
1726 
1727 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1728 /// alias.
1729 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1730   return Name.startswith("default") || Name.startswith("thinlto") ||
1731          Name.startswith("lto");
1732 }
1733 
1734 /// Tests whether registered callbacks will accept a given pass name.
1735 ///
1736 /// When parsing a pipeline text, the type of the outermost pipeline may be
1737 /// omitted, in which case the type is automatically determined from the first
1738 /// pass name in the text. This may be a name that is handled through one of the
1739 /// callbacks. We check this through the oridinary parsing callbacks by setting
1740 /// up a dummy PassManager in order to not force the client to also handle this
1741 /// type of query.
1742 template <typename PassManagerT, typename CallbacksT>
1743 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1744   if (!Callbacks.empty()) {
1745     PassManagerT DummyPM;
1746     for (auto &CB : Callbacks)
1747       if (CB(Name, DummyPM, {}))
1748         return true;
1749   }
1750   return false;
1751 }
1752 
1753 template <typename CallbacksT>
1754 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1755   // Manually handle aliases for pre-configured pipeline fragments.
1756   if (startsWithDefaultPipelineAliasPrefix(Name))
1757     return DefaultAliasRegex.match(Name);
1758 
1759   // Explicitly handle pass manager names.
1760   if (Name == "module")
1761     return true;
1762   if (Name == "cgscc")
1763     return true;
1764   if (Name == "function")
1765     return true;
1766 
1767   // Explicitly handle custom-parsed pass names.
1768   if (parseRepeatPassName(Name))
1769     return true;
1770 
1771 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1772   if (Name == NAME)                                                            \
1773     return true;
1774 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1775   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1776     return true;
1777 #include "PassRegistry.def"
1778 
1779   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1780 }
1781 
1782 template <typename CallbacksT>
1783 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1784   // Explicitly handle pass manager names.
1785   if (Name == "cgscc")
1786     return true;
1787   if (Name == "function")
1788     return true;
1789 
1790   // Explicitly handle custom-parsed pass names.
1791   if (parseRepeatPassName(Name))
1792     return true;
1793   if (parseDevirtPassName(Name))
1794     return true;
1795 
1796 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1797   if (Name == NAME)                                                            \
1798     return true;
1799 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1800   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1801     return true;
1802 #include "PassRegistry.def"
1803 
1804   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1805 }
1806 
1807 template <typename CallbacksT>
1808 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1809   // Explicitly handle pass manager names.
1810   if (Name == "function")
1811     return true;
1812   if (Name == "loop" || Name == "loop-mssa")
1813     return true;
1814 
1815   // Explicitly handle custom-parsed pass names.
1816   if (parseRepeatPassName(Name))
1817     return true;
1818 
1819 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1820   if (Name == NAME)                                                            \
1821     return true;
1822 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER)                   \
1823   if (checkParametrizedPassName(Name, NAME))                                   \
1824     return true;
1825 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1826   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1827     return true;
1828 #include "PassRegistry.def"
1829 
1830   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1831 }
1832 
1833 template <typename CallbacksT>
1834 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1835   // Explicitly handle pass manager names.
1836   if (Name == "loop" || Name == "loop-mssa")
1837     return true;
1838 
1839   // Explicitly handle custom-parsed pass names.
1840   if (parseRepeatPassName(Name))
1841     return true;
1842 
1843 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1844   if (Name == NAME)                                                            \
1845     return true;
1846 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER)                       \
1847   if (checkParametrizedPassName(Name, NAME))                                   \
1848     return true;
1849 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1850   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1851     return true;
1852 #include "PassRegistry.def"
1853 
1854   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1855 }
1856 
1857 Optional<std::vector<PassBuilder::PipelineElement>>
1858 PassBuilder::parsePipelineText(StringRef Text) {
1859   std::vector<PipelineElement> ResultPipeline;
1860 
1861   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1862       &ResultPipeline};
1863   for (;;) {
1864     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1865     size_t Pos = Text.find_first_of(",()");
1866     Pipeline.push_back({Text.substr(0, Pos), {}});
1867 
1868     // If we have a single terminating name, we're done.
1869     if (Pos == Text.npos)
1870       break;
1871 
1872     char Sep = Text[Pos];
1873     Text = Text.substr(Pos + 1);
1874     if (Sep == ',')
1875       // Just a name ending in a comma, continue.
1876       continue;
1877 
1878     if (Sep == '(') {
1879       // Push the inner pipeline onto the stack to continue processing.
1880       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1881       continue;
1882     }
1883 
1884     assert(Sep == ')' && "Bogus separator!");
1885     // When handling the close parenthesis, we greedily consume them to avoid
1886     // empty strings in the pipeline.
1887     do {
1888       // If we try to pop the outer pipeline we have unbalanced parentheses.
1889       if (PipelineStack.size() == 1)
1890         return None;
1891 
1892       PipelineStack.pop_back();
1893     } while (Text.consume_front(")"));
1894 
1895     // Check if we've finished parsing.
1896     if (Text.empty())
1897       break;
1898 
1899     // Otherwise, the end of an inner pipeline always has to be followed by
1900     // a comma, and then we can continue.
1901     if (!Text.consume_front(","))
1902       return None;
1903   }
1904 
1905   if (PipelineStack.size() > 1)
1906     // Unbalanced paretheses.
1907     return None;
1908 
1909   assert(PipelineStack.back() == &ResultPipeline &&
1910          "Wrong pipeline at the bottom of the stack!");
1911   return {std::move(ResultPipeline)};
1912 }
1913 
1914 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1915                                    const PipelineElement &E,
1916                                    bool VerifyEachPass, bool DebugLogging) {
1917   auto &Name = E.Name;
1918   auto &InnerPipeline = E.InnerPipeline;
1919 
1920   // First handle complex passes like the pass managers which carry pipelines.
1921   if (!InnerPipeline.empty()) {
1922     if (Name == "module") {
1923       ModulePassManager NestedMPM(DebugLogging);
1924       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1925                                              VerifyEachPass, DebugLogging))
1926         return Err;
1927       MPM.addPass(std::move(NestedMPM));
1928       return Error::success();
1929     }
1930     if (Name == "cgscc") {
1931       CGSCCPassManager CGPM(DebugLogging);
1932       if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1933                                             DebugLogging))
1934         return Err;
1935       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1936       return Error::success();
1937     }
1938     if (Name == "function") {
1939       FunctionPassManager FPM(DebugLogging);
1940       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1941                                                VerifyEachPass, DebugLogging))
1942         return Err;
1943       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1944       return Error::success();
1945     }
1946     if (auto Count = parseRepeatPassName(Name)) {
1947       ModulePassManager NestedMPM(DebugLogging);
1948       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1949                                              VerifyEachPass, DebugLogging))
1950         return Err;
1951       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1952       return Error::success();
1953     }
1954 
1955     for (auto &C : ModulePipelineParsingCallbacks)
1956       if (C(Name, MPM, InnerPipeline))
1957         return Error::success();
1958 
1959     // Normal passes can't have pipelines.
1960     return make_error<StringError>(
1961         formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1962         inconvertibleErrorCode());
1963     ;
1964   }
1965 
1966   // Manually handle aliases for pre-configured pipeline fragments.
1967   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1968     SmallVector<StringRef, 3> Matches;
1969     if (!DefaultAliasRegex.match(Name, &Matches))
1970       return make_error<StringError>(
1971           formatv("unknown default pipeline alias '{0}'", Name).str(),
1972           inconvertibleErrorCode());
1973 
1974     assert(Matches.size() == 3 && "Must capture two matched strings!");
1975 
1976     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1977                               .Case("O0", OptimizationLevel::O0)
1978                               .Case("O1", OptimizationLevel::O1)
1979                               .Case("O2", OptimizationLevel::O2)
1980                               .Case("O3", OptimizationLevel::O3)
1981                               .Case("Os", OptimizationLevel::Os)
1982                               .Case("Oz", OptimizationLevel::Oz);
1983     if (L == OptimizationLevel::O0) {
1984       // Add instrumentation PGO passes -- at O0 we can still do PGO.
1985       if (PGOOpt && Matches[1] != "thinlto" &&
1986           (PGOOpt->Action == PGOOptions::IRInstr ||
1987            PGOOpt->Action == PGOOptions::IRUse))
1988         addPGOInstrPassesForO0(
1989             MPM, DebugLogging,
1990             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1991             /* IsCS */ false, PGOOpt->ProfileFile,
1992             PGOOpt->ProfileRemappingFile);
1993 
1994       // For IR that makes use of coroutines intrinsics, coroutine passes must
1995       // be run, even at -O0.
1996       if (PTO.Coroutines) {
1997         MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1998 
1999         CGSCCPassManager CGPM(DebugLogging);
2000         CGPM.addPass(CoroSplitPass());
2001         CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
2002         MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
2003 
2004         MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
2005       }
2006 
2007       // Do nothing else at all!
2008       return Error::success();
2009     }
2010 
2011     // This is consistent with old pass manager invoked via opt, but
2012     // inconsistent with clang. Clang doesn't enable loop vectorization
2013     // but does enable slp vectorization at Oz.
2014     PTO.LoopVectorization =
2015         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
2016     PTO.SLPVectorization =
2017         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
2018 
2019     if (Matches[1] == "default") {
2020       MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
2021     } else if (Matches[1] == "thinlto-pre-link") {
2022       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
2023     } else if (Matches[1] == "thinlto") {
2024       MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
2025     } else if (Matches[1] == "lto-pre-link") {
2026       MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
2027     } else {
2028       assert(Matches[1] == "lto" && "Not one of the matched options!");
2029       MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
2030     }
2031     return Error::success();
2032   }
2033 
2034   // Finally expand the basic registered passes from the .inc file.
2035 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
2036   if (Name == NAME) {                                                          \
2037     MPM.addPass(CREATE_PASS);                                                  \
2038     return Error::success();                                                   \
2039   }
2040 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
2041   if (Name == "require<" NAME ">") {                                           \
2042     MPM.addPass(                                                               \
2043         RequireAnalysisPass<                                                   \
2044             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
2045     return Error::success();                                                   \
2046   }                                                                            \
2047   if (Name == "invalidate<" NAME ">") {                                        \
2048     MPM.addPass(InvalidateAnalysisPass<                                        \
2049                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2050     return Error::success();                                                   \
2051   }
2052 #include "PassRegistry.def"
2053 
2054   for (auto &C : ModulePipelineParsingCallbacks)
2055     if (C(Name, MPM, InnerPipeline))
2056       return Error::success();
2057   return make_error<StringError>(
2058       formatv("unknown module pass '{0}'", Name).str(),
2059       inconvertibleErrorCode());
2060 }
2061 
2062 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
2063                                   const PipelineElement &E, bool VerifyEachPass,
2064                                   bool DebugLogging) {
2065   auto &Name = E.Name;
2066   auto &InnerPipeline = E.InnerPipeline;
2067 
2068   // First handle complex passes like the pass managers which carry pipelines.
2069   if (!InnerPipeline.empty()) {
2070     if (Name == "cgscc") {
2071       CGSCCPassManager NestedCGPM(DebugLogging);
2072       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
2073                                             VerifyEachPass, DebugLogging))
2074         return Err;
2075       // Add the nested pass manager with the appropriate adaptor.
2076       CGPM.addPass(std::move(NestedCGPM));
2077       return Error::success();
2078     }
2079     if (Name == "function") {
2080       FunctionPassManager FPM(DebugLogging);
2081       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
2082                                                VerifyEachPass, DebugLogging))
2083         return Err;
2084       // Add the nested pass manager with the appropriate adaptor.
2085       CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
2086       return Error::success();
2087     }
2088     if (auto Count = parseRepeatPassName(Name)) {
2089       CGSCCPassManager NestedCGPM(DebugLogging);
2090       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
2091                                             VerifyEachPass, DebugLogging))
2092         return Err;
2093       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
2094       return Error::success();
2095     }
2096     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
2097       CGSCCPassManager NestedCGPM(DebugLogging);
2098       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
2099                                             VerifyEachPass, DebugLogging))
2100         return Err;
2101       CGPM.addPass(
2102           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
2103       return Error::success();
2104     }
2105 
2106     for (auto &C : CGSCCPipelineParsingCallbacks)
2107       if (C(Name, CGPM, InnerPipeline))
2108         return Error::success();
2109 
2110     // Normal passes can't have pipelines.
2111     return make_error<StringError>(
2112         formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
2113         inconvertibleErrorCode());
2114   }
2115 
2116 // Now expand the basic registered passes from the .inc file.
2117 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
2118   if (Name == NAME) {                                                          \
2119     CGPM.addPass(CREATE_PASS);                                                 \
2120     return Error::success();                                                   \
2121   }
2122 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
2123   if (Name == "require<" NAME ">") {                                           \
2124     CGPM.addPass(RequireAnalysisPass<                                          \
2125                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
2126                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
2127                  CGSCCUpdateResult &>());                                      \
2128     return Error::success();                                                   \
2129   }                                                                            \
2130   if (Name == "invalidate<" NAME ">") {                                        \
2131     CGPM.addPass(InvalidateAnalysisPass<                                       \
2132                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
2133     return Error::success();                                                   \
2134   }
2135 #include "PassRegistry.def"
2136 
2137   for (auto &C : CGSCCPipelineParsingCallbacks)
2138     if (C(Name, CGPM, InnerPipeline))
2139       return Error::success();
2140   return make_error<StringError>(
2141       formatv("unknown cgscc pass '{0}'", Name).str(),
2142       inconvertibleErrorCode());
2143 }
2144 
2145 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
2146                                      const PipelineElement &E,
2147                                      bool VerifyEachPass, bool DebugLogging) {
2148   auto &Name = E.Name;
2149   auto &InnerPipeline = E.InnerPipeline;
2150 
2151   // First handle complex passes like the pass managers which carry pipelines.
2152   if (!InnerPipeline.empty()) {
2153     if (Name == "function") {
2154       FunctionPassManager NestedFPM(DebugLogging);
2155       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2156                                                VerifyEachPass, DebugLogging))
2157         return Err;
2158       // Add the nested pass manager with the appropriate adaptor.
2159       FPM.addPass(std::move(NestedFPM));
2160       return Error::success();
2161     }
2162     if (Name == "loop" || Name == "loop-mssa") {
2163       LoopPassManager LPM(DebugLogging);
2164       if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2165                                            DebugLogging))
2166         return Err;
2167       // Add the nested pass manager with the appropriate adaptor.
2168       bool UseMemorySSA = (Name == "loop-mssa");
2169       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2170                                                   DebugLogging));
2171       return Error::success();
2172     }
2173     if (auto Count = parseRepeatPassName(Name)) {
2174       FunctionPassManager NestedFPM(DebugLogging);
2175       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2176                                                VerifyEachPass, DebugLogging))
2177         return Err;
2178       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
2179       return Error::success();
2180     }
2181 
2182     for (auto &C : FunctionPipelineParsingCallbacks)
2183       if (C(Name, FPM, InnerPipeline))
2184         return Error::success();
2185 
2186     // Normal passes can't have pipelines.
2187     return make_error<StringError>(
2188         formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2189         inconvertibleErrorCode());
2190   }
2191 
2192 // Now expand the basic registered passes from the .inc file.
2193 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
2194   if (Name == NAME) {                                                          \
2195     FPM.addPass(CREATE_PASS);                                                  \
2196     return Error::success();                                                   \
2197   }
2198 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER)                   \
2199   if (checkParametrizedPassName(Name, NAME)) {                                 \
2200     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2201     if (!Params)                                                               \
2202       return Params.takeError();                                               \
2203     FPM.addPass(CREATE_PASS(Params.get()));                                    \
2204     return Error::success();                                                   \
2205   }
2206 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
2207   if (Name == "require<" NAME ">") {                                           \
2208     FPM.addPass(                                                               \
2209         RequireAnalysisPass<                                                   \
2210             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
2211     return Error::success();                                                   \
2212   }                                                                            \
2213   if (Name == "invalidate<" NAME ">") {                                        \
2214     FPM.addPass(InvalidateAnalysisPass<                                        \
2215                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2216     return Error::success();                                                   \
2217   }
2218 #include "PassRegistry.def"
2219 
2220   for (auto &C : FunctionPipelineParsingCallbacks)
2221     if (C(Name, FPM, InnerPipeline))
2222       return Error::success();
2223   return make_error<StringError>(
2224       formatv("unknown function pass '{0}'", Name).str(),
2225       inconvertibleErrorCode());
2226 }
2227 
2228 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2229                                  bool VerifyEachPass, bool DebugLogging) {
2230   StringRef Name = E.Name;
2231   auto &InnerPipeline = E.InnerPipeline;
2232 
2233   // First handle complex passes like the pass managers which carry pipelines.
2234   if (!InnerPipeline.empty()) {
2235     if (Name == "loop") {
2236       LoopPassManager NestedLPM(DebugLogging);
2237       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2238                                            VerifyEachPass, DebugLogging))
2239         return Err;
2240       // Add the nested pass manager with the appropriate adaptor.
2241       LPM.addPass(std::move(NestedLPM));
2242       return Error::success();
2243     }
2244     if (auto Count = parseRepeatPassName(Name)) {
2245       LoopPassManager NestedLPM(DebugLogging);
2246       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2247                                            VerifyEachPass, DebugLogging))
2248         return Err;
2249       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
2250       return Error::success();
2251     }
2252 
2253     for (auto &C : LoopPipelineParsingCallbacks)
2254       if (C(Name, LPM, InnerPipeline))
2255         return Error::success();
2256 
2257     // Normal passes can't have pipelines.
2258     return make_error<StringError>(
2259         formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2260         inconvertibleErrorCode());
2261   }
2262 
2263 // Now expand the basic registered passes from the .inc file.
2264 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
2265   if (Name == NAME) {                                                          \
2266     LPM.addPass(CREATE_PASS);                                                  \
2267     return Error::success();                                                   \
2268   }
2269 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER)                       \
2270   if (checkParametrizedPassName(Name, NAME)) {                                 \
2271     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
2272     if (!Params)                                                               \
2273       return Params.takeError();                                               \
2274     LPM.addPass(CREATE_PASS(Params.get()));                                    \
2275     return Error::success();                                                   \
2276   }
2277 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
2278   if (Name == "require<" NAME ">") {                                           \
2279     LPM.addPass(RequireAnalysisPass<                                           \
2280                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
2281                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
2282                 LPMUpdater &>());                                              \
2283     return Error::success();                                                   \
2284   }                                                                            \
2285   if (Name == "invalidate<" NAME ">") {                                        \
2286     LPM.addPass(InvalidateAnalysisPass<                                        \
2287                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
2288     return Error::success();                                                   \
2289   }
2290 #include "PassRegistry.def"
2291 
2292   for (auto &C : LoopPipelineParsingCallbacks)
2293     if (C(Name, LPM, InnerPipeline))
2294       return Error::success();
2295   return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2296                                  inconvertibleErrorCode());
2297 }
2298 
2299 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
2300 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
2301   if (Name == NAME) {                                                          \
2302     AA.registerModuleAnalysis<                                                 \
2303         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
2304     return true;                                                               \
2305   }
2306 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
2307   if (Name == NAME) {                                                          \
2308     AA.registerFunctionAnalysis<                                               \
2309         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
2310     return true;                                                               \
2311   }
2312 #include "PassRegistry.def"
2313 
2314   for (auto &C : AAParsingCallbacks)
2315     if (C(Name, AA))
2316       return true;
2317   return false;
2318 }
2319 
2320 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
2321                                          ArrayRef<PipelineElement> Pipeline,
2322                                          bool VerifyEachPass,
2323                                          bool DebugLogging) {
2324   for (const auto &Element : Pipeline) {
2325     if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2326       return Err;
2327     // FIXME: No verifier support for Loop passes!
2328   }
2329   return Error::success();
2330 }
2331 
2332 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2333                                              ArrayRef<PipelineElement> Pipeline,
2334                                              bool VerifyEachPass,
2335                                              bool DebugLogging) {
2336   for (const auto &Element : Pipeline) {
2337     if (auto Err =
2338             parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2339       return Err;
2340     if (VerifyEachPass)
2341       FPM.addPass(VerifierPass());
2342   }
2343   return Error::success();
2344 }
2345 
2346 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2347                                           ArrayRef<PipelineElement> Pipeline,
2348                                           bool VerifyEachPass,
2349                                           bool DebugLogging) {
2350   for (const auto &Element : Pipeline) {
2351     if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2352       return Err;
2353     // FIXME: No verifier support for CGSCC passes!
2354   }
2355   return Error::success();
2356 }
2357 
2358 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2359                                        FunctionAnalysisManager &FAM,
2360                                        CGSCCAnalysisManager &CGAM,
2361                                        ModuleAnalysisManager &MAM) {
2362   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2363   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
2364   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2365   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2366   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2367   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2368   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2369 }
2370 
2371 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2372                                            ArrayRef<PipelineElement> Pipeline,
2373                                            bool VerifyEachPass,
2374                                            bool DebugLogging) {
2375   for (const auto &Element : Pipeline) {
2376     if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2377       return Err;
2378     if (VerifyEachPass)
2379       MPM.addPass(VerifierPass());
2380   }
2381   return Error::success();
2382 }
2383 
2384 // Primary pass pipeline description parsing routine for a \c ModulePassManager
2385 // FIXME: Should this routine accept a TargetMachine or require the caller to
2386 // pre-populate the analysis managers with target-specific stuff?
2387 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2388                                      StringRef PipelineText,
2389                                      bool VerifyEachPass, bool DebugLogging) {
2390   auto Pipeline = parsePipelineText(PipelineText);
2391   if (!Pipeline || Pipeline->empty())
2392     return make_error<StringError>(
2393         formatv("invalid pipeline '{0}'", PipelineText).str(),
2394         inconvertibleErrorCode());
2395 
2396   // If the first name isn't at the module layer, wrap the pipeline up
2397   // automatically.
2398   StringRef FirstName = Pipeline->front().Name;
2399 
2400   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2401     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
2402       Pipeline = {{"cgscc", std::move(*Pipeline)}};
2403     } else if (isFunctionPassName(FirstName,
2404                                   FunctionPipelineParsingCallbacks)) {
2405       Pipeline = {{"function", std::move(*Pipeline)}};
2406     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
2407       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
2408     } else {
2409       for (auto &C : TopLevelPipelineParsingCallbacks)
2410         if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2411           return Error::success();
2412 
2413       // Unknown pass or pipeline name!
2414       auto &InnerPipeline = Pipeline->front().InnerPipeline;
2415       return make_error<StringError>(
2416           formatv("unknown {0} name '{1}'",
2417                   (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2418               .str(),
2419           inconvertibleErrorCode());
2420     }
2421   }
2422 
2423   if (auto Err =
2424           parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2425     return Err;
2426   return Error::success();
2427 }
2428 
2429 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
2430 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2431                                      StringRef PipelineText,
2432                                      bool VerifyEachPass, bool DebugLogging) {
2433   auto Pipeline = parsePipelineText(PipelineText);
2434   if (!Pipeline || Pipeline->empty())
2435     return make_error<StringError>(
2436         formatv("invalid pipeline '{0}'", PipelineText).str(),
2437         inconvertibleErrorCode());
2438 
2439   StringRef FirstName = Pipeline->front().Name;
2440   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
2441     return make_error<StringError>(
2442         formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2443                 PipelineText)
2444             .str(),
2445         inconvertibleErrorCode());
2446 
2447   if (auto Err =
2448           parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2449     return Err;
2450   return Error::success();
2451 }
2452 
2453 // Primary pass pipeline description parsing routine for a \c
2454 // FunctionPassManager
2455 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2456                                      StringRef PipelineText,
2457                                      bool VerifyEachPass, bool DebugLogging) {
2458   auto Pipeline = parsePipelineText(PipelineText);
2459   if (!Pipeline || Pipeline->empty())
2460     return make_error<StringError>(
2461         formatv("invalid pipeline '{0}'", PipelineText).str(),
2462         inconvertibleErrorCode());
2463 
2464   StringRef FirstName = Pipeline->front().Name;
2465   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
2466     return make_error<StringError>(
2467         formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2468                 PipelineText)
2469             .str(),
2470         inconvertibleErrorCode());
2471 
2472   if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2473                                            DebugLogging))
2474     return Err;
2475   return Error::success();
2476 }
2477 
2478 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2479 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2480                                      StringRef PipelineText,
2481                                      bool VerifyEachPass, bool DebugLogging) {
2482   auto Pipeline = parsePipelineText(PipelineText);
2483   if (!Pipeline || Pipeline->empty())
2484     return make_error<StringError>(
2485         formatv("invalid pipeline '{0}'", PipelineText).str(),
2486         inconvertibleErrorCode());
2487 
2488   if (auto Err =
2489           parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2490     return Err;
2491 
2492   return Error::success();
2493 }
2494 
2495 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
2496   // If the pipeline just consists of the word 'default' just replace the AA
2497   // manager with our default one.
2498   if (PipelineText == "default") {
2499     AA = buildDefaultAAPipeline();
2500     return Error::success();
2501   }
2502 
2503   while (!PipelineText.empty()) {
2504     StringRef Name;
2505     std::tie(Name, PipelineText) = PipelineText.split(',');
2506     if (!parseAAPassName(AA, Name))
2507       return make_error<StringError>(
2508           formatv("unknown alias analysis name '{0}'", Name).str(),
2509           inconvertibleErrorCode());
2510   }
2511 
2512   return Error::success();
2513 }
2514