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