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