xref: /freebsd/contrib/llvm-project/llvm/lib/Passes/PassBuilder.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===- Parsing and selection 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/AliasAnalysisEvaluator.h"
20 #include "llvm/Analysis/AliasSetTracker.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/CostModel.h"
31 #include "llvm/Analysis/CycleAnalysis.h"
32 #include "llvm/Analysis/DDG.h"
33 #include "llvm/Analysis/DDGPrinter.h"
34 #include "llvm/Analysis/Delinearization.h"
35 #include "llvm/Analysis/DemandedBits.h"
36 #include "llvm/Analysis/DependenceAnalysis.h"
37 #include "llvm/Analysis/DivergenceAnalysis.h"
38 #include "llvm/Analysis/DomPrinter.h"
39 #include "llvm/Analysis/DominanceFrontier.h"
40 #include "llvm/Analysis/FunctionPropertiesAnalysis.h"
41 #include "llvm/Analysis/GlobalsModRef.h"
42 #include "llvm/Analysis/IRSimilarityIdentifier.h"
43 #include "llvm/Analysis/IVUsers.h"
44 #include "llvm/Analysis/InlineAdvisor.h"
45 #include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
46 #include "llvm/Analysis/InstCount.h"
47 #include "llvm/Analysis/LazyCallGraph.h"
48 #include "llvm/Analysis/LazyValueInfo.h"
49 #include "llvm/Analysis/Lint.h"
50 #include "llvm/Analysis/LoopAccessAnalysis.h"
51 #include "llvm/Analysis/LoopCacheAnalysis.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopNestAnalysis.h"
54 #include "llvm/Analysis/MemDerefPrinter.h"
55 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
56 #include "llvm/Analysis/MemorySSA.h"
57 #include "llvm/Analysis/ModuleDebugInfoPrinter.h"
58 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
59 #include "llvm/Analysis/MustExecute.h"
60 #include "llvm/Analysis/ObjCARCAliasAnalysis.h"
61 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
62 #include "llvm/Analysis/PhiValues.h"
63 #include "llvm/Analysis/PostDominators.h"
64 #include "llvm/Analysis/ProfileSummaryInfo.h"
65 #include "llvm/Analysis/RegionInfo.h"
66 #include "llvm/Analysis/ScalarEvolution.h"
67 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
68 #include "llvm/Analysis/ScopedNoAliasAA.h"
69 #include "llvm/Analysis/StackLifetime.h"
70 #include "llvm/Analysis/StackSafetyAnalysis.h"
71 #include "llvm/Analysis/TargetLibraryInfo.h"
72 #include "llvm/Analysis/TargetTransformInfo.h"
73 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/IRPrintingPasses.h"
76 #include "llvm/IR/PassManager.h"
77 #include "llvm/IR/PrintPasses.h"
78 #include "llvm/IR/SafepointIRVerifier.h"
79 #include "llvm/IR/Verifier.h"
80 #include "llvm/Support/CommandLine.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/FormatVariadic.h"
84 #include "llvm/Support/Regex.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
87 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
88 #include "llvm/Transforms/Coroutines/CoroEarly.h"
89 #include "llvm/Transforms/Coroutines/CoroElide.h"
90 #include "llvm/Transforms/Coroutines/CoroSplit.h"
91 #include "llvm/Transforms/IPO/AlwaysInliner.h"
92 #include "llvm/Transforms/IPO/Annotation2Metadata.h"
93 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
94 #include "llvm/Transforms/IPO/Attributor.h"
95 #include "llvm/Transforms/IPO/BlockExtractor.h"
96 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
97 #include "llvm/Transforms/IPO/ConstantMerge.h"
98 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
99 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
100 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
101 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
102 #include "llvm/Transforms/IPO/FunctionAttrs.h"
103 #include "llvm/Transforms/IPO/FunctionImport.h"
104 #include "llvm/Transforms/IPO/GlobalDCE.h"
105 #include "llvm/Transforms/IPO/GlobalOpt.h"
106 #include "llvm/Transforms/IPO/GlobalSplit.h"
107 #include "llvm/Transforms/IPO/HotColdSplitting.h"
108 #include "llvm/Transforms/IPO/IROutliner.h"
109 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
110 #include "llvm/Transforms/IPO/Inliner.h"
111 #include "llvm/Transforms/IPO/Internalize.h"
112 #include "llvm/Transforms/IPO/LoopExtractor.h"
113 #include "llvm/Transforms/IPO/LowerTypeTests.h"
114 #include "llvm/Transforms/IPO/MergeFunctions.h"
115 #include "llvm/Transforms/IPO/ModuleInliner.h"
116 #include "llvm/Transforms/IPO/OpenMPOpt.h"
117 #include "llvm/Transforms/IPO/PartialInlining.h"
118 #include "llvm/Transforms/IPO/SCCP.h"
119 #include "llvm/Transforms/IPO/SampleProfile.h"
120 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
121 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
122 #include "llvm/Transforms/IPO/StripSymbols.h"
123 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
124 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
125 #include "llvm/Transforms/InstCombine/InstCombine.h"
126 #include "llvm/Transforms/Instrumentation.h"
127 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
128 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
129 #include "llvm/Transforms/Instrumentation/CGProfile.h"
130 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
131 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
132 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
133 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
134 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
135 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
136 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
137 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
138 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
139 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
140 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
141 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
142 #include "llvm/Transforms/ObjCARC.h"
143 #include "llvm/Transforms/Scalar/ADCE.h"
144 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
145 #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
146 #include "llvm/Transforms/Scalar/BDCE.h"
147 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
148 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
149 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
150 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
151 #include "llvm/Transforms/Scalar/DCE.h"
152 #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
153 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
154 #include "llvm/Transforms/Scalar/DivRemPairs.h"
155 #include "llvm/Transforms/Scalar/EarlyCSE.h"
156 #include "llvm/Transforms/Scalar/FlattenCFG.h"
157 #include "llvm/Transforms/Scalar/Float2Int.h"
158 #include "llvm/Transforms/Scalar/GVN.h"
159 #include "llvm/Transforms/Scalar/GuardWidening.h"
160 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
161 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
162 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
163 #include "llvm/Transforms/Scalar/InferAddressSpaces.h"
164 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
165 #include "llvm/Transforms/Scalar/JumpThreading.h"
166 #include "llvm/Transforms/Scalar/LICM.h"
167 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
168 #include "llvm/Transforms/Scalar/LoopBoundSplit.h"
169 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
170 #include "llvm/Transforms/Scalar/LoopDeletion.h"
171 #include "llvm/Transforms/Scalar/LoopDistribute.h"
172 #include "llvm/Transforms/Scalar/LoopFlatten.h"
173 #include "llvm/Transforms/Scalar/LoopFuse.h"
174 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
175 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
176 #include "llvm/Transforms/Scalar/LoopInterchange.h"
177 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
178 #include "llvm/Transforms/Scalar/LoopPassManager.h"
179 #include "llvm/Transforms/Scalar/LoopPredication.h"
180 #include "llvm/Transforms/Scalar/LoopReroll.h"
181 #include "llvm/Transforms/Scalar/LoopRotation.h"
182 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
183 #include "llvm/Transforms/Scalar/LoopSink.h"
184 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
185 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
186 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
187 #include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
188 #include "llvm/Transforms/Scalar/LowerAtomic.h"
189 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
190 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
191 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
192 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
193 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
194 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
195 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
196 #include "llvm/Transforms/Scalar/MergeICmps.h"
197 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
198 #include "llvm/Transforms/Scalar/NaryReassociate.h"
199 #include "llvm/Transforms/Scalar/NewGVN.h"
200 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
201 #include "llvm/Transforms/Scalar/Reassociate.h"
202 #include "llvm/Transforms/Scalar/Reg2Mem.h"
203 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
204 #include "llvm/Transforms/Scalar/SCCP.h"
205 #include "llvm/Transforms/Scalar/SROA.h"
206 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
207 #include "llvm/Transforms/Scalar/Scalarizer.h"
208 #include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
209 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
210 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
211 #include "llvm/Transforms/Scalar/Sink.h"
212 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
213 #include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
214 #include "llvm/Transforms/Scalar/StructurizeCFG.h"
215 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
216 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
217 #include "llvm/Transforms/Utils/AddDiscriminators.h"
218 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
219 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
220 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
221 #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
222 #include "llvm/Transforms/Utils/Debugify.h"
223 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
224 #include "llvm/Transforms/Utils/FixIrreducible.h"
225 #include "llvm/Transforms/Utils/HelloWorld.h"
226 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
227 #include "llvm/Transforms/Utils/InstructionNamer.h"
228 #include "llvm/Transforms/Utils/LCSSA.h"
229 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
230 #include "llvm/Transforms/Utils/LoopSimplify.h"
231 #include "llvm/Transforms/Utils/LoopVersioning.h"
232 #include "llvm/Transforms/Utils/LowerInvoke.h"
233 #include "llvm/Transforms/Utils/LowerSwitch.h"
234 #include "llvm/Transforms/Utils/Mem2Reg.h"
235 #include "llvm/Transforms/Utils/MetaRenamer.h"
236 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
237 #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
238 #include "llvm/Transforms/Utils/StripGCRelocates.h"
239 #include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
240 #include "llvm/Transforms/Utils/SymbolRewriter.h"
241 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
242 #include "llvm/Transforms/Utils/UnifyLoopExits.h"
243 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
244 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
245 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
246 #include "llvm/Transforms/Vectorize/VectorCombine.h"
247 
248 using namespace llvm;
249 
250 static const Regex DefaultAliasRegex(
251     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
252 
253 namespace llvm {
254 cl::opt<bool> PrintPipelinePasses(
255     "print-pipeline-passes",
256     cl::desc("Print a '-passes' compatible string describing the pipeline "
257              "(best-effort only)."));
258 } // namespace llvm
259 
260 namespace {
261 
262 // The following passes/analyses have custom names, otherwise their name will
263 // include `(anonymous namespace)`. These are special since they are only for
264 // testing purposes and don't live in a header file.
265 
266 /// No-op module pass which does nothing.
267 struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
268   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
269     return PreservedAnalyses::all();
270   }
271 
272   static StringRef name() { return "NoOpModulePass"; }
273 };
274 
275 /// No-op module analysis.
276 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
277   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
278   static AnalysisKey Key;
279 
280 public:
281   struct Result {};
282   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
283   static StringRef name() { return "NoOpModuleAnalysis"; }
284 };
285 
286 /// No-op CGSCC pass which does nothing.
287 struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
288   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
289                         LazyCallGraph &, CGSCCUpdateResult &UR) {
290     return PreservedAnalyses::all();
291   }
292   static StringRef name() { return "NoOpCGSCCPass"; }
293 };
294 
295 /// No-op CGSCC analysis.
296 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
297   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
298   static AnalysisKey Key;
299 
300 public:
301   struct Result {};
302   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
303     return Result();
304   }
305   static StringRef name() { return "NoOpCGSCCAnalysis"; }
306 };
307 
308 /// No-op function pass which does nothing.
309 struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
310   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
311     return PreservedAnalyses::all();
312   }
313   static StringRef name() { return "NoOpFunctionPass"; }
314 };
315 
316 /// No-op function analysis.
317 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
318   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
319   static AnalysisKey Key;
320 
321 public:
322   struct Result {};
323   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
324   static StringRef name() { return "NoOpFunctionAnalysis"; }
325 };
326 
327 /// No-op loop nest pass which does nothing.
328 struct NoOpLoopNestPass : PassInfoMixin<NoOpLoopNestPass> {
329   PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &,
330                         LoopStandardAnalysisResults &, LPMUpdater &) {
331     return PreservedAnalyses::all();
332   }
333   static StringRef name() { return "NoOpLoopNestPass"; }
334 };
335 
336 /// No-op loop pass which does nothing.
337 struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
338   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
339                         LoopStandardAnalysisResults &, LPMUpdater &) {
340     return PreservedAnalyses::all();
341   }
342   static StringRef name() { return "NoOpLoopPass"; }
343 };
344 
345 /// No-op loop analysis.
346 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
347   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
348   static AnalysisKey Key;
349 
350 public:
351   struct Result {};
352   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
353     return Result();
354   }
355   static StringRef name() { return "NoOpLoopAnalysis"; }
356 };
357 
358 AnalysisKey NoOpModuleAnalysis::Key;
359 AnalysisKey NoOpCGSCCAnalysis::Key;
360 AnalysisKey NoOpFunctionAnalysis::Key;
361 AnalysisKey NoOpLoopAnalysis::Key;
362 
363 /// Whether or not we should populate a PassInstrumentationCallbacks's class to
364 /// pass name map.
365 ///
366 /// This is for optimization purposes so we don't populate it if we never use
367 /// it. This should be updated if new pass instrumentation wants to use the map.
368 /// We currently only use this for --print-before/after.
369 bool shouldPopulateClassToPassNames() {
370   return PrintPipelinePasses || !printBeforePasses().empty() ||
371          !printAfterPasses().empty();
372 }
373 
374 } // namespace
375 
376 PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
377                          Optional<PGOOptions> PGOOpt,
378                          PassInstrumentationCallbacks *PIC)
379     : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
380   if (TM)
381     TM->registerPassBuilderCallbacks(*this);
382   if (PIC && shouldPopulateClassToPassNames()) {
383 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
384   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
385 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
386   PIC->addClassToPassName(CLASS, NAME);
387 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
388   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
389 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
390   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
391 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
392   PIC->addClassToPassName(CLASS, NAME);
393 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
394   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
395 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
396   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
397 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
398   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
399 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
400   PIC->addClassToPassName(CLASS, NAME);
401 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
402   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
403 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
404   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
405 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
406   PIC->addClassToPassName(CLASS, NAME);
407 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
408   PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
409 #include "PassRegistry.def"
410   }
411 }
412 
413 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
414 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
415   MAM.registerPass([&] { return CREATE_PASS; });
416 #include "PassRegistry.def"
417 
418   for (auto &C : ModuleAnalysisRegistrationCallbacks)
419     C(MAM);
420 }
421 
422 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
423 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
424   CGAM.registerPass([&] { return CREATE_PASS; });
425 #include "PassRegistry.def"
426 
427   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
428     C(CGAM);
429 }
430 
431 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
432   // We almost always want the default alias analysis pipeline.
433   // If a user wants a different one, they can register their own before calling
434   // registerFunctionAnalyses().
435   FAM.registerPass([&] { return buildDefaultAAPipeline(); });
436 
437 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
438   FAM.registerPass([&] { return CREATE_PASS; });
439 #include "PassRegistry.def"
440 
441   for (auto &C : FunctionAnalysisRegistrationCallbacks)
442     C(FAM);
443 }
444 
445 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
446 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
447   LAM.registerPass([&] { return CREATE_PASS; });
448 #include "PassRegistry.def"
449 
450   for (auto &C : LoopAnalysisRegistrationCallbacks)
451     C(LAM);
452 }
453 
454 static Optional<int> parseRepeatPassName(StringRef Name) {
455   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
456     return None;
457   int Count;
458   if (Name.getAsInteger(0, Count) || Count <= 0)
459     return None;
460   return Count;
461 }
462 
463 static Optional<int> parseDevirtPassName(StringRef Name) {
464   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
465     return None;
466   int Count;
467   if (Name.getAsInteger(0, Count) || Count < 0)
468     return None;
469   return Count;
470 }
471 
472 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
473   if (!Name.consume_front(PassName))
474     return false;
475   // normal pass name w/o parameters == default parameters
476   if (Name.empty())
477     return true;
478   return Name.startswith("<") && Name.endswith(">");
479 }
480 
481 namespace {
482 
483 /// This performs customized parsing of pass name with parameters.
484 ///
485 /// We do not need parametrization of passes in textual pipeline very often,
486 /// yet on a rare occasion ability to specify parameters right there can be
487 /// useful.
488 ///
489 /// \p Name - parameterized specification of a pass from a textual pipeline
490 /// is a string in a form of :
491 ///      PassName '<' parameter-list '>'
492 ///
493 /// Parameter list is being parsed by the parser callable argument, \p Parser,
494 /// It takes a string-ref of parameters and returns either StringError or a
495 /// parameter list in a form of a custom parameters type, all wrapped into
496 /// Expected<> template class.
497 ///
498 template <typename ParametersParseCallableT>
499 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
500                          StringRef PassName) -> decltype(Parser(StringRef{})) {
501   using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
502 
503   StringRef Params = Name;
504   if (!Params.consume_front(PassName)) {
505     assert(false &&
506            "unable to strip pass name from parametrized pass specification");
507   }
508   if (!Params.empty() &&
509       (!Params.consume_front("<") || !Params.consume_back(">"))) {
510     assert(false && "invalid format for parametrized pass name");
511   }
512 
513   Expected<ParametersT> Result = Parser(Params);
514   assert((Result || Result.template errorIsA<StringError>()) &&
515          "Pass parameter parser can only return StringErrors.");
516   return Result;
517 }
518 
519 /// Parser of parameters for LoopUnroll pass.
520 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
521   LoopUnrollOptions UnrollOpts;
522   while (!Params.empty()) {
523     StringRef ParamName;
524     std::tie(ParamName, Params) = Params.split(';');
525     int OptLevel = StringSwitch<int>(ParamName)
526                        .Case("O0", 0)
527                        .Case("O1", 1)
528                        .Case("O2", 2)
529                        .Case("O3", 3)
530                        .Default(-1);
531     if (OptLevel >= 0) {
532       UnrollOpts.setOptLevel(OptLevel);
533       continue;
534     }
535     if (ParamName.consume_front("full-unroll-max=")) {
536       int Count;
537       if (ParamName.getAsInteger(0, Count))
538         return make_error<StringError>(
539             formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
540             inconvertibleErrorCode());
541       UnrollOpts.setFullUnrollMaxCount(Count);
542       continue;
543     }
544 
545     bool Enable = !ParamName.consume_front("no-");
546     if (ParamName == "partial") {
547       UnrollOpts.setPartial(Enable);
548     } else if (ParamName == "peeling") {
549       UnrollOpts.setPeeling(Enable);
550     } else if (ParamName == "profile-peeling") {
551       UnrollOpts.setProfileBasedPeeling(Enable);
552     } else if (ParamName == "runtime") {
553       UnrollOpts.setRuntime(Enable);
554     } else if (ParamName == "upperbound") {
555       UnrollOpts.setUpperBound(Enable);
556     } else {
557       return make_error<StringError>(
558           formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
559           inconvertibleErrorCode());
560     }
561   }
562   return UnrollOpts;
563 }
564 
565 Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName,
566                                      StringRef PassName) {
567   bool Result = false;
568   while (!Params.empty()) {
569     StringRef ParamName;
570     std::tie(ParamName, Params) = Params.split(';');
571 
572     if (ParamName == OptionName) {
573       Result = true;
574     } else {
575       return make_error<StringError>(
576           formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName)
577               .str(),
578           inconvertibleErrorCode());
579     }
580   }
581   return Result;
582 }
583 
584 Expected<bool> parseInlinerPassOptions(StringRef Params) {
585   return parseSinglePassOption(Params, "only-mandatory", "InlinerPass");
586 }
587 
588 Expected<bool> parseEarlyCSEPassOptions(StringRef Params) {
589   return parseSinglePassOption(Params, "memssa", "EarlyCSE");
590 }
591 
592 Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) {
593   return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter");
594 }
595 
596 Expected<bool> parseLoopExtractorPassOptions(StringRef Params) {
597   return parseSinglePassOption(Params, "single", "LoopExtractor");
598 }
599 
600 Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) {
601   return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics");
602 }
603 
604 Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) {
605   AddressSanitizerOptions Result;
606   while (!Params.empty()) {
607     StringRef ParamName;
608     std::tie(ParamName, Params) = Params.split(';');
609 
610     if (ParamName == "kernel") {
611       Result.CompileKernel = true;
612     } else {
613       return make_error<StringError>(
614           formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName)
615               .str(),
616           inconvertibleErrorCode());
617     }
618   }
619   return Result;
620 }
621 
622 Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) {
623   HWAddressSanitizerOptions Result;
624   while (!Params.empty()) {
625     StringRef ParamName;
626     std::tie(ParamName, Params) = Params.split(';');
627 
628     if (ParamName == "recover") {
629       Result.Recover = true;
630     } else if (ParamName == "kernel") {
631       Result.CompileKernel = true;
632     } else {
633       return make_error<StringError>(
634           formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName)
635               .str(),
636           inconvertibleErrorCode());
637     }
638   }
639   return Result;
640 }
641 
642 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
643   MemorySanitizerOptions Result;
644   while (!Params.empty()) {
645     StringRef ParamName;
646     std::tie(ParamName, Params) = Params.split(';');
647 
648     if (ParamName == "recover") {
649       Result.Recover = true;
650     } else if (ParamName == "kernel") {
651       Result.Kernel = true;
652     } else if (ParamName.consume_front("track-origins=")) {
653       if (ParamName.getAsInteger(0, Result.TrackOrigins))
654         return make_error<StringError>(
655             formatv("invalid argument to MemorySanitizer pass track-origins "
656                     "parameter: '{0}' ",
657                     ParamName)
658                 .str(),
659             inconvertibleErrorCode());
660     } else if (ParamName == "eager-checks") {
661       Result.EagerChecks = true;
662     } else {
663       return make_error<StringError>(
664           formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
665               .str(),
666           inconvertibleErrorCode());
667     }
668   }
669   return Result;
670 }
671 
672 /// Parser of parameters for SimplifyCFG pass.
673 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
674   SimplifyCFGOptions Result;
675   while (!Params.empty()) {
676     StringRef ParamName;
677     std::tie(ParamName, Params) = Params.split(';');
678 
679     bool Enable = !ParamName.consume_front("no-");
680     if (ParamName == "forward-switch-cond") {
681       Result.forwardSwitchCondToPhi(Enable);
682     } else if (ParamName == "switch-range-to-icmp") {
683       Result.convertSwitchRangeToICmp(Enable);
684     } else if (ParamName == "switch-to-lookup") {
685       Result.convertSwitchToLookupTable(Enable);
686     } else if (ParamName == "keep-loops") {
687       Result.needCanonicalLoops(Enable);
688     } else if (ParamName == "hoist-common-insts") {
689       Result.hoistCommonInsts(Enable);
690     } else if (ParamName == "sink-common-insts") {
691       Result.sinkCommonInsts(Enable);
692     } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
693       APInt BonusInstThreshold;
694       if (ParamName.getAsInteger(0, BonusInstThreshold))
695         return make_error<StringError>(
696             formatv("invalid argument to SimplifyCFG pass bonus-threshold "
697                     "parameter: '{0}' ",
698                     ParamName).str(),
699             inconvertibleErrorCode());
700       Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
701     } else {
702       return make_error<StringError>(
703           formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
704           inconvertibleErrorCode());
705     }
706   }
707   return Result;
708 }
709 
710 /// Parser of parameters for LoopVectorize pass.
711 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
712   LoopVectorizeOptions Opts;
713   while (!Params.empty()) {
714     StringRef ParamName;
715     std::tie(ParamName, Params) = Params.split(';');
716 
717     bool Enable = !ParamName.consume_front("no-");
718     if (ParamName == "interleave-forced-only") {
719       Opts.setInterleaveOnlyWhenForced(Enable);
720     } else if (ParamName == "vectorize-forced-only") {
721       Opts.setVectorizeOnlyWhenForced(Enable);
722     } else {
723       return make_error<StringError>(
724           formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
725           inconvertibleErrorCode());
726     }
727   }
728   return Opts;
729 }
730 
731 Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
732   std::pair<bool, bool> Result = {false, true};
733   while (!Params.empty()) {
734     StringRef ParamName;
735     std::tie(ParamName, Params) = Params.split(';');
736 
737     bool Enable = !ParamName.consume_front("no-");
738     if (ParamName == "nontrivial") {
739       Result.first = Enable;
740     } else if (ParamName == "trivial") {
741       Result.second = Enable;
742     } else {
743       return make_error<StringError>(
744           formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
745               .str(),
746           inconvertibleErrorCode());
747     }
748   }
749   return Result;
750 }
751 
752 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
753   bool Result = false;
754   while (!Params.empty()) {
755     StringRef ParamName;
756     std::tie(ParamName, Params) = Params.split(';');
757 
758     bool Enable = !ParamName.consume_front("no-");
759     if (ParamName == "split-footer-bb") {
760       Result = Enable;
761     } else {
762       return make_error<StringError>(
763           formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
764                   ParamName)
765               .str(),
766           inconvertibleErrorCode());
767     }
768   }
769   return Result;
770 }
771 
772 Expected<GVNOptions> parseGVNOptions(StringRef Params) {
773   GVNOptions Result;
774   while (!Params.empty()) {
775     StringRef ParamName;
776     std::tie(ParamName, Params) = Params.split(';');
777 
778     bool Enable = !ParamName.consume_front("no-");
779     if (ParamName == "pre") {
780       Result.setPRE(Enable);
781     } else if (ParamName == "load-pre") {
782       Result.setLoadPRE(Enable);
783     } else if (ParamName == "split-backedge-load-pre") {
784       Result.setLoadPRESplitBackedge(Enable);
785     } else if (ParamName == "memdep") {
786       Result.setMemDep(Enable);
787     } else {
788       return make_error<StringError>(
789           formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
790           inconvertibleErrorCode());
791     }
792   }
793   return Result;
794 }
795 
796 Expected<StackLifetime::LivenessType>
797 parseStackLifetimeOptions(StringRef Params) {
798   StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
799   while (!Params.empty()) {
800     StringRef ParamName;
801     std::tie(ParamName, Params) = Params.split(';');
802 
803     if (ParamName == "may") {
804       Result = StackLifetime::LivenessType::May;
805     } else if (ParamName == "must") {
806       Result = StackLifetime::LivenessType::Must;
807     } else {
808       return make_error<StringError>(
809           formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
810           inconvertibleErrorCode());
811     }
812   }
813   return Result;
814 }
815 
816 } // namespace
817 
818 /// Tests whether a pass name starts with a valid prefix for a default pipeline
819 /// alias.
820 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
821   return Name.startswith("default") || Name.startswith("thinlto") ||
822          Name.startswith("lto");
823 }
824 
825 /// Tests whether registered callbacks will accept a given pass name.
826 ///
827 /// When parsing a pipeline text, the type of the outermost pipeline may be
828 /// omitted, in which case the type is automatically determined from the first
829 /// pass name in the text. This may be a name that is handled through one of the
830 /// callbacks. We check this through the oridinary parsing callbacks by setting
831 /// up a dummy PassManager in order to not force the client to also handle this
832 /// type of query.
833 template <typename PassManagerT, typename CallbacksT>
834 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
835   if (!Callbacks.empty()) {
836     PassManagerT DummyPM;
837     for (auto &CB : Callbacks)
838       if (CB(Name, DummyPM, {}))
839         return true;
840   }
841   return false;
842 }
843 
844 template <typename CallbacksT>
845 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
846   // Manually handle aliases for pre-configured pipeline fragments.
847   if (startsWithDefaultPipelineAliasPrefix(Name))
848     return DefaultAliasRegex.match(Name);
849 
850   // Explicitly handle pass manager names.
851   if (Name == "module")
852     return true;
853   if (Name == "cgscc")
854     return true;
855   if (Name == "function" || Name == "function<eager-inv>")
856     return true;
857 
858   // Explicitly handle custom-parsed pass names.
859   if (parseRepeatPassName(Name))
860     return true;
861 
862 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
863   if (Name == NAME)                                                            \
864     return true;
865 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
866   if (checkParametrizedPassName(Name, NAME))                                   \
867     return true;
868 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
869   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
870     return true;
871 #include "PassRegistry.def"
872 
873   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
874 }
875 
876 template <typename CallbacksT>
877 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
878   // Explicitly handle pass manager names.
879   if (Name == "cgscc")
880     return true;
881   if (Name == "function" || Name == "function<eager-inv>")
882     return true;
883 
884   // Explicitly handle custom-parsed pass names.
885   if (parseRepeatPassName(Name))
886     return true;
887   if (parseDevirtPassName(Name))
888     return true;
889 
890 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
891   if (Name == NAME)                                                            \
892     return true;
893 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
894   if (checkParametrizedPassName(Name, NAME))                                   \
895     return true;
896 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
897   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
898     return true;
899 #include "PassRegistry.def"
900 
901   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
902 }
903 
904 template <typename CallbacksT>
905 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
906   // Explicitly handle pass manager names.
907   if (Name == "function" || Name == "function<eager-inv>")
908     return true;
909   if (Name == "loop" || Name == "loop-mssa")
910     return true;
911 
912   // Explicitly handle custom-parsed pass names.
913   if (parseRepeatPassName(Name))
914     return true;
915 
916 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
917   if (Name == NAME)                                                            \
918     return true;
919 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
920   if (checkParametrizedPassName(Name, NAME))                                   \
921     return true;
922 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
923   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
924     return true;
925 #include "PassRegistry.def"
926 
927   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
928 }
929 
930 template <typename CallbacksT>
931 static bool isLoopNestPassName(StringRef Name, CallbacksT &Callbacks,
932                                bool &UseMemorySSA) {
933   UseMemorySSA = false;
934 
935   // Explicitly handle custom-parsed pass names.
936   if (parseRepeatPassName(Name))
937     return true;
938 
939   if (Name == "lnicm") {
940     UseMemorySSA = true;
941     return true;
942   }
943 
944 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
945   if (Name == NAME)                                                            \
946     return true;
947 #include "PassRegistry.def"
948 
949   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
950 }
951 
952 template <typename CallbacksT>
953 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks,
954                            bool &UseMemorySSA) {
955   UseMemorySSA = false;
956 
957   // Explicitly handle custom-parsed pass names.
958   if (parseRepeatPassName(Name))
959     return true;
960 
961   if (Name == "licm") {
962     UseMemorySSA = true;
963     return true;
964   }
965 
966 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
967   if (Name == NAME)                                                            \
968     return true;
969 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
970   if (checkParametrizedPassName(Name, NAME))                                   \
971     return true;
972 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
973   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
974     return true;
975 #include "PassRegistry.def"
976 
977   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
978 }
979 
980 Optional<std::vector<PassBuilder::PipelineElement>>
981 PassBuilder::parsePipelineText(StringRef Text) {
982   std::vector<PipelineElement> ResultPipeline;
983 
984   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
985       &ResultPipeline};
986   for (;;) {
987     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
988     size_t Pos = Text.find_first_of(",()");
989     Pipeline.push_back({Text.substr(0, Pos), {}});
990 
991     // If we have a single terminating name, we're done.
992     if (Pos == Text.npos)
993       break;
994 
995     char Sep = Text[Pos];
996     Text = Text.substr(Pos + 1);
997     if (Sep == ',')
998       // Just a name ending in a comma, continue.
999       continue;
1000 
1001     if (Sep == '(') {
1002       // Push the inner pipeline onto the stack to continue processing.
1003       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1004       continue;
1005     }
1006 
1007     assert(Sep == ')' && "Bogus separator!");
1008     // When handling the close parenthesis, we greedily consume them to avoid
1009     // empty strings in the pipeline.
1010     do {
1011       // If we try to pop the outer pipeline we have unbalanced parentheses.
1012       if (PipelineStack.size() == 1)
1013         return None;
1014 
1015       PipelineStack.pop_back();
1016     } while (Text.consume_front(")"));
1017 
1018     // Check if we've finished parsing.
1019     if (Text.empty())
1020       break;
1021 
1022     // Otherwise, the end of an inner pipeline always has to be followed by
1023     // a comma, and then we can continue.
1024     if (!Text.consume_front(","))
1025       return None;
1026   }
1027 
1028   if (PipelineStack.size() > 1)
1029     // Unbalanced paretheses.
1030     return None;
1031 
1032   assert(PipelineStack.back() == &ResultPipeline &&
1033          "Wrong pipeline at the bottom of the stack!");
1034   return {std::move(ResultPipeline)};
1035 }
1036 
1037 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1038                                    const PipelineElement &E) {
1039   auto &Name = E.Name;
1040   auto &InnerPipeline = E.InnerPipeline;
1041 
1042   // First handle complex passes like the pass managers which carry pipelines.
1043   if (!InnerPipeline.empty()) {
1044     if (Name == "module") {
1045       ModulePassManager NestedMPM;
1046       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1047         return Err;
1048       MPM.addPass(std::move(NestedMPM));
1049       return Error::success();
1050     }
1051     if (Name == "cgscc") {
1052       CGSCCPassManager CGPM;
1053       if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
1054         return Err;
1055       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1056       return Error::success();
1057     }
1058     if (Name == "function" || Name == "function<eager-inv>") {
1059       FunctionPassManager FPM;
1060       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1061         return Err;
1062       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
1063                                                     Name != "function"));
1064       return Error::success();
1065     }
1066     if (auto Count = parseRepeatPassName(Name)) {
1067       ModulePassManager NestedMPM;
1068       if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1069         return Err;
1070       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1071       return Error::success();
1072     }
1073 
1074     for (auto &C : ModulePipelineParsingCallbacks)
1075       if (C(Name, MPM, InnerPipeline))
1076         return Error::success();
1077 
1078     // Normal passes can't have pipelines.
1079     return make_error<StringError>(
1080         formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1081         inconvertibleErrorCode());
1082     ;
1083   }
1084 
1085   // Manually handle aliases for pre-configured pipeline fragments.
1086   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1087     SmallVector<StringRef, 3> Matches;
1088     if (!DefaultAliasRegex.match(Name, &Matches))
1089       return make_error<StringError>(
1090           formatv("unknown default pipeline alias '{0}'", Name).str(),
1091           inconvertibleErrorCode());
1092 
1093     assert(Matches.size() == 3 && "Must capture two matched strings!");
1094 
1095     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1096                               .Case("O0", OptimizationLevel::O0)
1097                               .Case("O1", OptimizationLevel::O1)
1098                               .Case("O2", OptimizationLevel::O2)
1099                               .Case("O3", OptimizationLevel::O3)
1100                               .Case("Os", OptimizationLevel::Os)
1101                               .Case("Oz", OptimizationLevel::Oz);
1102     if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" &&
1103         Matches[1] != "lto") {
1104       MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" ||
1105                                                 Matches[1] == "lto-pre-link"));
1106       return Error::success();
1107     }
1108 
1109     // This is consistent with old pass manager invoked via opt, but
1110     // inconsistent with clang. Clang doesn't enable loop vectorization
1111     // but does enable slp vectorization at Oz.
1112     PTO.LoopVectorization =
1113         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1114     PTO.SLPVectorization =
1115         L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1116 
1117     if (Matches[1] == "default") {
1118       MPM.addPass(buildPerModuleDefaultPipeline(L));
1119     } else if (Matches[1] == "thinlto-pre-link") {
1120       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
1121     } else if (Matches[1] == "thinlto") {
1122       MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
1123     } else if (Matches[1] == "lto-pre-link") {
1124       MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
1125     } else {
1126       assert(Matches[1] == "lto" && "Not one of the matched options!");
1127       MPM.addPass(buildLTODefaultPipeline(L, nullptr));
1128     }
1129     return Error::success();
1130   }
1131 
1132   // Finally expand the basic registered passes from the .inc file.
1133 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1134   if (Name == NAME) {                                                          \
1135     MPM.addPass(CREATE_PASS);                                                  \
1136     return Error::success();                                                   \
1137   }
1138 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
1139   if (checkParametrizedPassName(Name, NAME)) {                                 \
1140     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1141     if (!Params)                                                               \
1142       return Params.takeError();                                               \
1143     MPM.addPass(CREATE_PASS(Params.get()));                                    \
1144     return Error::success();                                                   \
1145   }
1146 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1147   if (Name == "require<" NAME ">") {                                           \
1148     MPM.addPass(                                                               \
1149         RequireAnalysisPass<                                                   \
1150             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
1151     return Error::success();                                                   \
1152   }                                                                            \
1153   if (Name == "invalidate<" NAME ">") {                                        \
1154     MPM.addPass(InvalidateAnalysisPass<                                        \
1155                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1156     return Error::success();                                                   \
1157   }
1158 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1159   if (Name == NAME) {                                                          \
1160     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS));         \
1161     return Error::success();                                                   \
1162   }
1163 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1164   if (checkParametrizedPassName(Name, NAME)) {                                 \
1165     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1166     if (!Params)                                                               \
1167       return Params.takeError();                                               \
1168     MPM.addPass(                                                               \
1169         createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS(Params.get())));   \
1170     return Error::success();                                                   \
1171   }
1172 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1173   if (Name == NAME) {                                                          \
1174     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS));               \
1175     return Error::success();                                                   \
1176   }
1177 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1178   if (checkParametrizedPassName(Name, NAME)) {                                 \
1179     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1180     if (!Params)                                                               \
1181       return Params.takeError();                                               \
1182     MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1183     return Error::success();                                                   \
1184   }
1185 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1186   if (Name == NAME) {                                                          \
1187     MPM.addPass(createModuleToFunctionPassAdaptor(                             \
1188         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1189     return Error::success();                                                   \
1190   }
1191 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1192   if (Name == NAME) {                                                          \
1193     MPM.addPass(createModuleToFunctionPassAdaptor(                             \
1194         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1195     return Error::success();                                                   \
1196   }
1197 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1198   if (checkParametrizedPassName(Name, NAME)) {                                 \
1199     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1200     if (!Params)                                                               \
1201       return Params.takeError();                                               \
1202     MPM.addPass(                                                               \
1203         createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(     \
1204             CREATE_PASS(Params.get()), false, false)));                        \
1205     return Error::success();                                                   \
1206   }
1207 #include "PassRegistry.def"
1208 
1209   for (auto &C : ModulePipelineParsingCallbacks)
1210     if (C(Name, MPM, InnerPipeline))
1211       return Error::success();
1212   return make_error<StringError>(
1213       formatv("unknown module pass '{0}'", Name).str(),
1214       inconvertibleErrorCode());
1215 }
1216 
1217 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1218                                   const PipelineElement &E) {
1219   auto &Name = E.Name;
1220   auto &InnerPipeline = E.InnerPipeline;
1221 
1222   // First handle complex passes like the pass managers which carry pipelines.
1223   if (!InnerPipeline.empty()) {
1224     if (Name == "cgscc") {
1225       CGSCCPassManager NestedCGPM;
1226       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1227         return Err;
1228       // Add the nested pass manager with the appropriate adaptor.
1229       CGPM.addPass(std::move(NestedCGPM));
1230       return Error::success();
1231     }
1232     if (Name == "function" || Name == "function<eager-inv>") {
1233       FunctionPassManager FPM;
1234       if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1235         return Err;
1236       // Add the nested pass manager with the appropriate adaptor.
1237       CGPM.addPass(
1238           createCGSCCToFunctionPassAdaptor(std::move(FPM), Name != "function"));
1239       return Error::success();
1240     }
1241     if (auto Count = parseRepeatPassName(Name)) {
1242       CGSCCPassManager NestedCGPM;
1243       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1244         return Err;
1245       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1246       return Error::success();
1247     }
1248     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1249       CGSCCPassManager NestedCGPM;
1250       if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1251         return Err;
1252       CGPM.addPass(
1253           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1254       return Error::success();
1255     }
1256 
1257     for (auto &C : CGSCCPipelineParsingCallbacks)
1258       if (C(Name, CGPM, InnerPipeline))
1259         return Error::success();
1260 
1261     // Normal passes can't have pipelines.
1262     return make_error<StringError>(
1263         formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1264         inconvertibleErrorCode());
1265   }
1266 
1267 // Now expand the basic registered passes from the .inc file.
1268 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1269   if (Name == NAME) {                                                          \
1270     CGPM.addPass(CREATE_PASS);                                                 \
1271     return Error::success();                                                   \
1272   }
1273 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1274   if (checkParametrizedPassName(Name, NAME)) {                                 \
1275     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1276     if (!Params)                                                               \
1277       return Params.takeError();                                               \
1278     CGPM.addPass(CREATE_PASS(Params.get()));                                   \
1279     return Error::success();                                                   \
1280   }
1281 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1282   if (Name == "require<" NAME ">") {                                           \
1283     CGPM.addPass(RequireAnalysisPass<                                          \
1284                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
1285                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
1286                  CGSCCUpdateResult &>());                                      \
1287     return Error::success();                                                   \
1288   }                                                                            \
1289   if (Name == "invalidate<" NAME ">") {                                        \
1290     CGPM.addPass(InvalidateAnalysisPass<                                       \
1291                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
1292     return Error::success();                                                   \
1293   }
1294 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1295   if (Name == NAME) {                                                          \
1296     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS));               \
1297     return Error::success();                                                   \
1298   }
1299 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1300   if (checkParametrizedPassName(Name, NAME)) {                                 \
1301     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1302     if (!Params)                                                               \
1303       return Params.takeError();                                               \
1304     CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1305     return Error::success();                                                   \
1306   }
1307 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1308   if (Name == NAME) {                                                          \
1309     CGPM.addPass(createCGSCCToFunctionPassAdaptor(                             \
1310         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1311     return Error::success();                                                   \
1312   }
1313 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1314   if (Name == NAME) {                                                          \
1315     CGPM.addPass(createCGSCCToFunctionPassAdaptor(                             \
1316         createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)));          \
1317     return Error::success();                                                   \
1318   }
1319 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1320   if (checkParametrizedPassName(Name, NAME)) {                                 \
1321     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1322     if (!Params)                                                               \
1323       return Params.takeError();                                               \
1324     CGPM.addPass(                                                              \
1325         createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(      \
1326             CREATE_PASS(Params.get()), false, false)));                        \
1327     return Error::success();                                                   \
1328   }
1329 #include "PassRegistry.def"
1330 
1331   for (auto &C : CGSCCPipelineParsingCallbacks)
1332     if (C(Name, CGPM, InnerPipeline))
1333       return Error::success();
1334   return make_error<StringError>(
1335       formatv("unknown cgscc pass '{0}'", Name).str(),
1336       inconvertibleErrorCode());
1337 }
1338 
1339 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1340                                      const PipelineElement &E) {
1341   auto &Name = E.Name;
1342   auto &InnerPipeline = E.InnerPipeline;
1343 
1344   // First handle complex passes like the pass managers which carry pipelines.
1345   if (!InnerPipeline.empty()) {
1346     if (Name == "function") {
1347       FunctionPassManager NestedFPM;
1348       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1349         return Err;
1350       // Add the nested pass manager with the appropriate adaptor.
1351       FPM.addPass(std::move(NestedFPM));
1352       return Error::success();
1353     }
1354     if (Name == "loop" || Name == "loop-mssa") {
1355       LoopPassManager LPM;
1356       if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
1357         return Err;
1358       // Add the nested pass manager with the appropriate adaptor.
1359       bool UseMemorySSA = (Name == "loop-mssa");
1360       bool UseBFI = llvm::any_of(
1361           InnerPipeline, [](auto Pipeline) { return Pipeline.Name == "licm"; });
1362       bool UseBPI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
1363         return Pipeline.Name == "loop-predication";
1364       });
1365       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
1366                                                   UseBFI, UseBPI));
1367       return Error::success();
1368     }
1369     if (auto Count = parseRepeatPassName(Name)) {
1370       FunctionPassManager NestedFPM;
1371       if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1372         return Err;
1373       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1374       return Error::success();
1375     }
1376 
1377     for (auto &C : FunctionPipelineParsingCallbacks)
1378       if (C(Name, FPM, InnerPipeline))
1379         return Error::success();
1380 
1381     // Normal passes can't have pipelines.
1382     return make_error<StringError>(
1383         formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1384         inconvertibleErrorCode());
1385   }
1386 
1387 // Now expand the basic registered passes from the .inc file.
1388 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1389   if (Name == NAME) {                                                          \
1390     FPM.addPass(CREATE_PASS);                                                  \
1391     return Error::success();                                                   \
1392   }
1393 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1394   if (checkParametrizedPassName(Name, NAME)) {                                 \
1395     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1396     if (!Params)                                                               \
1397       return Params.takeError();                                               \
1398     FPM.addPass(CREATE_PASS(Params.get()));                                    \
1399     return Error::success();                                                   \
1400   }
1401 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1402   if (Name == "require<" NAME ">") {                                           \
1403     FPM.addPass(                                                               \
1404         RequireAnalysisPass<                                                   \
1405             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
1406     return Error::success();                                                   \
1407   }                                                                            \
1408   if (Name == "invalidate<" NAME ">") {                                        \
1409     FPM.addPass(InvalidateAnalysisPass<                                        \
1410                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1411     return Error::success();                                                   \
1412   }
1413 // FIXME: UseMemorySSA is set to false. Maybe we could do things like:
1414 //        bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
1415 //                              "guard-widening");
1416 //        The risk is that it may become obsolete if we're not careful.
1417 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1418   if (Name == NAME) {                                                          \
1419     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false));   \
1420     return Error::success();                                                   \
1421   }
1422 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1423   if (Name == NAME) {                                                          \
1424     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false));   \
1425     return Error::success();                                                   \
1426   }
1427 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1428   if (checkParametrizedPassName(Name, NAME)) {                                 \
1429     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1430     if (!Params)                                                               \
1431       return Params.takeError();                                               \
1432     FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()),     \
1433                                                 false, false));                \
1434     return Error::success();                                                   \
1435   }
1436 #include "PassRegistry.def"
1437 
1438   for (auto &C : FunctionPipelineParsingCallbacks)
1439     if (C(Name, FPM, InnerPipeline))
1440       return Error::success();
1441   return make_error<StringError>(
1442       formatv("unknown function pass '{0}'", Name).str(),
1443       inconvertibleErrorCode());
1444 }
1445 
1446 Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
1447                                  const PipelineElement &E) {
1448   StringRef Name = E.Name;
1449   auto &InnerPipeline = E.InnerPipeline;
1450 
1451   // First handle complex passes like the pass managers which carry pipelines.
1452   if (!InnerPipeline.empty()) {
1453     if (Name == "loop") {
1454       LoopPassManager NestedLPM;
1455       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1456         return Err;
1457       // Add the nested pass manager with the appropriate adaptor.
1458       LPM.addPass(std::move(NestedLPM));
1459       return Error::success();
1460     }
1461     if (auto Count = parseRepeatPassName(Name)) {
1462       LoopPassManager NestedLPM;
1463       if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1464         return Err;
1465       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1466       return Error::success();
1467     }
1468 
1469     for (auto &C : LoopPipelineParsingCallbacks)
1470       if (C(Name, LPM, InnerPipeline))
1471         return Error::success();
1472 
1473     // Normal passes can't have pipelines.
1474     return make_error<StringError>(
1475         formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1476         inconvertibleErrorCode());
1477   }
1478 
1479 // Now expand the basic registered passes from the .inc file.
1480 #define LOOPNEST_PASS(NAME, CREATE_PASS)                                       \
1481   if (Name == NAME) {                                                          \
1482     LPM.addPass(CREATE_PASS);                                                  \
1483     return Error::success();                                                   \
1484   }
1485 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1486   if (Name == NAME) {                                                          \
1487     LPM.addPass(CREATE_PASS);                                                  \
1488     return Error::success();                                                   \
1489   }
1490 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1491   if (checkParametrizedPassName(Name, NAME)) {                                 \
1492     auto Params = parsePassParameters(PARSER, Name, NAME);                     \
1493     if (!Params)                                                               \
1494       return Params.takeError();                                               \
1495     LPM.addPass(CREATE_PASS(Params.get()));                                    \
1496     return Error::success();                                                   \
1497   }
1498 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1499   if (Name == "require<" NAME ">") {                                           \
1500     LPM.addPass(RequireAnalysisPass<                                           \
1501                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
1502                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
1503                 LPMUpdater &>());                                              \
1504     return Error::success();                                                   \
1505   }                                                                            \
1506   if (Name == "invalidate<" NAME ">") {                                        \
1507     LPM.addPass(InvalidateAnalysisPass<                                        \
1508                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1509     return Error::success();                                                   \
1510   }
1511 #include "PassRegistry.def"
1512 
1513   for (auto &C : LoopPipelineParsingCallbacks)
1514     if (C(Name, LPM, InnerPipeline))
1515       return Error::success();
1516   return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1517                                  inconvertibleErrorCode());
1518 }
1519 
1520 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1521 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1522   if (Name == NAME) {                                                          \
1523     AA.registerModuleAnalysis<                                                 \
1524         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1525     return true;                                                               \
1526   }
1527 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1528   if (Name == NAME) {                                                          \
1529     AA.registerFunctionAnalysis<                                               \
1530         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1531     return true;                                                               \
1532   }
1533 #include "PassRegistry.def"
1534 
1535   for (auto &C : AAParsingCallbacks)
1536     if (C(Name, AA))
1537       return true;
1538   return false;
1539 }
1540 
1541 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1542                                          ArrayRef<PipelineElement> Pipeline) {
1543   for (const auto &Element : Pipeline) {
1544     if (auto Err = parseLoopPass(LPM, Element))
1545       return Err;
1546   }
1547   return Error::success();
1548 }
1549 
1550 Error PassBuilder::parseFunctionPassPipeline(
1551     FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
1552   for (const auto &Element : Pipeline) {
1553     if (auto Err = parseFunctionPass(FPM, Element))
1554       return Err;
1555   }
1556   return Error::success();
1557 }
1558 
1559 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1560                                           ArrayRef<PipelineElement> Pipeline) {
1561   for (const auto &Element : Pipeline) {
1562     if (auto Err = parseCGSCCPass(CGPM, Element))
1563       return Err;
1564   }
1565   return Error::success();
1566 }
1567 
1568 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1569                                        FunctionAnalysisManager &FAM,
1570                                        CGSCCAnalysisManager &CGAM,
1571                                        ModuleAnalysisManager &MAM) {
1572   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1573   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1574   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1575   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1576   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1577   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1578   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1579 }
1580 
1581 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1582                                            ArrayRef<PipelineElement> Pipeline) {
1583   for (const auto &Element : Pipeline) {
1584     if (auto Err = parseModulePass(MPM, Element))
1585       return Err;
1586   }
1587   return Error::success();
1588 }
1589 
1590 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1591 // FIXME: Should this routine accept a TargetMachine or require the caller to
1592 // pre-populate the analysis managers with target-specific stuff?
1593 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1594                                      StringRef PipelineText) {
1595   auto Pipeline = parsePipelineText(PipelineText);
1596   if (!Pipeline || Pipeline->empty())
1597     return make_error<StringError>(
1598         formatv("invalid pipeline '{0}'", PipelineText).str(),
1599         inconvertibleErrorCode());
1600 
1601   // If the first name isn't at the module layer, wrap the pipeline up
1602   // automatically.
1603   StringRef FirstName = Pipeline->front().Name;
1604 
1605   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1606     bool UseMemorySSA;
1607     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1608       Pipeline = {{"cgscc", std::move(*Pipeline)}};
1609     } else if (isFunctionPassName(FirstName,
1610                                   FunctionPipelineParsingCallbacks)) {
1611       Pipeline = {{"function", std::move(*Pipeline)}};
1612     } else if (isLoopNestPassName(FirstName, LoopPipelineParsingCallbacks,
1613                                   UseMemorySSA)) {
1614       Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1615                                  std::move(*Pipeline)}}}};
1616     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks,
1617                               UseMemorySSA)) {
1618       Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1619                                  std::move(*Pipeline)}}}};
1620     } else {
1621       for (auto &C : TopLevelPipelineParsingCallbacks)
1622         if (C(MPM, *Pipeline))
1623           return Error::success();
1624 
1625       // Unknown pass or pipeline name!
1626       auto &InnerPipeline = Pipeline->front().InnerPipeline;
1627       return make_error<StringError>(
1628           formatv("unknown {0} name '{1}'",
1629                   (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1630               .str(),
1631           inconvertibleErrorCode());
1632     }
1633   }
1634 
1635   if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
1636     return Err;
1637   return Error::success();
1638 }
1639 
1640 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1641 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1642                                      StringRef PipelineText) {
1643   auto Pipeline = parsePipelineText(PipelineText);
1644   if (!Pipeline || Pipeline->empty())
1645     return make_error<StringError>(
1646         formatv("invalid pipeline '{0}'", PipelineText).str(),
1647         inconvertibleErrorCode());
1648 
1649   StringRef FirstName = Pipeline->front().Name;
1650   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1651     return make_error<StringError>(
1652         formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1653                 PipelineText)
1654             .str(),
1655         inconvertibleErrorCode());
1656 
1657   if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
1658     return Err;
1659   return Error::success();
1660 }
1661 
1662 // Primary pass pipeline description parsing routine for a \c
1663 // FunctionPassManager
1664 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1665                                      StringRef PipelineText) {
1666   auto Pipeline = parsePipelineText(PipelineText);
1667   if (!Pipeline || Pipeline->empty())
1668     return make_error<StringError>(
1669         formatv("invalid pipeline '{0}'", PipelineText).str(),
1670         inconvertibleErrorCode());
1671 
1672   StringRef FirstName = Pipeline->front().Name;
1673   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1674     return make_error<StringError>(
1675         formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1676                 PipelineText)
1677             .str(),
1678         inconvertibleErrorCode());
1679 
1680   if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
1681     return Err;
1682   return Error::success();
1683 }
1684 
1685 // Primary pass pipeline description parsing routine for a \c LoopPassManager
1686 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1687                                      StringRef PipelineText) {
1688   auto Pipeline = parsePipelineText(PipelineText);
1689   if (!Pipeline || Pipeline->empty())
1690     return make_error<StringError>(
1691         formatv("invalid pipeline '{0}'", PipelineText).str(),
1692         inconvertibleErrorCode());
1693 
1694   if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
1695     return Err;
1696 
1697   return Error::success();
1698 }
1699 
1700 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1701   // If the pipeline just consists of the word 'default' just replace the AA
1702   // manager with our default one.
1703   if (PipelineText == "default") {
1704     AA = buildDefaultAAPipeline();
1705     return Error::success();
1706   }
1707 
1708   while (!PipelineText.empty()) {
1709     StringRef Name;
1710     std::tie(Name, PipelineText) = PipelineText.split(',');
1711     if (!parseAAPassName(AA, Name))
1712       return make_error<StringError>(
1713           formatv("unknown alias analysis name '{0}'", Name).str(),
1714           inconvertibleErrorCode());
1715   }
1716 
1717   return Error::success();
1718 }
1719 
1720 bool PassBuilder::isAAPassName(StringRef PassName) {
1721 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1722   if (PassName == NAME)                                                        \
1723     return true;
1724 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1725   if (PassName == NAME)                                                        \
1726     return true;
1727 #include "PassRegistry.def"
1728   return false;
1729 }
1730 
1731 bool PassBuilder::isAnalysisPassName(StringRef PassName) {
1732 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1733   if (PassName == NAME)                                                        \
1734     return true;
1735 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1736   if (PassName == NAME)                                                        \
1737     return true;
1738 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1739   if (PassName == NAME)                                                        \
1740     return true;
1741 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1742   if (PassName == NAME)                                                        \
1743     return true;
1744 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1745   if (PassName == NAME)                                                        \
1746     return true;
1747 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1748   if (PassName == NAME)                                                        \
1749     return true;
1750 #include "PassRegistry.def"
1751   return false;
1752 }
1753 
1754 static void printPassName(StringRef PassName, raw_ostream &OS) {
1755   OS << "  " << PassName << "\n";
1756 }
1757 static void printPassName(StringRef PassName, StringRef Params,
1758                           raw_ostream &OS) {
1759   OS << "  " << PassName << "<" << Params << ">\n";
1760 }
1761 
1762 void PassBuilder::printPassNames(raw_ostream &OS) {
1763   // TODO: print pass descriptions when they are available
1764 
1765   OS << "Module passes:\n";
1766 #define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1767 #include "PassRegistry.def"
1768 
1769   OS << "Module passes with params:\n";
1770 #define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)      \
1771   printPassName(NAME, PARAMS, OS);
1772 #include "PassRegistry.def"
1773 
1774   OS << "Module analyses:\n";
1775 #define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1776 #include "PassRegistry.def"
1777 
1778   OS << "Module alias analyses:\n";
1779 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1780 #include "PassRegistry.def"
1781 
1782   OS << "CGSCC passes:\n";
1783 #define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1784 #include "PassRegistry.def"
1785 
1786   OS << "CGSCC passes with params:\n";
1787 #define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)       \
1788   printPassName(NAME, PARAMS, OS);
1789 #include "PassRegistry.def"
1790 
1791   OS << "CGSCC analyses:\n";
1792 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1793 #include "PassRegistry.def"
1794 
1795   OS << "Function passes:\n";
1796 #define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1797 #include "PassRegistry.def"
1798 
1799   OS << "Function passes with params:\n";
1800 #define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)    \
1801   printPassName(NAME, PARAMS, OS);
1802 #include "PassRegistry.def"
1803 
1804   OS << "Function analyses:\n";
1805 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1806 #include "PassRegistry.def"
1807 
1808   OS << "Function alias analyses:\n";
1809 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1810 #include "PassRegistry.def"
1811 
1812   OS << "LoopNest passes:\n";
1813 #define LOOPNEST_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1814 #include "PassRegistry.def"
1815 
1816   OS << "Loop passes:\n";
1817 #define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1818 #include "PassRegistry.def"
1819 
1820   OS << "Loop passes with params:\n";
1821 #define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS)        \
1822   printPassName(NAME, PARAMS, OS);
1823 #include "PassRegistry.def"
1824 
1825   OS << "Loop analyses:\n";
1826 #define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1827 #include "PassRegistry.def"
1828 }
1829 
1830 void PassBuilder::registerParseTopLevelPipelineCallback(
1831     const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
1832         &C) {
1833   TopLevelPipelineParsingCallbacks.push_back(C);
1834 }
1835