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