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