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