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