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