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