1 //===- Parsing, selection, and construction of pass pipelines -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This file provides the implementation of the PassBuilder based on our
12 /// static pass registry as well as related functionality. It also provides
13 /// helpers to aid in analyzing, debugging, and testing passes and pass
14 /// pipelines.
15 ///
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Passes/PassBuilder.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/BasicAliasAnalysis.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26 #include "llvm/Analysis/BranchProbabilityInfo.h"
27 #include "llvm/Analysis/CFGPrinter.h"
28 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
29 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
30 #include "llvm/Analysis/CGSCCPassManager.h"
31 #include "llvm/Analysis/CallGraph.h"
32 #include "llvm/Analysis/DemandedBits.h"
33 #include "llvm/Analysis/DependenceAnalysis.h"
34 #include "llvm/Analysis/DominanceFrontier.h"
35 #include "llvm/Analysis/GlobalsModRef.h"
36 #include "llvm/Analysis/IVUsers.h"
37 #include "llvm/Analysis/LazyCallGraph.h"
38 #include "llvm/Analysis/LazyValueInfo.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
42 #include "llvm/Analysis/MemorySSA.h"
43 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/PostDominators.h"
46 #include "llvm/Analysis/ProfileSummaryInfo.h"
47 #include "llvm/Analysis/RegionInfo.h"
48 #include "llvm/Analysis/ScalarEvolution.h"
49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
50 #include "llvm/Analysis/ScopedNoAliasAA.h"
51 #include "llvm/Analysis/TargetLibraryInfo.h"
52 #include "llvm/Analysis/TargetTransformInfo.h"
53 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
54 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
55 #include "llvm/CodeGen/UnreachableBlockElim.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/IRPrintingPasses.h"
58 #include "llvm/IR/PassManager.h"
59 #include "llvm/IR/Verifier.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/Regex.h"
62 #include "llvm/Target/TargetMachine.h"
63 #include "llvm/Transforms/GCOVProfiler.h"
64 #include "llvm/Transforms/IPO/AlwaysInliner.h"
65 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
66 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
67 #include "llvm/Transforms/IPO/ConstantMerge.h"
68 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
69 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
70 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
71 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
72 #include "llvm/Transforms/IPO/FunctionAttrs.h"
73 #include "llvm/Transforms/IPO/FunctionImport.h"
74 #include "llvm/Transforms/IPO/GlobalDCE.h"
75 #include "llvm/Transforms/IPO/GlobalOpt.h"
76 #include "llvm/Transforms/IPO/GlobalSplit.h"
77 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
78 #include "llvm/Transforms/IPO/Inliner.h"
79 #include "llvm/Transforms/IPO/Internalize.h"
80 #include "llvm/Transforms/IPO/LowerTypeTests.h"
81 #include "llvm/Transforms/IPO/PartialInlining.h"
82 #include "llvm/Transforms/IPO/SCCP.h"
83 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
84 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
85 #include "llvm/Transforms/InstCombine/InstCombine.h"
86 #include "llvm/Transforms/InstrProfiling.h"
87 #include "llvm/Transforms/PGOInstrumentation.h"
88 #include "llvm/Transforms/SampleProfile.h"
89 #include "llvm/Transforms/Scalar/ADCE.h"
90 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
91 #include "llvm/Transforms/Scalar/BDCE.h"
92 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
93 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
94 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
95 #include "llvm/Transforms/Scalar/DCE.h"
96 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
97 #include "llvm/Transforms/Scalar/DivRemPairs.h"
98 #include "llvm/Transforms/Scalar/EarlyCSE.h"
99 #include "llvm/Transforms/Scalar/Float2Int.h"
100 #include "llvm/Transforms/Scalar/GVN.h"
101 #include "llvm/Transforms/Scalar/GuardWidening.h"
102 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
103 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
104 #include "llvm/Transforms/Scalar/JumpThreading.h"
105 #include "llvm/Transforms/Scalar/LICM.h"
106 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
107 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
108 #include "llvm/Transforms/Scalar/LoopDeletion.h"
109 #include "llvm/Transforms/Scalar/LoopDistribute.h"
110 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
111 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
112 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
113 #include "llvm/Transforms/Scalar/LoopPassManager.h"
114 #include "llvm/Transforms/Scalar/LoopPredication.h"
115 #include "llvm/Transforms/Scalar/LoopRotation.h"
116 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
117 #include "llvm/Transforms/Scalar/LoopSink.h"
118 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
119 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
120 #include "llvm/Transforms/Scalar/LowerAtomic.h"
121 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
122 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
123 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
124 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
125 #include "llvm/Transforms/Scalar/NaryReassociate.h"
126 #include "llvm/Transforms/Scalar/NewGVN.h"
127 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
128 #include "llvm/Transforms/Scalar/Reassociate.h"
129 #include "llvm/Transforms/Scalar/SCCP.h"
130 #include "llvm/Transforms/Scalar/SROA.h"
131 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
132 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
133 #include "llvm/Transforms/Scalar/Sink.h"
134 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
135 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
136 #include "llvm/Transforms/Utils/AddDiscriminators.h"
137 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
138 #include "llvm/Transforms/Utils/LCSSA.h"
139 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
140 #include "llvm/Transforms/Utils/LoopSimplify.h"
141 #include "llvm/Transforms/Utils/LowerInvoke.h"
142 #include "llvm/Transforms/Utils/Mem2Reg.h"
143 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
144 #include "llvm/Transforms/Utils/PredicateInfo.h"
145 #include "llvm/Transforms/Utils/SimplifyInstructions.h"
146 #include "llvm/Transforms/Utils/SymbolRewriter.h"
147 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
148 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
149 
150 #include <type_traits>
151 
152 using namespace llvm;
153 
154 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
155                                              cl::ReallyHidden, cl::init(4));
156 static cl::opt<bool>
157     RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
158                        cl::Hidden, cl::ZeroOrMore,
159                        cl::desc("Run Partial inlinining pass"));
160 
161 static cl::opt<bool>
162     RunNewGVN("enable-npm-newgvn", cl::init(false),
163               cl::Hidden, cl::ZeroOrMore,
164               cl::desc("Run NewGVN instead of GVN"));
165 
166 static cl::opt<bool> EnableEarlyCSEMemSSA(
167     "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
168     cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
169 
170 static cl::opt<bool> EnableGVNHoist(
171     "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
172     cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
173 
174 static cl::opt<bool> EnableGVNSink(
175     "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
176     cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
177 
178 static Regex DefaultAliasRegex(
179     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
180 
181 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
182   switch (Level) {
183   case PassBuilder::O0:
184   case PassBuilder::O1:
185   case PassBuilder::O2:
186   case PassBuilder::O3:
187     return false;
188 
189   case PassBuilder::Os:
190   case PassBuilder::Oz:
191     return true;
192   }
193   llvm_unreachable("Invalid optimization level!");
194 }
195 
196 namespace {
197 
198 /// \brief No-op module pass which does nothing.
199 struct NoOpModulePass {
200   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
201     return PreservedAnalyses::all();
202   }
203   static StringRef name() { return "NoOpModulePass"; }
204 };
205 
206 /// \brief No-op module analysis.
207 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
208   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
209   static AnalysisKey Key;
210 
211 public:
212   struct Result {};
213   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
214   static StringRef name() { return "NoOpModuleAnalysis"; }
215 };
216 
217 /// \brief No-op CGSCC pass which does nothing.
218 struct NoOpCGSCCPass {
219   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
220                         LazyCallGraph &, CGSCCUpdateResult &UR) {
221     return PreservedAnalyses::all();
222   }
223   static StringRef name() { return "NoOpCGSCCPass"; }
224 };
225 
226 /// \brief No-op CGSCC analysis.
227 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
228   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
229   static AnalysisKey Key;
230 
231 public:
232   struct Result {};
233   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
234     return Result();
235   }
236   static StringRef name() { return "NoOpCGSCCAnalysis"; }
237 };
238 
239 /// \brief No-op function pass which does nothing.
240 struct NoOpFunctionPass {
241   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
242     return PreservedAnalyses::all();
243   }
244   static StringRef name() { return "NoOpFunctionPass"; }
245 };
246 
247 /// \brief No-op function analysis.
248 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
249   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
250   static AnalysisKey Key;
251 
252 public:
253   struct Result {};
254   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
255   static StringRef name() { return "NoOpFunctionAnalysis"; }
256 };
257 
258 /// \brief No-op loop pass which does nothing.
259 struct NoOpLoopPass {
260   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
261                         LoopStandardAnalysisResults &, LPMUpdater &) {
262     return PreservedAnalyses::all();
263   }
264   static StringRef name() { return "NoOpLoopPass"; }
265 };
266 
267 /// \brief No-op loop analysis.
268 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
269   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
270   static AnalysisKey Key;
271 
272 public:
273   struct Result {};
274   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
275     return Result();
276   }
277   static StringRef name() { return "NoOpLoopAnalysis"; }
278 };
279 
280 AnalysisKey NoOpModuleAnalysis::Key;
281 AnalysisKey NoOpCGSCCAnalysis::Key;
282 AnalysisKey NoOpFunctionAnalysis::Key;
283 AnalysisKey NoOpLoopAnalysis::Key;
284 
285 } // End anonymous namespace.
286 
287 void PassBuilder::invokePeepholeEPCallbacks(
288     FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
289   for (auto &C : PeepholeEPCallbacks)
290     C(FPM, Level);
291 }
292 
293 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
294 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
295   MAM.registerPass([&] { return CREATE_PASS; });
296 #include "PassRegistry.def"
297 
298   for (auto &C : ModuleAnalysisRegistrationCallbacks)
299     C(MAM);
300 }
301 
302 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
303 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
304   CGAM.registerPass([&] { return CREATE_PASS; });
305 #include "PassRegistry.def"
306 
307   for (auto &C : CGSCCAnalysisRegistrationCallbacks)
308     C(CGAM);
309 }
310 
311 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
312 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
313   FAM.registerPass([&] { return CREATE_PASS; });
314 #include "PassRegistry.def"
315 
316   for (auto &C : FunctionAnalysisRegistrationCallbacks)
317     C(FAM);
318 }
319 
320 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
321 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
322   LAM.registerPass([&] { return CREATE_PASS; });
323 #include "PassRegistry.def"
324 
325   for (auto &C : LoopAnalysisRegistrationCallbacks)
326     C(LAM);
327 }
328 
329 FunctionPassManager
330 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
331                                                  ThinLTOPhase Phase,
332                                                  bool DebugLogging) {
333   assert(Level != O0 && "Must request optimizations!");
334   FunctionPassManager FPM(DebugLogging);
335 
336   // Form SSA out of local memory accesses after breaking apart aggregates into
337   // scalars.
338   FPM.addPass(SROA());
339 
340   // Catch trivial redundancies
341   FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
342 
343   // Hoisting of scalars and load expressions.
344   if (EnableGVNHoist)
345     FPM.addPass(GVNHoistPass());
346 
347   // Global value numbering based sinking.
348   if (EnableGVNSink) {
349     FPM.addPass(GVNSinkPass());
350     FPM.addPass(SimplifyCFGPass());
351   }
352 
353   // Speculative execution if the target has divergent branches; otherwise nop.
354   FPM.addPass(SpeculativeExecutionPass());
355 
356   // Optimize based on known information about branches, and cleanup afterward.
357   FPM.addPass(JumpThreadingPass());
358   FPM.addPass(CorrelatedValuePropagationPass());
359   FPM.addPass(SimplifyCFGPass());
360   FPM.addPass(InstCombinePass());
361 
362   if (!isOptimizingForSize(Level))
363     FPM.addPass(LibCallsShrinkWrapPass());
364 
365   invokePeepholeEPCallbacks(FPM, Level);
366 
367   // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
368   // using the size value profile. Don't perform this when optimizing for size.
369   if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
370       !isOptimizingForSize(Level))
371     FPM.addPass(PGOMemOPSizeOpt());
372 
373   FPM.addPass(TailCallElimPass());
374   FPM.addPass(SimplifyCFGPass());
375 
376   // Form canonically associated expression trees, and simplify the trees using
377   // basic mathematical properties. For example, this will form (nearly)
378   // minimal multiplication trees.
379   FPM.addPass(ReassociatePass());
380 
381   // Add the primary loop simplification pipeline.
382   // FIXME: Currently this is split into two loop pass pipelines because we run
383   // some function passes in between them. These can and should be replaced by
384   // loop pass equivalenst but those aren't ready yet. Specifically,
385   // `SimplifyCFGPass` and `InstCombinePass` are used. We have
386   // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
387   // the other we have is `LoopInstSimplify`.
388   LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
389 
390   // Rotate Loop - disable header duplication at -Oz
391   LPM1.addPass(LoopRotatePass(Level != Oz));
392   LPM1.addPass(LICMPass());
393   LPM1.addPass(SimpleLoopUnswitchPass());
394   LPM2.addPass(IndVarSimplifyPass());
395   LPM2.addPass(LoopIdiomRecognizePass());
396 
397   for (auto &C : LateLoopOptimizationsEPCallbacks)
398     C(LPM2, Level);
399 
400   LPM2.addPass(LoopDeletionPass());
401   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
402   // because it changes IR to makes profile annotation in back compile
403   // inaccurate.
404   if (Phase != ThinLTOPhase::PreLink ||
405       !PGOOpt || PGOOpt->SampleProfileFile.empty())
406     LPM2.addPass(LoopFullUnrollPass(Level));
407 
408   for (auto &C : LoopOptimizerEndEPCallbacks)
409     C(LPM2, Level);
410 
411   // We provide the opt remark emitter pass for LICM to use. We only need to do
412   // this once as it is immutable.
413   FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
414   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
415   FPM.addPass(SimplifyCFGPass());
416   FPM.addPass(InstCombinePass());
417   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
418 
419   // Eliminate redundancies.
420   if (Level != O1) {
421     // These passes add substantial compile time so skip them at O1.
422     FPM.addPass(MergedLoadStoreMotionPass());
423     if (RunNewGVN)
424       FPM.addPass(NewGVNPass());
425     else
426       FPM.addPass(GVN());
427   }
428 
429   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
430   FPM.addPass(MemCpyOptPass());
431 
432   // Sparse conditional constant propagation.
433   // FIXME: It isn't clear why we do this *after* loop passes rather than
434   // before...
435   FPM.addPass(SCCPPass());
436 
437   // Delete dead bit computations (instcombine runs after to fold away the dead
438   // computations, and then ADCE will run later to exploit any new DCE
439   // opportunities that creates).
440   FPM.addPass(BDCEPass());
441 
442   // Run instcombine after redundancy and dead bit elimination to exploit
443   // opportunities opened up by them.
444   FPM.addPass(InstCombinePass());
445   invokePeepholeEPCallbacks(FPM, Level);
446 
447   // Re-consider control flow based optimizations after redundancy elimination,
448   // redo DCE, etc.
449   FPM.addPass(JumpThreadingPass());
450   FPM.addPass(CorrelatedValuePropagationPass());
451   FPM.addPass(DSEPass());
452   FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
453 
454   for (auto &C : ScalarOptimizerLateEPCallbacks)
455     C(FPM, Level);
456 
457   // Finally, do an expensive DCE pass to catch all the dead code exposed by
458   // the simplifications and basic cleanup after all the simplifications.
459   FPM.addPass(ADCEPass());
460   FPM.addPass(SimplifyCFGPass());
461   FPM.addPass(InstCombinePass());
462   invokePeepholeEPCallbacks(FPM, Level);
463 
464   return FPM;
465 }
466 
467 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
468                                     PassBuilder::OptimizationLevel Level,
469                                     bool RunProfileGen,
470                                     std::string ProfileGenFile,
471                                     std::string ProfileUseFile) {
472   // Generally running simplification passes and the inliner with an high
473   // threshold results in smaller executables, but there may be cases where
474   // the size grows, so let's be conservative here and skip this simplification
475   // at -Os/Oz.
476   if (!isOptimizingForSize(Level)) {
477     InlineParams IP;
478 
479     // In the old pass manager, this is a cl::opt. Should still this be one?
480     IP.DefaultThreshold = 75;
481 
482     // FIXME: The hint threshold has the same value used by the regular inliner.
483     // This should probably be lowered after performance testing.
484     // FIXME: this comment is cargo culted from the old pass manager, revisit).
485     IP.HintThreshold = 325;
486 
487     CGSCCPassManager CGPipeline(DebugLogging);
488 
489     CGPipeline.addPass(InlinerPass(IP));
490 
491     FunctionPassManager FPM;
492     FPM.addPass(SROA());
493     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
494     FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
495     FPM.addPass(InstCombinePass()); // Combine silly sequences.
496     invokePeepholeEPCallbacks(FPM, Level);
497 
498     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
499 
500     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
501   }
502 
503   // Delete anything that is now dead to make sure that we don't instrument
504   // dead code. Instrumentation can end up keeping dead code around and
505   // dramatically increase code size.
506   MPM.addPass(GlobalDCEPass());
507 
508   if (RunProfileGen) {
509     MPM.addPass(PGOInstrumentationGen());
510 
511     FunctionPassManager FPM;
512     FPM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
513     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
514 
515     // Add the profile lowering pass.
516     InstrProfOptions Options;
517     if (!ProfileGenFile.empty())
518       Options.InstrProfileOutput = ProfileGenFile;
519     Options.DoCounterPromotion = true;
520     MPM.addPass(InstrProfiling(Options));
521   }
522 
523   if (!ProfileUseFile.empty())
524     MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
525 }
526 
527 static InlineParams
528 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
529   auto O3 = PassBuilder::O3;
530   unsigned OptLevel = Level > O3 ? 2 : Level;
531   unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
532   return getInlineParams(OptLevel, SizeLevel);
533 }
534 
535 ModulePassManager
536 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
537                                                ThinLTOPhase Phase,
538                                                bool DebugLogging) {
539   ModulePassManager MPM(DebugLogging);
540 
541   // Do basic inference of function attributes from known properties of system
542   // libraries and other oracles.
543   MPM.addPass(InferFunctionAttrsPass());
544 
545   // Create an early function pass manager to cleanup the output of the
546   // frontend.
547   FunctionPassManager EarlyFPM(DebugLogging);
548   EarlyFPM.addPass(SimplifyCFGPass());
549   EarlyFPM.addPass(SROA());
550   EarlyFPM.addPass(EarlyCSEPass());
551   EarlyFPM.addPass(LowerExpectIntrinsicPass());
552   if (Level == O3)
553     EarlyFPM.addPass(CallSiteSplittingPass());
554 
555   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
556   // to convert bitcast to direct calls so that they can be inlined during the
557   // profile annotation prepration step.
558   // More details about SamplePGO design can be found in:
559   // https://research.google.com/pubs/pub45290.html
560   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
561   if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
562       Phase == ThinLTOPhase::PostLink)
563     EarlyFPM.addPass(InstCombinePass());
564   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
565 
566   if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
567     // Annotate sample profile right after early FPM to ensure freshness of
568     // the debug info.
569     MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
570                                         Phase == ThinLTOPhase::PreLink));
571     // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
572     // for the profile annotation to be accurate in the ThinLTO backend.
573     if (Phase != ThinLTOPhase::PreLink)
574       // We perform early indirect call promotion here, before globalopt.
575       // This is important for the ThinLTO backend phase because otherwise
576       // imported available_externally functions look unreferenced and are
577       // removed.
578       MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
579                                            true));
580   }
581 
582   // Interprocedural constant propagation now that basic cleanup has occured
583   // and prior to optimizing globals.
584   // FIXME: This position in the pipeline hasn't been carefully considered in
585   // years, it should be re-analyzed.
586   MPM.addPass(IPSCCPPass());
587 
588   // Attach metadata to indirect call sites indicating the set of functions
589   // they may target at run-time. This should follow IPSCCP.
590   MPM.addPass(CalledValuePropagationPass());
591 
592   // Optimize globals to try and fold them into constants.
593   MPM.addPass(GlobalOptPass());
594 
595   // Promote any localized globals to SSA registers.
596   // FIXME: Should this instead by a run of SROA?
597   // FIXME: We should probably run instcombine and simplify-cfg afterward to
598   // delete control flows that are dead once globals have been folded to
599   // constants.
600   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
601 
602   // Remove any dead arguments exposed by cleanups and constand folding
603   // globals.
604   MPM.addPass(DeadArgumentEliminationPass());
605 
606   // Create a small function pass pipeline to cleanup after all the global
607   // optimizations.
608   FunctionPassManager GlobalCleanupPM(DebugLogging);
609   GlobalCleanupPM.addPass(InstCombinePass());
610   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
611 
612   GlobalCleanupPM.addPass(SimplifyCFGPass());
613   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
614 
615   // Add all the requested passes for instrumentation PGO, if requested.
616   if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
617       (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
618     addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
619                       PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
620     MPM.addPass(PGOIndirectCallPromotion(false, false));
621   }
622 
623   // Require the GlobalsAA analysis for the module so we can query it within
624   // the CGSCC pipeline.
625   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
626 
627   // Require the ProfileSummaryAnalysis for the module so we can query it within
628   // the inliner pass.
629   MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
630 
631   // Now begin the main postorder CGSCC pipeline.
632   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
633   // manager and trying to emulate its precise behavior. Much of this doesn't
634   // make a lot of sense and we should revisit the core CGSCC structure.
635   CGSCCPassManager MainCGPipeline(DebugLogging);
636 
637   // Note: historically, the PruneEH pass was run first to deduce nounwind and
638   // generally clean up exception handling overhead. It isn't clear this is
639   // valuable as the inliner doesn't currently care whether it is inlining an
640   // invoke or a call.
641 
642   // Run the inliner first. The theory is that we are walking bottom-up and so
643   // the callees have already been fully optimized, and we want to inline them
644   // into the callers so that our optimizations can reflect that.
645   // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
646   // because it makes profile annotation in the backend inaccurate.
647   InlineParams IP = getInlineParamsFromOptLevel(Level);
648   if (Phase == ThinLTOPhase::PreLink &&
649       PGOOpt && !PGOOpt->SampleProfileFile.empty())
650     IP.HotCallSiteThreshold = 0;
651   MainCGPipeline.addPass(InlinerPass(IP));
652 
653   // Now deduce any function attributes based in the current code.
654   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
655 
656   // When at O3 add argument promotion to the pass pipeline.
657   // FIXME: It isn't at all clear why this should be limited to O3.
658   if (Level == O3)
659     MainCGPipeline.addPass(ArgumentPromotionPass());
660 
661   // Lastly, add the core function simplification pipeline nested inside the
662   // CGSCC walk.
663   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
664       buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
665 
666   for (auto &C : CGSCCOptimizerLateEPCallbacks)
667     C(MainCGPipeline, Level);
668 
669   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
670   // to detect when we devirtualize indirect calls and iterate the SCC passes
671   // in that case to try and catch knock-on inlining or function attrs
672   // opportunities. Then we add it to the module pipeline by walking the SCCs
673   // in postorder (or bottom-up).
674   MPM.addPass(
675       createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
676           std::move(MainCGPipeline), MaxDevirtIterations)));
677 
678   return MPM;
679 }
680 
681 ModulePassManager
682 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
683                                              bool DebugLogging) {
684   ModulePassManager MPM(DebugLogging);
685 
686   // Optimize globals now that the module is fully simplified.
687   MPM.addPass(GlobalOptPass());
688   MPM.addPass(GlobalDCEPass());
689 
690   // Run partial inlining pass to partially inline functions that have
691   // large bodies.
692   if (RunPartialInlining)
693     MPM.addPass(PartialInlinerPass());
694 
695   // Remove avail extern fns and globals definitions since we aren't compiling
696   // an object file for later LTO. For LTO we want to preserve these so they
697   // are eligible for inlining at link-time. Note if they are unreferenced they
698   // will be removed by GlobalDCE later, so this only impacts referenced
699   // available externally globals. Eventually they will be suppressed during
700   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
701   // may make globals referenced by available external functions dead and saves
702   // running remaining passes on the eliminated functions.
703   MPM.addPass(EliminateAvailableExternallyPass());
704 
705   // Do RPO function attribute inference across the module to forward-propagate
706   // attributes where applicable.
707   // FIXME: Is this really an optimization rather than a canonicalization?
708   MPM.addPass(ReversePostOrderFunctionAttrsPass());
709 
710   // Re-require GloblasAA here prior to function passes. This is particularly
711   // useful as the above will have inlined, DCE'ed, and function-attr
712   // propagated everything. We should at this point have a reasonably minimal
713   // and richly annotated call graph. By computing aliasing and mod/ref
714   // information for all local globals here, the late loop passes and notably
715   // the vectorizer will be able to use them to help recognize vectorizable
716   // memory operations.
717   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
718 
719   FunctionPassManager OptimizePM(DebugLogging);
720   OptimizePM.addPass(Float2IntPass());
721   // FIXME: We need to run some loop optimizations to re-rotate loops after
722   // simplify-cfg and others undo their rotation.
723 
724   // Optimize the loop execution. These passes operate on entire loop nests
725   // rather than on each loop in an inside-out manner, and so they are actually
726   // function passes.
727 
728   for (auto &C : VectorizerStartEPCallbacks)
729     C(OptimizePM, Level);
730 
731   // First rotate loops that may have been un-rotated by prior passes.
732   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
733 
734   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
735   // into separate loop that would otherwise inhibit vectorization.  This is
736   // currently only performed for loops marked with the metadata
737   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
738   OptimizePM.addPass(LoopDistributePass());
739 
740   // Now run the core loop vectorizer.
741   OptimizePM.addPass(LoopVectorizePass());
742 
743   // Eliminate loads by forwarding stores from the previous iteration to loads
744   // of the current iteration.
745   OptimizePM.addPass(LoopLoadEliminationPass());
746 
747   // Cleanup after the loop optimization passes.
748   OptimizePM.addPass(InstCombinePass());
749 
750 
751   // Now that we've formed fast to execute loop structures, we do further
752   // optimizations. These are run afterward as they might block doing complex
753   // analyses and transforms such as what are needed for loop vectorization.
754 
755   // Optimize parallel scalar instruction chains into SIMD instructions.
756   OptimizePM.addPass(SLPVectorizerPass());
757 
758   // Cleanup after all of the vectorizers.
759   OptimizePM.addPass(SimplifyCFGPass());
760   OptimizePM.addPass(InstCombinePass());
761 
762   // Unroll small loops to hide loop backedge latency and saturate any parallel
763   // execution resources of an out-of-order processor. We also then need to
764   // clean up redundancies and loop invariant code.
765   // FIXME: It would be really good to use a loop-integrated instruction
766   // combiner for cleanup here so that the unrolling and LICM can be pipelined
767   // across the loop nests.
768   OptimizePM.addPass(LoopUnrollPass(Level));
769   OptimizePM.addPass(InstCombinePass());
770   OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
771   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
772 
773   // Now that we've vectorized and unrolled loops, we may have more refined
774   // alignment information, try to re-derive it here.
775   OptimizePM.addPass(AlignmentFromAssumptionsPass());
776 
777   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
778   // canonicalization pass that enables other optimizations. As a result,
779   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
780   // result too early.
781   OptimizePM.addPass(LoopSinkPass());
782 
783   // And finally clean up LCSSA form before generating code.
784   OptimizePM.addPass(InstSimplifierPass());
785 
786   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
787   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
788   // flattening of blocks.
789   OptimizePM.addPass(DivRemPairsPass());
790 
791   // LoopSink (and other loop passes since the last simplifyCFG) might have
792   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
793   OptimizePM.addPass(SimplifyCFGPass());
794 
795   // Add the core optimizing pipeline.
796   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
797 
798   // Now we need to do some global optimization transforms.
799   // FIXME: It would seem like these should come first in the optimization
800   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
801   // ordering here.
802   MPM.addPass(GlobalDCEPass());
803   MPM.addPass(ConstantMergePass());
804 
805   return MPM;
806 }
807 
808 ModulePassManager
809 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
810                                            bool DebugLogging) {
811   assert(Level != O0 && "Must request optimizations for the default pipeline!");
812 
813   ModulePassManager MPM(DebugLogging);
814 
815   // Force any function attributes we want the rest of the pipeline to observe.
816   MPM.addPass(ForceFunctionAttrsPass());
817 
818   if (PGOOpt && PGOOpt->SamplePGOSupport)
819     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
820 
821   // Add the core simplification pipeline.
822   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
823                                                 DebugLogging));
824 
825   // Now add the optimization pipeline.
826   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
827 
828   return MPM;
829 }
830 
831 ModulePassManager
832 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
833                                                 bool DebugLogging) {
834   assert(Level != O0 && "Must request optimizations for the default pipeline!");
835 
836   ModulePassManager MPM(DebugLogging);
837 
838   // Force any function attributes we want the rest of the pipeline to observe.
839   MPM.addPass(ForceFunctionAttrsPass());
840 
841   if (PGOOpt && PGOOpt->SamplePGOSupport)
842     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
843 
844   // If we are planning to perform ThinLTO later, we don't bloat the code with
845   // unrolling/vectorization/... now. Just simplify the module as much as we
846   // can.
847   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
848                                                 DebugLogging));
849 
850   // Run partial inlining pass to partially inline functions that have
851   // large bodies.
852   // FIXME: It isn't clear whether this is really the right place to run this
853   // in ThinLTO. Because there is another canonicalization and simplification
854   // phase that will run after the thin link, running this here ends up with
855   // less information than will be available later and it may grow functions in
856   // ways that aren't beneficial.
857   if (RunPartialInlining)
858     MPM.addPass(PartialInlinerPass());
859 
860   // Reduce the size of the IR as much as possible.
861   MPM.addPass(GlobalOptPass());
862 
863   return MPM;
864 }
865 
866 ModulePassManager
867 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
868                                          bool DebugLogging) {
869   // FIXME: The summary index is not hooked in the new pass manager yet.
870   // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
871   // here.
872 
873   ModulePassManager MPM(DebugLogging);
874 
875   // Force any function attributes we want the rest of the pipeline to observe.
876   MPM.addPass(ForceFunctionAttrsPass());
877 
878   // During the ThinLTO backend phase we perform early indirect call promotion
879   // here, before globalopt. Otherwise imported available_externally functions
880   // look unreferenced and are removed.
881   // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
882   //        with SamplePGO.
883   if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
884     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
885                                          false /* SamplePGO */));
886 
887   // Add the core simplification pipeline.
888   MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
889                                                 DebugLogging));
890 
891   // Now add the optimization pipeline.
892   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
893 
894   return MPM;
895 }
896 
897 ModulePassManager
898 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
899                                             bool DebugLogging) {
900   assert(Level != O0 && "Must request optimizations for the default pipeline!");
901   // FIXME: We should use a customized pre-link pipeline!
902   return buildPerModuleDefaultPipeline(Level, DebugLogging);
903 }
904 
905 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
906                                                        bool DebugLogging) {
907   assert(Level != O0 && "Must request optimizations for the default pipeline!");
908   ModulePassManager MPM(DebugLogging);
909 
910   // Remove unused virtual tables to improve the quality of code generated by
911   // whole-program devirtualization and bitset lowering.
912   MPM.addPass(GlobalDCEPass());
913 
914   // Force any function attributes we want the rest of the pipeline to observe.
915   MPM.addPass(ForceFunctionAttrsPass());
916 
917   // Do basic inference of function attributes from known properties of system
918   // libraries and other oracles.
919   MPM.addPass(InferFunctionAttrsPass());
920 
921   if (Level > 1) {
922     FunctionPassManager EarlyFPM(DebugLogging);
923     EarlyFPM.addPass(CallSiteSplittingPass());
924     MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
925 
926     // Indirect call promotion. This should promote all the targets that are
927     // left by the earlier promotion pass that promotes intra-module targets.
928     // This two-step promotion is to save the compile time. For LTO, it should
929     // produce the same result as if we only do promotion here.
930     MPM.addPass(PGOIndirectCallPromotion(
931         true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
932     // Propagate constants at call sites into the functions they call.  This
933     // opens opportunities for globalopt (and inlining) by substituting function
934     // pointers passed as arguments to direct uses of functions.
935    MPM.addPass(IPSCCPPass());
936 
937    // Attach metadata to indirect call sites indicating the set of functions
938    // they may target at run-time. This should follow IPSCCP.
939    MPM.addPass(CalledValuePropagationPass());
940   }
941 
942   // Now deduce any function attributes based in the current code.
943   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
944               PostOrderFunctionAttrsPass()));
945 
946   // Do RPO function attribute inference across the module to forward-propagate
947   // attributes where applicable.
948   // FIXME: Is this really an optimization rather than a canonicalization?
949   MPM.addPass(ReversePostOrderFunctionAttrsPass());
950 
951   // Use inragne annotations on GEP indices to split globals where beneficial.
952   MPM.addPass(GlobalSplitPass());
953 
954   // Run whole program optimization of virtual call when the list of callees
955   // is fixed.
956   MPM.addPass(WholeProgramDevirtPass());
957 
958   // Stop here at -O1.
959   if (Level == 1)
960     return MPM;
961 
962   // Optimize globals to try and fold them into constants.
963   MPM.addPass(GlobalOptPass());
964 
965   // Promote any localized globals to SSA registers.
966   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
967 
968   // Linking modules together can lead to duplicate global constant, only
969   // keep one copy of each constant.
970   MPM.addPass(ConstantMergePass());
971 
972   // Remove unused arguments from functions.
973   MPM.addPass(DeadArgumentEliminationPass());
974 
975   // Reduce the code after globalopt and ipsccp.  Both can open up significant
976   // simplification opportunities, and both can propagate functions through
977   // function pointers.  When this happens, we often have to resolve varargs
978   // calls, etc, so let instcombine do this.
979   FunctionPassManager PeepholeFPM(DebugLogging);
980   PeepholeFPM.addPass(InstCombinePass());
981   invokePeepholeEPCallbacks(PeepholeFPM, Level);
982 
983   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
984 
985   // Note: historically, the PruneEH pass was run first to deduce nounwind and
986   // generally clean up exception handling overhead. It isn't clear this is
987   // valuable as the inliner doesn't currently care whether it is inlining an
988   // invoke or a call.
989   // Run the inliner now.
990   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
991       InlinerPass(getInlineParamsFromOptLevel(Level))));
992 
993   // Optimize globals again after we ran the inliner.
994   MPM.addPass(GlobalOptPass());
995 
996   // Garbage collect dead functions.
997   // FIXME: Add ArgumentPromotion pass after once it's ported.
998   MPM.addPass(GlobalDCEPass());
999 
1000   FunctionPassManager FPM(DebugLogging);
1001   // The IPO Passes may leave cruft around. Clean up after them.
1002   FPM.addPass(InstCombinePass());
1003   invokePeepholeEPCallbacks(FPM, Level);
1004 
1005   FPM.addPass(JumpThreadingPass());
1006 
1007   // Break up allocas
1008   FPM.addPass(SROA());
1009 
1010   // Run a few AA driver optimizations here and now to cleanup the code.
1011   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1012 
1013   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1014               PostOrderFunctionAttrsPass()));
1015   // FIXME: here we run IP alias analysis in the legacy PM.
1016 
1017   FunctionPassManager MainFPM;
1018 
1019   // FIXME: once we fix LoopPass Manager, add LICM here.
1020   // FIXME: once we provide support for enabling MLSM, add it here.
1021   // FIXME: once we provide support for enabling NewGVN, add it here.
1022   if (RunNewGVN)
1023     MainFPM.addPass(NewGVNPass());
1024   else
1025     MainFPM.addPass(GVN());
1026 
1027   // Remove dead memcpy()'s.
1028   MainFPM.addPass(MemCpyOptPass());
1029 
1030   // Nuke dead stores.
1031   MainFPM.addPass(DSEPass());
1032 
1033   // FIXME: at this point, we run a bunch of loop passes:
1034   // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1035   // loopVectorize. Enable them once the remaining issue with LPM
1036   // are sorted out.
1037 
1038   MainFPM.addPass(InstCombinePass());
1039   MainFPM.addPass(SimplifyCFGPass());
1040   MainFPM.addPass(SCCPPass());
1041   MainFPM.addPass(InstCombinePass());
1042   MainFPM.addPass(BDCEPass());
1043 
1044   // FIXME: We may want to run SLPVectorizer here.
1045   // After vectorization, assume intrinsics may tell us more
1046   // about pointer alignments.
1047 #if 0
1048   MainFPM.add(AlignmentFromAssumptionsPass());
1049 #endif
1050 
1051   // FIXME: Conditionally run LoadCombine here, after it's ported
1052   // (in case we still have this pass, given its questionable usefulness).
1053 
1054   MainFPM.addPass(InstCombinePass());
1055   invokePeepholeEPCallbacks(MainFPM, Level);
1056   MainFPM.addPass(JumpThreadingPass());
1057   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1058 
1059   // Create a function that performs CFI checks for cross-DSO calls with
1060   // targets in the current module.
1061   MPM.addPass(CrossDSOCFIPass());
1062 
1063   // Lower type metadata and the type.test intrinsic. This pass supports
1064   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1065   // to be run at link time if CFI is enabled. This pass does nothing if
1066   // CFI is disabled.
1067   // Enable once we add support for the summary in the new PM.
1068 #if 0
1069   MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1070                                            PassSummaryAction::None,
1071                                 Summary));
1072 #endif
1073 
1074   // Add late LTO optimization passes.
1075   // Delete basic blocks, which optimization passes may have killed.
1076   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1077 
1078   // Drop bodies of available eternally objects to improve GlobalDCE.
1079   MPM.addPass(EliminateAvailableExternallyPass());
1080 
1081   // Now that we have optimized the program, discard unreachable functions.
1082   MPM.addPass(GlobalDCEPass());
1083 
1084   // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
1085   return MPM;
1086 }
1087 
1088 AAManager PassBuilder::buildDefaultAAPipeline() {
1089   AAManager AA;
1090 
1091   // The order in which these are registered determines their priority when
1092   // being queried.
1093 
1094   // First we register the basic alias analysis that provides the majority of
1095   // per-function local AA logic. This is a stateless, on-demand local set of
1096   // AA techniques.
1097   AA.registerFunctionAnalysis<BasicAA>();
1098 
1099   // Next we query fast, specialized alias analyses that wrap IR-embedded
1100   // information about aliasing.
1101   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1102   AA.registerFunctionAnalysis<TypeBasedAA>();
1103 
1104   // Add support for querying global aliasing information when available.
1105   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1106   // analysis, all that the `AAManager` can do is query for any *cached*
1107   // results from `GlobalsAA` through a readonly proxy.
1108   AA.registerModuleAnalysis<GlobalsAA>();
1109 
1110   return AA;
1111 }
1112 
1113 static Optional<int> parseRepeatPassName(StringRef Name) {
1114   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1115     return None;
1116   int Count;
1117   if (Name.getAsInteger(0, Count) || Count <= 0)
1118     return None;
1119   return Count;
1120 }
1121 
1122 static Optional<int> parseDevirtPassName(StringRef Name) {
1123   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1124     return None;
1125   int Count;
1126   if (Name.getAsInteger(0, Count) || Count <= 0)
1127     return None;
1128   return Count;
1129 }
1130 
1131 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1132 /// alias.
1133 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1134   return Name.startswith("default") || Name.startswith("thinlto") ||
1135          Name.startswith("lto");
1136 }
1137 
1138 /// Tests whether registered callbacks will accept a given pass name.
1139 ///
1140 /// When parsing a pipeline text, the type of the outermost pipeline may be
1141 /// omitted, in which case the type is automatically determined from the first
1142 /// pass name in the text. This may be a name that is handled through one of the
1143 /// callbacks. We check this through the oridinary parsing callbacks by setting
1144 /// up a dummy PassManager in order to not force the client to also handle this
1145 /// type of query.
1146 template <typename PassManagerT, typename CallbacksT>
1147 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1148   if (!Callbacks.empty()) {
1149     PassManagerT DummyPM;
1150     for (auto &CB : Callbacks)
1151       if (CB(Name, DummyPM, {}))
1152         return true;
1153   }
1154   return false;
1155 }
1156 
1157 template <typename CallbacksT>
1158 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1159   // Manually handle aliases for pre-configured pipeline fragments.
1160   if (startsWithDefaultPipelineAliasPrefix(Name))
1161     return DefaultAliasRegex.match(Name);
1162 
1163   // Explicitly handle pass manager names.
1164   if (Name == "module")
1165     return true;
1166   if (Name == "cgscc")
1167     return true;
1168   if (Name == "function")
1169     return true;
1170 
1171   // Explicitly handle custom-parsed pass names.
1172   if (parseRepeatPassName(Name))
1173     return true;
1174 
1175 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1176   if (Name == NAME)                                                            \
1177     return true;
1178 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1179   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1180     return true;
1181 #include "PassRegistry.def"
1182 
1183   return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1184 }
1185 
1186 template <typename CallbacksT>
1187 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1188   // Explicitly handle pass manager names.
1189   if (Name == "cgscc")
1190     return true;
1191   if (Name == "function")
1192     return true;
1193 
1194   // Explicitly handle custom-parsed pass names.
1195   if (parseRepeatPassName(Name))
1196     return true;
1197   if (parseDevirtPassName(Name))
1198     return true;
1199 
1200 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1201   if (Name == NAME)                                                            \
1202     return true;
1203 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1204   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1205     return true;
1206 #include "PassRegistry.def"
1207 
1208   return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1209 }
1210 
1211 template <typename CallbacksT>
1212 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1213   // Explicitly handle pass manager names.
1214   if (Name == "function")
1215     return true;
1216   if (Name == "loop")
1217     return true;
1218 
1219   // Explicitly handle custom-parsed pass names.
1220   if (parseRepeatPassName(Name))
1221     return true;
1222 
1223 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1224   if (Name == NAME)                                                            \
1225     return true;
1226 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1227   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1228     return true;
1229 #include "PassRegistry.def"
1230 
1231   return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1232 }
1233 
1234 template <typename CallbacksT>
1235 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1236   // Explicitly handle pass manager names.
1237   if (Name == "loop")
1238     return true;
1239 
1240   // Explicitly handle custom-parsed pass names.
1241   if (parseRepeatPassName(Name))
1242     return true;
1243 
1244 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1245   if (Name == NAME)                                                            \
1246     return true;
1247 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1248   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1249     return true;
1250 #include "PassRegistry.def"
1251 
1252   return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1253 }
1254 
1255 Optional<std::vector<PassBuilder::PipelineElement>>
1256 PassBuilder::parsePipelineText(StringRef Text) {
1257   std::vector<PipelineElement> ResultPipeline;
1258 
1259   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1260       &ResultPipeline};
1261   for (;;) {
1262     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1263     size_t Pos = Text.find_first_of(",()");
1264     Pipeline.push_back({Text.substr(0, Pos), {}});
1265 
1266     // If we have a single terminating name, we're done.
1267     if (Pos == Text.npos)
1268       break;
1269 
1270     char Sep = Text[Pos];
1271     Text = Text.substr(Pos + 1);
1272     if (Sep == ',')
1273       // Just a name ending in a comma, continue.
1274       continue;
1275 
1276     if (Sep == '(') {
1277       // Push the inner pipeline onto the stack to continue processing.
1278       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1279       continue;
1280     }
1281 
1282     assert(Sep == ')' && "Bogus separator!");
1283     // When handling the close parenthesis, we greedily consume them to avoid
1284     // empty strings in the pipeline.
1285     do {
1286       // If we try to pop the outer pipeline we have unbalanced parentheses.
1287       if (PipelineStack.size() == 1)
1288         return None;
1289 
1290       PipelineStack.pop_back();
1291     } while (Text.consume_front(")"));
1292 
1293     // Check if we've finished parsing.
1294     if (Text.empty())
1295       break;
1296 
1297     // Otherwise, the end of an inner pipeline always has to be followed by
1298     // a comma, and then we can continue.
1299     if (!Text.consume_front(","))
1300       return None;
1301   }
1302 
1303   if (PipelineStack.size() > 1)
1304     // Unbalanced paretheses.
1305     return None;
1306 
1307   assert(PipelineStack.back() == &ResultPipeline &&
1308          "Wrong pipeline at the bottom of the stack!");
1309   return {std::move(ResultPipeline)};
1310 }
1311 
1312 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1313                                   const PipelineElement &E, bool VerifyEachPass,
1314                                   bool DebugLogging) {
1315   auto &Name = E.Name;
1316   auto &InnerPipeline = E.InnerPipeline;
1317 
1318   // First handle complex passes like the pass managers which carry pipelines.
1319   if (!InnerPipeline.empty()) {
1320     if (Name == "module") {
1321       ModulePassManager NestedMPM(DebugLogging);
1322       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1323                                    DebugLogging))
1324         return false;
1325       MPM.addPass(std::move(NestedMPM));
1326       return true;
1327     }
1328     if (Name == "cgscc") {
1329       CGSCCPassManager CGPM(DebugLogging);
1330       if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1331                                   DebugLogging))
1332         return false;
1333       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1334       return true;
1335     }
1336     if (Name == "function") {
1337       FunctionPassManager FPM(DebugLogging);
1338       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1339                                      DebugLogging))
1340         return false;
1341       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1342       return true;
1343     }
1344     if (auto Count = parseRepeatPassName(Name)) {
1345       ModulePassManager NestedMPM(DebugLogging);
1346       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1347                                    DebugLogging))
1348         return false;
1349       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1350       return true;
1351     }
1352 
1353     for (auto &C : ModulePipelineParsingCallbacks)
1354       if (C(Name, MPM, InnerPipeline))
1355         return true;
1356 
1357     // Normal passes can't have pipelines.
1358     return false;
1359   }
1360 
1361   // Manually handle aliases for pre-configured pipeline fragments.
1362   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1363     SmallVector<StringRef, 3> Matches;
1364     if (!DefaultAliasRegex.match(Name, &Matches))
1365       return false;
1366     assert(Matches.size() == 3 && "Must capture two matched strings!");
1367 
1368     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1369                               .Case("O0", O0)
1370                               .Case("O1", O1)
1371                               .Case("O2", O2)
1372                               .Case("O3", O3)
1373                               .Case("Os", Os)
1374                               .Case("Oz", Oz);
1375     if (L == O0)
1376       // At O0 we do nothing at all!
1377       return true;
1378 
1379     if (Matches[1] == "default") {
1380       MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1381     } else if (Matches[1] == "thinlto-pre-link") {
1382       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1383     } else if (Matches[1] == "thinlto") {
1384       MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1385     } else if (Matches[1] == "lto-pre-link") {
1386       MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1387     } else {
1388       assert(Matches[1] == "lto" && "Not one of the matched options!");
1389       MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1390     }
1391     return true;
1392   }
1393 
1394   // Finally expand the basic registered passes from the .inc file.
1395 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1396   if (Name == NAME) {                                                          \
1397     MPM.addPass(CREATE_PASS);                                                  \
1398     return true;                                                               \
1399   }
1400 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1401   if (Name == "require<" NAME ">") {                                           \
1402     MPM.addPass(                                                               \
1403         RequireAnalysisPass<                                                   \
1404             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
1405     return true;                                                               \
1406   }                                                                            \
1407   if (Name == "invalidate<" NAME ">") {                                        \
1408     MPM.addPass(InvalidateAnalysisPass<                                        \
1409                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1410     return true;                                                               \
1411   }
1412 #include "PassRegistry.def"
1413 
1414   for (auto &C : ModulePipelineParsingCallbacks)
1415     if (C(Name, MPM, InnerPipeline))
1416       return true;
1417   return false;
1418 }
1419 
1420 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1421                                  const PipelineElement &E, bool VerifyEachPass,
1422                                  bool DebugLogging) {
1423   auto &Name = E.Name;
1424   auto &InnerPipeline = E.InnerPipeline;
1425 
1426   // First handle complex passes like the pass managers which carry pipelines.
1427   if (!InnerPipeline.empty()) {
1428     if (Name == "cgscc") {
1429       CGSCCPassManager NestedCGPM(DebugLogging);
1430       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1431                                   DebugLogging))
1432         return false;
1433       // Add the nested pass manager with the appropriate adaptor.
1434       CGPM.addPass(std::move(NestedCGPM));
1435       return true;
1436     }
1437     if (Name == "function") {
1438       FunctionPassManager FPM(DebugLogging);
1439       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1440                                      DebugLogging))
1441         return false;
1442       // Add the nested pass manager with the appropriate adaptor.
1443       CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1444       return true;
1445     }
1446     if (auto Count = parseRepeatPassName(Name)) {
1447       CGSCCPassManager NestedCGPM(DebugLogging);
1448       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1449                                   DebugLogging))
1450         return false;
1451       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1452       return true;
1453     }
1454     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1455       CGSCCPassManager NestedCGPM(DebugLogging);
1456       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1457                                   DebugLogging))
1458         return false;
1459       CGPM.addPass(
1460           createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1461       return true;
1462     }
1463 
1464     for (auto &C : CGSCCPipelineParsingCallbacks)
1465       if (C(Name, CGPM, InnerPipeline))
1466         return true;
1467 
1468     // Normal passes can't have pipelines.
1469     return false;
1470   }
1471 
1472 // Now expand the basic registered passes from the .inc file.
1473 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1474   if (Name == NAME) {                                                          \
1475     CGPM.addPass(CREATE_PASS);                                                 \
1476     return true;                                                               \
1477   }
1478 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1479   if (Name == "require<" NAME ">") {                                           \
1480     CGPM.addPass(RequireAnalysisPass<                                          \
1481                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
1482                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
1483                  CGSCCUpdateResult &>());                                      \
1484     return true;                                                               \
1485   }                                                                            \
1486   if (Name == "invalidate<" NAME ">") {                                        \
1487     CGPM.addPass(InvalidateAnalysisPass<                                       \
1488                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
1489     return true;                                                               \
1490   }
1491 #include "PassRegistry.def"
1492 
1493   for (auto &C : CGSCCPipelineParsingCallbacks)
1494     if (C(Name, CGPM, InnerPipeline))
1495       return true;
1496   return false;
1497 }
1498 
1499 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1500                                     const PipelineElement &E,
1501                                     bool VerifyEachPass, bool DebugLogging) {
1502   auto &Name = E.Name;
1503   auto &InnerPipeline = E.InnerPipeline;
1504 
1505   // First handle complex passes like the pass managers which carry pipelines.
1506   if (!InnerPipeline.empty()) {
1507     if (Name == "function") {
1508       FunctionPassManager NestedFPM(DebugLogging);
1509       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1510                                      DebugLogging))
1511         return false;
1512       // Add the nested pass manager with the appropriate adaptor.
1513       FPM.addPass(std::move(NestedFPM));
1514       return true;
1515     }
1516     if (Name == "loop") {
1517       LoopPassManager LPM(DebugLogging);
1518       if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1519                                  DebugLogging))
1520         return false;
1521       // Add the nested pass manager with the appropriate adaptor.
1522       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1523       return true;
1524     }
1525     if (auto Count = parseRepeatPassName(Name)) {
1526       FunctionPassManager NestedFPM(DebugLogging);
1527       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1528                                      DebugLogging))
1529         return false;
1530       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1531       return true;
1532     }
1533 
1534     for (auto &C : FunctionPipelineParsingCallbacks)
1535       if (C(Name, FPM, InnerPipeline))
1536         return true;
1537 
1538     // Normal passes can't have pipelines.
1539     return false;
1540   }
1541 
1542 // Now expand the basic registered passes from the .inc file.
1543 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1544   if (Name == NAME) {                                                          \
1545     FPM.addPass(CREATE_PASS);                                                  \
1546     return true;                                                               \
1547   }
1548 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1549   if (Name == "require<" NAME ">") {                                           \
1550     FPM.addPass(                                                               \
1551         RequireAnalysisPass<                                                   \
1552             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
1553     return true;                                                               \
1554   }                                                                            \
1555   if (Name == "invalidate<" NAME ">") {                                        \
1556     FPM.addPass(InvalidateAnalysisPass<                                        \
1557                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1558     return true;                                                               \
1559   }
1560 #include "PassRegistry.def"
1561 
1562   for (auto &C : FunctionPipelineParsingCallbacks)
1563     if (C(Name, FPM, InnerPipeline))
1564       return true;
1565   return false;
1566 }
1567 
1568 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1569                                 bool VerifyEachPass, bool DebugLogging) {
1570   StringRef Name = E.Name;
1571   auto &InnerPipeline = E.InnerPipeline;
1572 
1573   // First handle complex passes like the pass managers which carry pipelines.
1574   if (!InnerPipeline.empty()) {
1575     if (Name == "loop") {
1576       LoopPassManager NestedLPM(DebugLogging);
1577       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1578                                  DebugLogging))
1579         return false;
1580       // Add the nested pass manager with the appropriate adaptor.
1581       LPM.addPass(std::move(NestedLPM));
1582       return true;
1583     }
1584     if (auto Count = parseRepeatPassName(Name)) {
1585       LoopPassManager NestedLPM(DebugLogging);
1586       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1587                                  DebugLogging))
1588         return false;
1589       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1590       return true;
1591     }
1592 
1593     for (auto &C : LoopPipelineParsingCallbacks)
1594       if (C(Name, LPM, InnerPipeline))
1595         return true;
1596 
1597     // Normal passes can't have pipelines.
1598     return false;
1599   }
1600 
1601 // Now expand the basic registered passes from the .inc file.
1602 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1603   if (Name == NAME) {                                                          \
1604     LPM.addPass(CREATE_PASS);                                                  \
1605     return true;                                                               \
1606   }
1607 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1608   if (Name == "require<" NAME ">") {                                           \
1609     LPM.addPass(RequireAnalysisPass<                                           \
1610                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
1611                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
1612                 LPMUpdater &>());                                              \
1613     return true;                                                               \
1614   }                                                                            \
1615   if (Name == "invalidate<" NAME ">") {                                        \
1616     LPM.addPass(InvalidateAnalysisPass<                                        \
1617                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1618     return true;                                                               \
1619   }
1620 #include "PassRegistry.def"
1621 
1622   for (auto &C : LoopPipelineParsingCallbacks)
1623     if (C(Name, LPM, InnerPipeline))
1624       return true;
1625   return false;
1626 }
1627 
1628 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1629 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1630   if (Name == NAME) {                                                          \
1631     AA.registerModuleAnalysis<                                                 \
1632         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1633     return true;                                                               \
1634   }
1635 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1636   if (Name == NAME) {                                                          \
1637     AA.registerFunctionAnalysis<                                               \
1638         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1639     return true;                                                               \
1640   }
1641 #include "PassRegistry.def"
1642 
1643   for (auto &C : AAParsingCallbacks)
1644     if (C(Name, AA))
1645       return true;
1646   return false;
1647 }
1648 
1649 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1650                                         ArrayRef<PipelineElement> Pipeline,
1651                                         bool VerifyEachPass,
1652                                         bool DebugLogging) {
1653   for (const auto &Element : Pipeline) {
1654     if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1655       return false;
1656     // FIXME: No verifier support for Loop passes!
1657   }
1658   return true;
1659 }
1660 
1661 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1662                                             ArrayRef<PipelineElement> Pipeline,
1663                                             bool VerifyEachPass,
1664                                             bool DebugLogging) {
1665   for (const auto &Element : Pipeline) {
1666     if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1667       return false;
1668     if (VerifyEachPass)
1669       FPM.addPass(VerifierPass());
1670   }
1671   return true;
1672 }
1673 
1674 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1675                                          ArrayRef<PipelineElement> Pipeline,
1676                                          bool VerifyEachPass,
1677                                          bool DebugLogging) {
1678   for (const auto &Element : Pipeline) {
1679     if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1680       return false;
1681     // FIXME: No verifier support for CGSCC passes!
1682   }
1683   return true;
1684 }
1685 
1686 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1687                                        FunctionAnalysisManager &FAM,
1688                                        CGSCCAnalysisManager &CGAM,
1689                                        ModuleAnalysisManager &MAM) {
1690   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1691   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1692   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1693   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1694   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1695   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1696   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1697 }
1698 
1699 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1700                                           ArrayRef<PipelineElement> Pipeline,
1701                                           bool VerifyEachPass,
1702                                           bool DebugLogging) {
1703   for (const auto &Element : Pipeline) {
1704     if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1705       return false;
1706     if (VerifyEachPass)
1707       MPM.addPass(VerifierPass());
1708   }
1709   return true;
1710 }
1711 
1712 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1713 // FIXME: Should this routine accept a TargetMachine or require the caller to
1714 // pre-populate the analysis managers with target-specific stuff?
1715 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1716                                     StringRef PipelineText, bool VerifyEachPass,
1717                                     bool DebugLogging) {
1718   auto Pipeline = parsePipelineText(PipelineText);
1719   if (!Pipeline || Pipeline->empty())
1720     return false;
1721 
1722   // If the first name isn't at the module layer, wrap the pipeline up
1723   // automatically.
1724   StringRef FirstName = Pipeline->front().Name;
1725 
1726   if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1727     if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1728       Pipeline = {{"cgscc", std::move(*Pipeline)}};
1729     } else if (isFunctionPassName(FirstName,
1730                                   FunctionPipelineParsingCallbacks)) {
1731       Pipeline = {{"function", std::move(*Pipeline)}};
1732     } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
1733       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1734     } else {
1735       for (auto &C : TopLevelPipelineParsingCallbacks)
1736         if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1737           return true;
1738 
1739       // Unknown pass name!
1740       return false;
1741     }
1742   }
1743 
1744   return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1745 }
1746 
1747 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1748 bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1749                                     StringRef PipelineText, bool VerifyEachPass,
1750                                     bool DebugLogging) {
1751   auto Pipeline = parsePipelineText(PipelineText);
1752   if (!Pipeline || Pipeline->empty())
1753     return false;
1754 
1755   StringRef FirstName = Pipeline->front().Name;
1756   if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1757     return false;
1758 
1759   return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1760 }
1761 
1762 // Primary pass pipeline description parsing routine for a \c
1763 // FunctionPassManager
1764 bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1765                                     StringRef PipelineText, bool VerifyEachPass,
1766                                     bool DebugLogging) {
1767   auto Pipeline = parsePipelineText(PipelineText);
1768   if (!Pipeline || Pipeline->empty())
1769     return false;
1770 
1771   StringRef FirstName = Pipeline->front().Name;
1772   if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1773     return false;
1774 
1775   return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1776                                    DebugLogging);
1777 }
1778 
1779 // Primary pass pipeline description parsing routine for a \c LoopPassManager
1780 bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1781                                     StringRef PipelineText, bool VerifyEachPass,
1782                                     bool DebugLogging) {
1783   auto Pipeline = parsePipelineText(PipelineText);
1784   if (!Pipeline || Pipeline->empty())
1785     return false;
1786 
1787   return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1788 }
1789 
1790 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1791   // If the pipeline just consists of the word 'default' just replace the AA
1792   // manager with our default one.
1793   if (PipelineText == "default") {
1794     AA = buildDefaultAAPipeline();
1795     return true;
1796   }
1797 
1798   while (!PipelineText.empty()) {
1799     StringRef Name;
1800     std::tie(Name, PipelineText) = PipelineText.split(',');
1801     if (!parseAAPassName(AA, Name))
1802       return false;
1803   }
1804 
1805   return true;
1806 }
1807