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