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