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