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