1 //===- Parsing, selection, and construction of pass pipelines -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
16 //===----------------------------------------------------------------------===//
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"
147 #include <type_traits>
149 using namespace llvm;
151 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
152 cl::ReallyHidden, cl::init(4));
154 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
155 cl::Hidden, cl::ZeroOrMore,
156 cl::desc("Run Partial inlinining pass"));
159 RunNewGVN("enable-npm-newgvn", cl::init(false),
160 cl::Hidden, cl::ZeroOrMore,
161 cl::desc("Run NewGVN instead of GVN"));
163 static cl::opt<bool> EnableGVNHoist(
164 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
165 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
167 static Regex DefaultAliasRegex(
168 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
170 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
172 case PassBuilder::O0:
173 case PassBuilder::O1:
174 case PassBuilder::O2:
175 case PassBuilder::O3:
178 case PassBuilder::Os:
179 case PassBuilder::Oz:
182 llvm_unreachable("Invalid optimization level!");
187 /// \brief No-op module pass which does nothing.
188 struct NoOpModulePass {
189 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
190 return PreservedAnalyses::all();
192 static StringRef name() { return "NoOpModulePass"; }
195 /// \brief No-op module analysis.
196 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
197 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
198 static AnalysisKey Key;
202 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
203 static StringRef name() { return "NoOpModuleAnalysis"; }
206 /// \brief No-op CGSCC pass which does nothing.
207 struct NoOpCGSCCPass {
208 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
209 LazyCallGraph &, CGSCCUpdateResult &UR) {
210 return PreservedAnalyses::all();
212 static StringRef name() { return "NoOpCGSCCPass"; }
215 /// \brief No-op CGSCC analysis.
216 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
217 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
218 static AnalysisKey Key;
222 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
225 static StringRef name() { return "NoOpCGSCCAnalysis"; }
228 /// \brief No-op function pass which does nothing.
229 struct NoOpFunctionPass {
230 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
231 return PreservedAnalyses::all();
233 static StringRef name() { return "NoOpFunctionPass"; }
236 /// \brief No-op function analysis.
237 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
238 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
239 static AnalysisKey Key;
243 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
244 static StringRef name() { return "NoOpFunctionAnalysis"; }
247 /// \brief No-op loop pass which does nothing.
248 struct NoOpLoopPass {
249 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
250 LoopStandardAnalysisResults &, LPMUpdater &) {
251 return PreservedAnalyses::all();
253 static StringRef name() { return "NoOpLoopPass"; }
256 /// \brief No-op loop analysis.
257 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
258 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
259 static AnalysisKey Key;
263 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
266 static StringRef name() { return "NoOpLoopAnalysis"; }
269 AnalysisKey NoOpModuleAnalysis::Key;
270 AnalysisKey NoOpCGSCCAnalysis::Key;
271 AnalysisKey NoOpFunctionAnalysis::Key;
272 AnalysisKey NoOpLoopAnalysis::Key;
274 } // End anonymous namespace.
276 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
277 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
278 MAM.registerPass([&] { return CREATE_PASS; });
279 #include "PassRegistry.def"
282 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
283 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
284 CGAM.registerPass([&] { return CREATE_PASS; });
285 #include "PassRegistry.def"
288 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
289 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
290 FAM.registerPass([&] { return CREATE_PASS; });
291 #include "PassRegistry.def"
294 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
295 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
296 LAM.registerPass([&] { return CREATE_PASS; });
297 #include "PassRegistry.def"
301 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
303 assert(Level != O0 && "Must request optimizations!");
304 FunctionPassManager FPM(DebugLogging);
306 // Form SSA out of local memory accesses after breaking apart aggregates into
310 // Catch trivial redundancies
311 FPM.addPass(EarlyCSEPass());
313 // Hoisting of scalars and load expressions.
315 FPM.addPass(GVNHoistPass());
317 // Speculative execution if the target has divergent branches; otherwise nop.
318 FPM.addPass(SpeculativeExecutionPass());
320 // Optimize based on known information about branches, and cleanup afterward.
321 FPM.addPass(JumpThreadingPass());
322 FPM.addPass(CorrelatedValuePropagationPass());
323 FPM.addPass(SimplifyCFGPass());
324 FPM.addPass(InstCombinePass());
326 if (!isOptimizingForSize(Level))
327 FPM.addPass(LibCallsShrinkWrapPass());
329 FPM.addPass(TailCallElimPass());
330 FPM.addPass(SimplifyCFGPass());
332 // Form canonically associated expression trees, and simplify the trees using
333 // basic mathematical properties. For example, this will form (nearly)
334 // minimal multiplication trees.
335 FPM.addPass(ReassociatePass());
337 // Add the primary loop simplification pipeline.
338 // FIXME: Currently this is split into two loop pass pipelines because we run
339 // some function passes in between them. These can and should be replaced by
340 // loop pass equivalenst but those aren't ready yet. Specifically,
341 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
342 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
343 // the other we have is `LoopInstSimplify`.
344 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
346 // Rotate Loop - disable header duplication at -Oz
347 LPM1.addPass(LoopRotatePass(Level != Oz));
348 LPM1.addPass(LICMPass());
349 LPM1.addPass(SimpleLoopUnswitchPass());
350 LPM2.addPass(IndVarSimplifyPass());
351 LPM2.addPass(LoopIdiomRecognizePass());
352 LPM2.addPass(LoopDeletionPass());
353 // FIXME: The old pass manager has a hack to disable loop unrolling during
354 // ThinLTO when using sample PGO. Need to either fix it or port some
356 LPM2.addPass(LoopUnrollPass::createFull(Level));
358 // We provide the opt remark emitter pass for LICM to use. We only need to do
359 // this once as it is immutable.
360 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
361 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
362 FPM.addPass(SimplifyCFGPass());
363 FPM.addPass(InstCombinePass());
364 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
366 // Eliminate redundancies.
368 // These passes add substantial compile time so skip them at O1.
369 FPM.addPass(MergedLoadStoreMotionPass());
371 FPM.addPass(NewGVNPass());
376 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
377 FPM.addPass(MemCpyOptPass());
379 // Sparse conditional constant propagation.
380 // FIXME: It isn't clear why we do this *after* loop passes rather than
382 FPM.addPass(SCCPPass());
384 // Delete dead bit computations (instcombine runs after to fold away the dead
385 // computations, and then ADCE will run later to exploit any new DCE
386 // opportunities that creates).
387 FPM.addPass(BDCEPass());
389 // Run instcombine after redundancy and dead bit elimination to exploit
390 // opportunities opened up by them.
391 FPM.addPass(InstCombinePass());
393 // Re-consider control flow based optimizations after redundancy elimination,
395 FPM.addPass(JumpThreadingPass());
396 FPM.addPass(CorrelatedValuePropagationPass());
397 FPM.addPass(DSEPass());
398 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
400 // Finally, do an expensive DCE pass to catch all the dead code exposed by
401 // the simplifications and basic cleanup after all the simplifications.
402 FPM.addPass(ADCEPass());
403 FPM.addPass(SimplifyCFGPass());
404 FPM.addPass(InstCombinePass());
409 static void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
410 PassBuilder::OptimizationLevel Level,
411 bool RunProfileGen, std::string ProfileGenFile,
412 std::string ProfileUseFile) {
413 // Generally running simplification passes and the inliner with an high
414 // threshold results in smaller executables, but there may be cases where
415 // the size grows, so let's be conservative here and skip this simplification
417 if (!isOptimizingForSize(Level)) {
420 // In the old pass manager, this is a cl::opt. Should still this be one?
421 IP.DefaultThreshold = 75;
423 // FIXME: The hint threshold has the same value used by the regular inliner.
424 // This should probably be lowered after performance testing.
425 // FIXME: this comment is cargo culted from the old pass manager, revisit).
426 IP.HintThreshold = 325;
428 CGSCCPassManager CGPipeline(DebugLogging);
430 CGPipeline.addPass(InlinerPass(IP));
432 FunctionPassManager FPM;
434 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
435 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
436 FPM.addPass(InstCombinePass()); // Combine silly sequences.
438 // FIXME: Here the old pass manager inserts peephole extensions.
439 // Add them when they're supported.
440 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
442 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
445 // Delete anything that is now dead to make sure that we don't instrument
446 // dead code. Instrumentation can end up keeping dead code around and
447 // dramatically increase code size.
448 MPM.addPass(GlobalDCEPass());
451 MPM.addPass(PGOInstrumentationGen());
453 // Add the profile lowering pass.
454 InstrProfOptions Options;
455 if (!ProfileGenFile.empty())
456 Options.InstrProfileOutput = ProfileGenFile;
457 MPM.addPass(InstrProfiling(Options));
460 if (!ProfileUseFile.empty())
461 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
465 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
467 ModulePassManager MPM(DebugLogging);
469 // Do basic inference of function attributes from known properties of system
470 // libraries and other oracles.
471 MPM.addPass(InferFunctionAttrsPass());
473 // Create an early function pass manager to cleanup the output of the
475 FunctionPassManager EarlyFPM(DebugLogging);
476 EarlyFPM.addPass(SimplifyCFGPass());
477 EarlyFPM.addPass(SROA());
478 EarlyFPM.addPass(EarlyCSEPass());
479 EarlyFPM.addPass(LowerExpectIntrinsicPass());
480 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
482 // Interprocedural constant propagation now that basic cleanup has occured
483 // and prior to optimizing globals.
484 // FIXME: This position in the pipeline hasn't been carefully considered in
485 // years, it should be re-analyzed.
486 MPM.addPass(IPSCCPPass());
488 // Optimize globals to try and fold them into constants.
489 MPM.addPass(GlobalOptPass());
491 // Promote any localized globals to SSA registers.
492 // FIXME: Should this instead by a run of SROA?
493 // FIXME: We should probably run instcombine and simplify-cfg afterward to
494 // delete control flows that are dead once globals have been folded to
496 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
498 // Remove any dead arguments exposed by cleanups and constand folding
500 MPM.addPass(DeadArgumentEliminationPass());
502 // Create a small function pass pipeline to cleanup after all the global
504 FunctionPassManager GlobalCleanupPM(DebugLogging);
505 GlobalCleanupPM.addPass(InstCombinePass());
506 GlobalCleanupPM.addPass(SimplifyCFGPass());
507 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
509 // Add all the requested passes for PGO, if requested.
511 assert(PGOOpt->RunProfileGen || PGOOpt->SamplePGO ||
512 !PGOOpt->ProfileUseFile.empty());
513 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
514 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
516 // Indirect call promotion that promotes intra-module targes only.
517 MPM.addPass(PGOIndirectCallPromotion(false, PGOOpt && PGOOpt->SamplePGO));
520 // Require the GlobalsAA analysis for the module so we can query it within
521 // the CGSCC pipeline.
522 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
524 // Require the ProfileSummaryAnalysis for the module so we can query it within
526 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
528 // Now begin the main postorder CGSCC pipeline.
529 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
530 // manager and trying to emulate its precise behavior. Much of this doesn't
531 // make a lot of sense and we should revisit the core CGSCC structure.
532 CGSCCPassManager MainCGPipeline(DebugLogging);
534 // Note: historically, the PruneEH pass was run first to deduce nounwind and
535 // generally clean up exception handling overhead. It isn't clear this is
536 // valuable as the inliner doesn't currently care whether it is inlining an
539 // Run the inliner first. The theory is that we are walking bottom-up and so
540 // the callees have already been fully optimized, and we want to inline them
541 // into the callers so that our optimizations can reflect that.
542 // FIXME; Customize the threshold based on optimization level.
543 MainCGPipeline.addPass(InlinerPass());
545 // Now deduce any function attributes based in the current code.
546 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
548 // When at O3 add argument promotion to the pass pipeline.
549 // FIXME: It isn't at all clear why this should be limited to O3.
551 MainCGPipeline.addPass(ArgumentPromotionPass());
553 // Lastly, add the core function simplification pipeline nested inside the
555 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
556 buildFunctionSimplificationPipeline(Level, DebugLogging)));
558 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
559 // to detect when we devirtualize indirect calls and iterate the SCC passes
560 // in that case to try and catch knock-on inlining or function attrs
561 // opportunities. Then we add it to the module pipeline by walking the SCCs
562 // in postorder (or bottom-up).
564 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
565 std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging)));
571 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
573 ModulePassManager MPM(DebugLogging);
575 // Optimize globals now that the module is fully simplified.
576 MPM.addPass(GlobalOptPass());
578 // Run partial inlining pass to partially inline functions that have
580 if (RunPartialInlining)
581 MPM.addPass(PartialInlinerPass());
583 // Remove avail extern fns and globals definitions since we aren't compiling
584 // an object file for later LTO. For LTO we want to preserve these so they
585 // are eligible for inlining at link-time. Note if they are unreferenced they
586 // will be removed by GlobalDCE later, so this only impacts referenced
587 // available externally globals. Eventually they will be suppressed during
588 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
589 // may make globals referenced by available external functions dead and saves
590 // running remaining passes on the eliminated functions.
591 MPM.addPass(EliminateAvailableExternallyPass());
593 // Do RPO function attribute inference across the module to forward-propagate
594 // attributes where applicable.
595 // FIXME: Is this really an optimization rather than a canonicalization?
596 MPM.addPass(ReversePostOrderFunctionAttrsPass());
598 // Re-require GloblasAA here prior to function passes. This is particularly
599 // useful as the above will have inlined, DCE'ed, and function-attr
600 // propagated everything. We should at this point have a reasonably minimal
601 // and richly annotated call graph. By computing aliasing and mod/ref
602 // information for all local globals here, the late loop passes and notably
603 // the vectorizer will be able to use them to help recognize vectorizable
604 // memory operations.
605 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
607 FunctionPassManager OptimizePM(DebugLogging);
608 OptimizePM.addPass(Float2IntPass());
609 // FIXME: We need to run some loop optimizations to re-rotate loops after
610 // simplify-cfg and others undo their rotation.
612 // Optimize the loop execution. These passes operate on entire loop nests
613 // rather than on each loop in an inside-out manner, and so they are actually
616 // First rotate loops that may have been un-rotated by prior passes.
617 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
619 // Distribute loops to allow partial vectorization. I.e. isolate dependences
620 // into separate loop that would otherwise inhibit vectorization. This is
621 // currently only performed for loops marked with the metadata
622 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
623 OptimizePM.addPass(LoopDistributePass());
625 // Now run the core loop vectorizer.
626 OptimizePM.addPass(LoopVectorizePass());
628 // Eliminate loads by forwarding stores from the previous iteration to loads
629 // of the current iteration.
630 OptimizePM.addPass(LoopLoadEliminationPass());
632 // Cleanup after the loop optimization passes.
633 OptimizePM.addPass(InstCombinePass());
636 // Now that we've formed fast to execute loop structures, we do further
637 // optimizations. These are run afterward as they might block doing complex
638 // analyses and transforms such as what are needed for loop vectorization.
640 // Optimize parallel scalar instruction chains into SIMD instructions.
641 OptimizePM.addPass(SLPVectorizerPass());
643 // Cleanup after all of the vectorizers.
644 OptimizePM.addPass(SimplifyCFGPass());
645 OptimizePM.addPass(InstCombinePass());
647 // Unroll small loops to hide loop backedge latency and saturate any parallel
648 // execution resources of an out-of-order processor. We also then need to
649 // clean up redundancies and loop invariant code.
650 // FIXME: It would be really good to use a loop-integrated instruction
651 // combiner for cleanup here so that the unrolling and LICM can be pipelined
652 // across the loop nests.
653 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level)));
654 OptimizePM.addPass(InstCombinePass());
655 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
656 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
658 // Now that we've vectorized and unrolled loops, we may have more refined
659 // alignment information, try to re-derive it here.
660 OptimizePM.addPass(AlignmentFromAssumptionsPass());
662 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
663 // canonicalization pass that enables other optimizations. As a result,
664 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
666 OptimizePM.addPass(LoopSinkPass());
668 // And finally clean up LCSSA form before generating code.
669 OptimizePM.addPass(InstSimplifierPass());
671 // LoopSink (and other loop passes since the last simplifyCFG) might have
672 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
673 OptimizePM.addPass(SimplifyCFGPass());
675 // Add the core optimizing pipeline.
676 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
678 // Now we need to do some global optimization transforms.
679 // FIXME: It would seem like these should come first in the optimization
680 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
682 MPM.addPass(GlobalDCEPass());
683 MPM.addPass(ConstantMergePass());
689 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
691 assert(Level != O0 && "Must request optimizations for the default pipeline!");
693 ModulePassManager MPM(DebugLogging);
695 // Force any function attributes we want the rest of the pipeline to observe.
696 MPM.addPass(ForceFunctionAttrsPass());
698 // Add the core simplification pipeline.
699 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
701 // Now add the optimization pipeline.
702 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
708 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
710 assert(Level != O0 && "Must request optimizations for the default pipeline!");
712 ModulePassManager MPM(DebugLogging);
714 // Force any function attributes we want the rest of the pipeline to observe.
715 MPM.addPass(ForceFunctionAttrsPass());
717 // If we are planning to perform ThinLTO later, we don't bloat the code with
718 // unrolling/vectorization/... now. Just simplify the module as much as we
720 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
722 // Run partial inlining pass to partially inline functions that have
724 // FIXME: It isn't clear whether this is really the right place to run this
725 // in ThinLTO. Because there is another canonicalization and simplification
726 // phase that will run after the thin link, running this here ends up with
727 // less information than will be available later and it may grow functions in
728 // ways that aren't beneficial.
729 if (RunPartialInlining)
730 MPM.addPass(PartialInlinerPass());
732 // Reduce the size of the IR as much as possible.
733 MPM.addPass(GlobalOptPass());
735 // Rename anon globals to be able to export them in the summary.
736 MPM.addPass(NameAnonGlobalPass());
742 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
744 // FIXME: The summary index is not hooked in the new pass manager yet.
745 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
748 ModulePassManager MPM(DebugLogging);
750 // Force any function attributes we want the rest of the pipeline to observe.
751 MPM.addPass(ForceFunctionAttrsPass());
753 // During the ThinLTO backend phase we perform early indirect call promotion
754 // here, before globalopt. Otherwise imported available_externally functions
755 // look unreferenced and are removed.
756 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
757 PGOOpt && PGOOpt->SamplePGO &&
758 !PGOOpt->ProfileUseFile.empty()));
760 // Add the core simplification pipeline.
761 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
763 // Now add the optimization pipeline.
764 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
770 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
772 assert(Level != O0 && "Must request optimizations for the default pipeline!");
773 // FIXME: We should use a customized pre-link pipeline!
774 return buildPerModuleDefaultPipeline(Level, DebugLogging);
777 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
779 assert(Level != O0 && "Must request optimizations for the default pipeline!");
780 ModulePassManager MPM(DebugLogging);
782 // Remove unused virtual tables to improve the quality of code generated by
783 // whole-program devirtualization and bitset lowering.
784 MPM.addPass(GlobalDCEPass());
786 // Force any function attributes we want the rest of the pipeline to observe.
787 MPM.addPass(ForceFunctionAttrsPass());
789 // Do basic inference of function attributes from known properties of system
790 // libraries and other oracles.
791 MPM.addPass(InferFunctionAttrsPass());
794 // Indirect call promotion. This should promote all the targets that are
795 // left by the earlier promotion pass that promotes intra-module targets.
796 // This two-step promotion is to save the compile time. For LTO, it should
797 // produce the same result as if we only do promotion here.
798 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
799 PGOOpt && PGOOpt->SamplePGO));
801 // Propagate constants at call sites into the functions they call. This
802 // opens opportunities for globalopt (and inlining) by substituting function
803 // pointers passed as arguments to direct uses of functions.
804 MPM.addPass(IPSCCPPass());
807 // Now deduce any function attributes based in the current code.
808 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
809 PostOrderFunctionAttrsPass()));
811 // Do RPO function attribute inference across the module to forward-propagate
812 // attributes where applicable.
813 // FIXME: Is this really an optimization rather than a canonicalization?
814 MPM.addPass(ReversePostOrderFunctionAttrsPass());
816 // Use inragne annotations on GEP indices to split globals where beneficial.
817 MPM.addPass(GlobalSplitPass());
819 // Run whole program optimization of virtual call when the list of callees
821 MPM.addPass(WholeProgramDevirtPass());
827 // Optimize globals to try and fold them into constants.
828 MPM.addPass(GlobalOptPass());
830 // Promote any localized globals to SSA registers.
831 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
833 // Linking modules together can lead to duplicate global constant, only
834 // keep one copy of each constant.
835 MPM.addPass(ConstantMergePass());
837 // Remove unused arguments from functions.
838 MPM.addPass(DeadArgumentEliminationPass());
840 // Reduce the code after globalopt and ipsccp. Both can open up significant
841 // simplification opportunities, and both can propagate functions through
842 // function pointers. When this happens, we often have to resolve varargs
843 // calls, etc, so let instcombine do this.
844 // FIXME: add peephole extensions here as the legacy PM does.
845 MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass()));
847 // Note: historically, the PruneEH pass was run first to deduce nounwind and
848 // generally clean up exception handling overhead. It isn't clear this is
849 // valuable as the inliner doesn't currently care whether it is inlining an
851 // Run the inliner now.
852 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(InlinerPass()));
854 // Optimize globals again after we ran the inliner.
855 MPM.addPass(GlobalOptPass());
857 // Garbage collect dead functions.
858 // FIXME: Add ArgumentPromotion pass after once it's ported.
859 MPM.addPass(GlobalDCEPass());
861 FunctionPassManager FPM(DebugLogging);
863 // The IPO Passes may leave cruft around. Clean up after them.
864 // FIXME: add peephole extensions here as the legacy PM does.
865 FPM.addPass(InstCombinePass());
866 FPM.addPass(JumpThreadingPass());
871 // Run a few AA driver optimizations here and now to cleanup the code.
872 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
874 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
875 PostOrderFunctionAttrsPass()));
876 // FIXME: here we run IP alias analysis in the legacy PM.
878 FunctionPassManager MainFPM;
880 // FIXME: once we fix LoopPass Manager, add LICM here.
881 // FIXME: once we provide support for enabling MLSM, add it here.
882 // FIXME: once we provide support for enabling NewGVN, add it here.
884 MainFPM.addPass(NewGVNPass());
886 MainFPM.addPass(GVN());
888 // Remove dead memcpy()'s.
889 MainFPM.addPass(MemCpyOptPass());
892 MainFPM.addPass(DSEPass());
894 // FIXME: at this point, we run a bunch of loop passes:
895 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
896 // loopVectorize. Enable them once the remaining issue with LPM
899 MainFPM.addPass(InstCombinePass());
900 MainFPM.addPass(SimplifyCFGPass());
901 MainFPM.addPass(SCCPPass());
902 MainFPM.addPass(InstCombinePass());
903 MainFPM.addPass(BDCEPass());
905 // FIXME: We may want to run SLPVectorizer here.
906 // After vectorization, assume intrinsics may tell us more
907 // about pointer alignments.
909 MainFPM.add(AlignmentFromAssumptionsPass());
912 // FIXME: Conditionally run LoadCombine here, after it's ported
913 // (in case we still have this pass, given its questionable usefulness).
915 // FIXME: add peephole extensions to the PM here.
916 MainFPM.addPass(InstCombinePass());
917 MainFPM.addPass(JumpThreadingPass());
918 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
920 // Create a function that performs CFI checks for cross-DSO calls with
921 // targets in the current module.
922 MPM.addPass(CrossDSOCFIPass());
924 // Lower type metadata and the type.test intrinsic. This pass supports
925 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
926 // to be run at link time if CFI is enabled. This pass does nothing if
928 // Enable once we add support for the summary in the new PM.
930 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
931 PassSummaryAction::None,
935 // Add late LTO optimization passes.
936 // Delete basic blocks, which optimization passes may have killed.
937 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
939 // Drop bodies of available eternally objects to improve GlobalDCE.
940 MPM.addPass(EliminateAvailableExternallyPass());
942 // Now that we have optimized the program, discard unreachable functions.
943 MPM.addPass(GlobalDCEPass());
945 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
949 AAManager PassBuilder::buildDefaultAAPipeline() {
952 // The order in which these are registered determines their priority when
955 // First we register the basic alias analysis that provides the majority of
956 // per-function local AA logic. This is a stateless, on-demand local set of
958 AA.registerFunctionAnalysis<BasicAA>();
960 // Next we query fast, specialized alias analyses that wrap IR-embedded
961 // information about aliasing.
962 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
963 AA.registerFunctionAnalysis<TypeBasedAA>();
965 // Add support for querying global aliasing information when available.
966 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
967 // analysis, all that the `AAManager` can do is query for any *cached*
968 // results from `GlobalsAA` through a readonly proxy.
969 AA.registerModuleAnalysis<GlobalsAA>();
974 static Optional<int> parseRepeatPassName(StringRef Name) {
975 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
978 if (Name.getAsInteger(0, Count) || Count <= 0)
983 static Optional<int> parseDevirtPassName(StringRef Name) {
984 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
987 if (Name.getAsInteger(0, Count) || Count <= 0)
992 /// Tests whether a pass name starts with a valid prefix for a default pipeline
994 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
995 return Name.startswith("default") || Name.startswith("thinlto") ||
996 Name.startswith("lto");
999 static bool isModulePassName(StringRef Name) {
1000 // Manually handle aliases for pre-configured pipeline fragments.
1001 if (startsWithDefaultPipelineAliasPrefix(Name))
1002 return DefaultAliasRegex.match(Name);
1004 // Explicitly handle pass manager names.
1005 if (Name == "module")
1007 if (Name == "cgscc")
1009 if (Name == "function")
1012 // Explicitly handle custom-parsed pass names.
1013 if (parseRepeatPassName(Name))
1016 #define MODULE_PASS(NAME, CREATE_PASS) \
1019 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1020 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1022 #include "PassRegistry.def"
1027 static bool isCGSCCPassName(StringRef Name) {
1028 // Explicitly handle pass manager names.
1029 if (Name == "cgscc")
1031 if (Name == "function")
1034 // Explicitly handle custom-parsed pass names.
1035 if (parseRepeatPassName(Name))
1037 if (parseDevirtPassName(Name))
1040 #define CGSCC_PASS(NAME, CREATE_PASS) \
1043 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1044 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1046 #include "PassRegistry.def"
1051 static bool isFunctionPassName(StringRef Name) {
1052 // Explicitly handle pass manager names.
1053 if (Name == "function")
1058 // Explicitly handle custom-parsed pass names.
1059 if (parseRepeatPassName(Name))
1062 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1065 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1066 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1068 #include "PassRegistry.def"
1073 static bool isLoopPassName(StringRef Name) {
1074 // Explicitly handle pass manager names.
1078 // Explicitly handle custom-parsed pass names.
1079 if (parseRepeatPassName(Name))
1082 #define LOOP_PASS(NAME, CREATE_PASS) \
1085 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1086 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1088 #include "PassRegistry.def"
1093 Optional<std::vector<PassBuilder::PipelineElement>>
1094 PassBuilder::parsePipelineText(StringRef Text) {
1095 std::vector<PipelineElement> ResultPipeline;
1097 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1100 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1101 size_t Pos = Text.find_first_of(",()");
1102 Pipeline.push_back({Text.substr(0, Pos), {}});
1104 // If we have a single terminating name, we're done.
1105 if (Pos == Text.npos)
1108 char Sep = Text[Pos];
1109 Text = Text.substr(Pos + 1);
1111 // Just a name ending in a comma, continue.
1115 // Push the inner pipeline onto the stack to continue processing.
1116 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1120 assert(Sep == ')' && "Bogus separator!");
1121 // When handling the close parenthesis, we greedily consume them to avoid
1122 // empty strings in the pipeline.
1124 // If we try to pop the outer pipeline we have unbalanced parentheses.
1125 if (PipelineStack.size() == 1)
1128 PipelineStack.pop_back();
1129 } while (Text.consume_front(")"));
1131 // Check if we've finished parsing.
1135 // Otherwise, the end of an inner pipeline always has to be followed by
1136 // a comma, and then we can continue.
1137 if (!Text.consume_front(","))
1141 if (PipelineStack.size() > 1)
1142 // Unbalanced paretheses.
1145 assert(PipelineStack.back() == &ResultPipeline &&
1146 "Wrong pipeline at the bottom of the stack!");
1147 return {std::move(ResultPipeline)};
1150 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1151 const PipelineElement &E, bool VerifyEachPass,
1152 bool DebugLogging) {
1153 auto &Name = E.Name;
1154 auto &InnerPipeline = E.InnerPipeline;
1156 // First handle complex passes like the pass managers which carry pipelines.
1157 if (!InnerPipeline.empty()) {
1158 if (Name == "module") {
1159 ModulePassManager NestedMPM(DebugLogging);
1160 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1163 MPM.addPass(std::move(NestedMPM));
1166 if (Name == "cgscc") {
1167 CGSCCPassManager CGPM(DebugLogging);
1168 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1171 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
1175 if (Name == "function") {
1176 FunctionPassManager FPM(DebugLogging);
1177 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1180 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1183 if (auto Count = parseRepeatPassName(Name)) {
1184 ModulePassManager NestedMPM(DebugLogging);
1185 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1188 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1191 // Normal passes can't have pipelines.
1195 // Manually handle aliases for pre-configured pipeline fragments.
1196 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1197 SmallVector<StringRef, 3> Matches;
1198 if (!DefaultAliasRegex.match(Name, &Matches))
1200 assert(Matches.size() == 3 && "Must capture two matched strings!");
1202 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1210 // At O0 we do nothing at all!
1213 if (Matches[1] == "default") {
1214 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1215 } else if (Matches[1] == "thinlto-pre-link") {
1216 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1217 } else if (Matches[1] == "thinlto") {
1218 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1219 } else if (Matches[1] == "lto-pre-link") {
1220 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1222 assert(Matches[1] == "lto" && "Not one of the matched options!");
1223 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1228 // Finally expand the basic registered passes from the .inc file.
1229 #define MODULE_PASS(NAME, CREATE_PASS) \
1230 if (Name == NAME) { \
1231 MPM.addPass(CREATE_PASS); \
1234 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1235 if (Name == "require<" NAME ">") { \
1237 RequireAnalysisPass< \
1238 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1241 if (Name == "invalidate<" NAME ">") { \
1242 MPM.addPass(InvalidateAnalysisPass< \
1243 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1246 #include "PassRegistry.def"
1251 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1252 const PipelineElement &E, bool VerifyEachPass,
1253 bool DebugLogging) {
1254 auto &Name = E.Name;
1255 auto &InnerPipeline = E.InnerPipeline;
1257 // First handle complex passes like the pass managers which carry pipelines.
1258 if (!InnerPipeline.empty()) {
1259 if (Name == "cgscc") {
1260 CGSCCPassManager NestedCGPM(DebugLogging);
1261 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1264 // Add the nested pass manager with the appropriate adaptor.
1265 CGPM.addPass(std::move(NestedCGPM));
1268 if (Name == "function") {
1269 FunctionPassManager FPM(DebugLogging);
1270 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1273 // Add the nested pass manager with the appropriate adaptor.
1275 createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
1278 if (auto Count = parseRepeatPassName(Name)) {
1279 CGSCCPassManager NestedCGPM(DebugLogging);
1280 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1283 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1286 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1287 CGSCCPassManager NestedCGPM(DebugLogging);
1288 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1291 CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM),
1292 *MaxRepetitions, DebugLogging));
1295 // Normal passes can't have pipelines.
1299 // Now expand the basic registered passes from the .inc file.
1300 #define CGSCC_PASS(NAME, CREATE_PASS) \
1301 if (Name == NAME) { \
1302 CGPM.addPass(CREATE_PASS); \
1305 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1306 if (Name == "require<" NAME ">") { \
1307 CGPM.addPass(RequireAnalysisPass< \
1308 std::remove_reference<decltype(CREATE_PASS)>::type, \
1309 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1310 CGSCCUpdateResult &>()); \
1313 if (Name == "invalidate<" NAME ">") { \
1314 CGPM.addPass(InvalidateAnalysisPass< \
1315 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1318 #include "PassRegistry.def"
1323 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1324 const PipelineElement &E,
1325 bool VerifyEachPass, bool DebugLogging) {
1326 auto &Name = E.Name;
1327 auto &InnerPipeline = E.InnerPipeline;
1329 // First handle complex passes like the pass managers which carry pipelines.
1330 if (!InnerPipeline.empty()) {
1331 if (Name == "function") {
1332 FunctionPassManager NestedFPM(DebugLogging);
1333 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1336 // Add the nested pass manager with the appropriate adaptor.
1337 FPM.addPass(std::move(NestedFPM));
1340 if (Name == "loop") {
1341 LoopPassManager LPM(DebugLogging);
1342 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1345 // Add the nested pass manager with the appropriate adaptor.
1346 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1349 if (auto Count = parseRepeatPassName(Name)) {
1350 FunctionPassManager NestedFPM(DebugLogging);
1351 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1354 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1357 // Normal passes can't have pipelines.
1361 // Now expand the basic registered passes from the .inc file.
1362 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1363 if (Name == NAME) { \
1364 FPM.addPass(CREATE_PASS); \
1367 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1368 if (Name == "require<" NAME ">") { \
1370 RequireAnalysisPass< \
1371 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1374 if (Name == "invalidate<" NAME ">") { \
1375 FPM.addPass(InvalidateAnalysisPass< \
1376 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1379 #include "PassRegistry.def"
1384 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1385 bool VerifyEachPass, bool DebugLogging) {
1386 StringRef Name = E.Name;
1387 auto &InnerPipeline = E.InnerPipeline;
1389 // First handle complex passes like the pass managers which carry pipelines.
1390 if (!InnerPipeline.empty()) {
1391 if (Name == "loop") {
1392 LoopPassManager NestedLPM(DebugLogging);
1393 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1396 // Add the nested pass manager with the appropriate adaptor.
1397 LPM.addPass(std::move(NestedLPM));
1400 if (auto Count = parseRepeatPassName(Name)) {
1401 LoopPassManager NestedLPM(DebugLogging);
1402 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1405 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1408 // Normal passes can't have pipelines.
1412 // Now expand the basic registered passes from the .inc file.
1413 #define LOOP_PASS(NAME, CREATE_PASS) \
1414 if (Name == NAME) { \
1415 LPM.addPass(CREATE_PASS); \
1418 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1419 if (Name == "require<" NAME ">") { \
1420 LPM.addPass(RequireAnalysisPass< \
1421 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1422 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1426 if (Name == "invalidate<" NAME ">") { \
1427 LPM.addPass(InvalidateAnalysisPass< \
1428 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1431 #include "PassRegistry.def"
1436 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1437 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1438 if (Name == NAME) { \
1439 AA.registerModuleAnalysis< \
1440 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1443 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1444 if (Name == NAME) { \
1445 AA.registerFunctionAnalysis< \
1446 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1449 #include "PassRegistry.def"
1454 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1455 ArrayRef<PipelineElement> Pipeline,
1456 bool VerifyEachPass,
1457 bool DebugLogging) {
1458 for (const auto &Element : Pipeline) {
1459 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1461 // FIXME: No verifier support for Loop passes!
1466 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1467 ArrayRef<PipelineElement> Pipeline,
1468 bool VerifyEachPass,
1469 bool DebugLogging) {
1470 for (const auto &Element : Pipeline) {
1471 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1474 FPM.addPass(VerifierPass());
1479 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1480 ArrayRef<PipelineElement> Pipeline,
1481 bool VerifyEachPass,
1482 bool DebugLogging) {
1483 for (const auto &Element : Pipeline) {
1484 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1486 // FIXME: No verifier support for CGSCC passes!
1491 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1492 FunctionAnalysisManager &FAM,
1493 CGSCCAnalysisManager &CGAM,
1494 ModuleAnalysisManager &MAM) {
1495 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1496 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1497 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1498 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1499 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1500 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1501 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1504 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1505 ArrayRef<PipelineElement> Pipeline,
1506 bool VerifyEachPass,
1507 bool DebugLogging) {
1508 for (const auto &Element : Pipeline) {
1509 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1512 MPM.addPass(VerifierPass());
1517 // Primary pass pipeline description parsing routine.
1518 // FIXME: Should this routine accept a TargetMachine or require the caller to
1519 // pre-populate the analysis managers with target-specific stuff?
1520 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1521 StringRef PipelineText, bool VerifyEachPass,
1522 bool DebugLogging) {
1523 auto Pipeline = parsePipelineText(PipelineText);
1524 if (!Pipeline || Pipeline->empty())
1527 // If the first name isn't at the module layer, wrap the pipeline up
1529 StringRef FirstName = Pipeline->front().Name;
1531 if (!isModulePassName(FirstName)) {
1532 if (isCGSCCPassName(FirstName))
1533 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1534 else if (isFunctionPassName(FirstName))
1535 Pipeline = {{"function", std::move(*Pipeline)}};
1536 else if (isLoopPassName(FirstName))
1537 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1539 // Unknown pass name!
1543 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1546 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1547 // If the pipeline just consists of the word 'default' just replace the AA
1548 // manager with our default one.
1549 if (PipelineText == "default") {
1550 AA = buildDefaultAAPipeline();
1554 while (!PipelineText.empty()) {
1556 std::tie(Name, PipelineText) = PipelineText.split(',');
1557 if (!parseAAPassName(AA, Name))