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 // Speculative execution if the target has divergent branches; otherwise nop.
314 FPM.addPass(SpeculativeExecutionPass());
316 // Optimize based on known information about branches, and cleanup afterward.
317 FPM.addPass(JumpThreadingPass());
318 FPM.addPass(CorrelatedValuePropagationPass());
319 FPM.addPass(SimplifyCFGPass());
320 FPM.addPass(InstCombinePass());
322 if (!isOptimizingForSize(Level))
323 FPM.addPass(LibCallsShrinkWrapPass());
325 FPM.addPass(TailCallElimPass());
326 FPM.addPass(SimplifyCFGPass());
328 // Form canonically associated expression trees, and simplify the trees using
329 // basic mathematical properties. For example, this will form (nearly)
330 // minimal multiplication trees.
331 FPM.addPass(ReassociatePass());
333 // Add the primary loop simplification pipeline.
334 // FIXME: Currently this is split into two loop pass pipelines because we run
335 // some function passes in between them. These can and should be replaced by
336 // loop pass equivalenst but those aren't ready yet. Specifically,
337 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
338 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
339 // the other we have is `LoopInstSimplify`.
340 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
342 // Rotate Loop - disable header duplication at -Oz
343 LPM1.addPass(LoopRotatePass(Level != Oz));
344 LPM1.addPass(LICMPass());
345 LPM1.addPass(SimpleLoopUnswitchPass());
346 LPM2.addPass(IndVarSimplifyPass());
347 LPM2.addPass(LoopIdiomRecognizePass());
348 LPM2.addPass(LoopDeletionPass());
349 // FIXME: The old pass manager has a hack to disable loop unrolling during
350 // ThinLTO when using sample PGO. Need to either fix it or port some
352 LPM2.addPass(LoopUnrollPass::createFull(Level));
354 // We provide the opt remark emitter pass for LICM to use. We only need to do
355 // this once as it is immutable.
356 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
357 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
358 FPM.addPass(SimplifyCFGPass());
359 FPM.addPass(InstCombinePass());
360 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
362 // Eliminate redundancies.
364 // These passes add substantial compile time so skip them at O1.
365 FPM.addPass(MergedLoadStoreMotionPass());
367 FPM.addPass(NewGVNPass());
372 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
373 FPM.addPass(MemCpyOptPass());
375 // Sparse conditional constant propagation.
376 // FIXME: It isn't clear why we do this *after* loop passes rather than
378 FPM.addPass(SCCPPass());
380 // Delete dead bit computations (instcombine runs after to fold away the dead
381 // computations, and then ADCE will run later to exploit any new DCE
382 // opportunities that creates).
383 FPM.addPass(BDCEPass());
385 // Run instcombine after redundancy and dead bit elimination to exploit
386 // opportunities opened up by them.
387 FPM.addPass(InstCombinePass());
389 // Re-consider control flow based optimizations after redundancy elimination,
391 FPM.addPass(JumpThreadingPass());
392 FPM.addPass(CorrelatedValuePropagationPass());
393 FPM.addPass(DSEPass());
394 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
396 // Finally, do an expensive DCE pass to catch all the dead code exposed by
397 // the simplifications and basic cleanup after all the simplifications.
398 FPM.addPass(ADCEPass());
399 FPM.addPass(SimplifyCFGPass());
400 FPM.addPass(InstCombinePass());
405 static void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
406 PassBuilder::OptimizationLevel Level,
407 bool RunProfileGen, std::string ProfileGenFile,
408 std::string ProfileUseFile) {
409 // Generally running simplification passes and the inliner with an high
410 // threshold results in smaller executables, but there may be cases where
411 // the size grows, so let's be conservative here and skip this simplification
413 if (!isOptimizingForSize(Level)) {
416 // In the old pass manager, this is a cl::opt. Should still this be one?
417 IP.DefaultThreshold = 75;
419 // FIXME: The hint threshold has the same value used by the regular inliner.
420 // This should probably be lowered after performance testing.
421 // FIXME: this comment is cargo culted from the old pass manager, revisit).
422 IP.HintThreshold = 325;
424 CGSCCPassManager CGPipeline(DebugLogging);
426 CGPipeline.addPass(InlinerPass(IP));
428 FunctionPassManager FPM;
430 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
431 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
432 FPM.addPass(InstCombinePass()); // Combine silly sequences.
434 // FIXME: Here the old pass manager inserts peephole extensions.
435 // Add them when they're supported.
436 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
438 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
441 // Delete anything that is now dead to make sure that we don't instrument
442 // dead code. Instrumentation can end up keeping dead code around and
443 // dramatically increase code size.
444 MPM.addPass(GlobalDCEPass());
447 MPM.addPass(PGOInstrumentationGen());
449 // Add the profile lowering pass.
450 InstrProfOptions Options;
451 if (!ProfileGenFile.empty())
452 Options.InstrProfileOutput = ProfileGenFile;
453 MPM.addPass(InstrProfiling(Options));
456 if (!ProfileUseFile.empty())
457 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
461 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
463 ModulePassManager MPM(DebugLogging);
465 // Do basic inference of function attributes from known properties of system
466 // libraries and other oracles.
467 MPM.addPass(InferFunctionAttrsPass());
469 // Create an early function pass manager to cleanup the output of the
471 FunctionPassManager EarlyFPM(DebugLogging);
472 EarlyFPM.addPass(SimplifyCFGPass());
473 EarlyFPM.addPass(SROA());
474 EarlyFPM.addPass(EarlyCSEPass());
475 EarlyFPM.addPass(LowerExpectIntrinsicPass());
477 EarlyFPM.addPass(GVNHoistPass());
478 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
480 // Interprocedural constant propagation now that basic cleanup has occured
481 // and prior to optimizing globals.
482 // FIXME: This position in the pipeline hasn't been carefully considered in
483 // years, it should be re-analyzed.
484 MPM.addPass(IPSCCPPass());
486 // Optimize globals to try and fold them into constants.
487 MPM.addPass(GlobalOptPass());
489 // Promote any localized globals to SSA registers.
490 // FIXME: Should this instead by a run of SROA?
491 // FIXME: We should probably run instcombine and simplify-cfg afterward to
492 // delete control flows that are dead once globals have been folded to
494 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
496 // Remove any dead arguments exposed by cleanups and constand folding
498 MPM.addPass(DeadArgumentEliminationPass());
500 // Create a small function pass pipeline to cleanup after all the global
502 FunctionPassManager GlobalCleanupPM(DebugLogging);
503 GlobalCleanupPM.addPass(InstCombinePass());
504 GlobalCleanupPM.addPass(SimplifyCFGPass());
505 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
507 // Add all the requested passes for PGO, if requested.
509 assert(PGOOpt->RunProfileGen || PGOOpt->SamplePGO ||
510 !PGOOpt->ProfileUseFile.empty());
511 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
512 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
514 // Indirect call promotion that promotes intra-module targes only.
515 MPM.addPass(PGOIndirectCallPromotion(false, PGOOpt && PGOOpt->SamplePGO));
518 // Require the GlobalsAA analysis for the module so we can query it within
519 // the CGSCC pipeline.
520 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
522 // Require the ProfileSummaryAnalysis for the module so we can query it within
524 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
526 // Now begin the main postorder CGSCC pipeline.
527 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
528 // manager and trying to emulate its precise behavior. Much of this doesn't
529 // make a lot of sense and we should revisit the core CGSCC structure.
530 CGSCCPassManager MainCGPipeline(DebugLogging);
532 // Note: historically, the PruneEH pass was run first to deduce nounwind and
533 // generally clean up exception handling overhead. It isn't clear this is
534 // valuable as the inliner doesn't currently care whether it is inlining an
537 // Run the inliner first. The theory is that we are walking bottom-up and so
538 // the callees have already been fully optimized, and we want to inline them
539 // into the callers so that our optimizations can reflect that.
540 // FIXME; Customize the threshold based on optimization level.
541 MainCGPipeline.addPass(InlinerPass());
543 // Now deduce any function attributes based in the current code.
544 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
546 // When at O3 add argument promotion to the pass pipeline.
547 // FIXME: It isn't at all clear why this should be limited to O3.
549 MainCGPipeline.addPass(ArgumentPromotionPass());
551 // Lastly, add the core function simplification pipeline nested inside the
553 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
554 buildFunctionSimplificationPipeline(Level, DebugLogging)));
556 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
557 // to detect when we devirtualize indirect calls and iterate the SCC passes
558 // in that case to try and catch knock-on inlining or function attrs
559 // opportunities. Then we add it to the module pipeline by walking the SCCs
560 // in postorder (or bottom-up).
562 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
563 std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging)));
569 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
571 ModulePassManager MPM(DebugLogging);
573 // Optimize globals now that the module is fully simplified.
574 MPM.addPass(GlobalOptPass());
576 // Run partial inlining pass to partially inline functions that have
578 if (RunPartialInlining)
579 MPM.addPass(PartialInlinerPass());
581 // Remove avail extern fns and globals definitions since we aren't compiling
582 // an object file for later LTO. For LTO we want to preserve these so they
583 // are eligible for inlining at link-time. Note if they are unreferenced they
584 // will be removed by GlobalDCE later, so this only impacts referenced
585 // available externally globals. Eventually they will be suppressed during
586 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
587 // may make globals referenced by available external functions dead and saves
588 // running remaining passes on the eliminated functions.
589 MPM.addPass(EliminateAvailableExternallyPass());
591 // Do RPO function attribute inference across the module to forward-propagate
592 // attributes where applicable.
593 // FIXME: Is this really an optimization rather than a canonicalization?
594 MPM.addPass(ReversePostOrderFunctionAttrsPass());
596 // Re-require GloblasAA here prior to function passes. This is particularly
597 // useful as the above will have inlined, DCE'ed, and function-attr
598 // propagated everything. We should at this point have a reasonably minimal
599 // and richly annotated call graph. By computing aliasing and mod/ref
600 // information for all local globals here, the late loop passes and notably
601 // the vectorizer will be able to use them to help recognize vectorizable
602 // memory operations.
603 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
605 FunctionPassManager OptimizePM(DebugLogging);
606 OptimizePM.addPass(Float2IntPass());
607 // FIXME: We need to run some loop optimizations to re-rotate loops after
608 // simplify-cfg and others undo their rotation.
610 // Optimize the loop execution. These passes operate on entire loop nests
611 // rather than on each loop in an inside-out manner, and so they are actually
614 // First rotate loops that may have been un-rotated by prior passes.
615 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
617 // Distribute loops to allow partial vectorization. I.e. isolate dependences
618 // into separate loop that would otherwise inhibit vectorization. This is
619 // currently only performed for loops marked with the metadata
620 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
621 OptimizePM.addPass(LoopDistributePass());
623 // Now run the core loop vectorizer.
624 OptimizePM.addPass(LoopVectorizePass());
626 // Eliminate loads by forwarding stores from the previous iteration to loads
627 // of the current iteration.
628 OptimizePM.addPass(LoopLoadEliminationPass());
630 // Cleanup after the loop optimization passes.
631 OptimizePM.addPass(InstCombinePass());
634 // Now that we've formed fast to execute loop structures, we do further
635 // optimizations. These are run afterward as they might block doing complex
636 // analyses and transforms such as what are needed for loop vectorization.
638 // Optimize parallel scalar instruction chains into SIMD instructions.
639 OptimizePM.addPass(SLPVectorizerPass());
641 // Cleanup after all of the vectorizers.
642 OptimizePM.addPass(SimplifyCFGPass());
643 OptimizePM.addPass(InstCombinePass());
645 // Unroll small loops to hide loop backedge latency and saturate any parallel
646 // execution resources of an out-of-order processor. We also then need to
647 // clean up redundancies and loop invariant code.
648 // FIXME: It would be really good to use a loop-integrated instruction
649 // combiner for cleanup here so that the unrolling and LICM can be pipelined
650 // across the loop nests.
651 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level)));
652 OptimizePM.addPass(InstCombinePass());
653 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
654 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
656 // Now that we've vectorized and unrolled loops, we may have more refined
657 // alignment information, try to re-derive it here.
658 OptimizePM.addPass(AlignmentFromAssumptionsPass());
660 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
661 // canonicalization pass that enables other optimizations. As a result,
662 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
664 OptimizePM.addPass(LoopSinkPass());
666 // And finally clean up LCSSA form before generating code.
667 OptimizePM.addPass(InstSimplifierPass());
669 // LoopSink (and other loop passes since the last simplifyCFG) might have
670 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
671 OptimizePM.addPass(SimplifyCFGPass());
673 // Add the core optimizing pipeline.
674 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
676 // Now we need to do some global optimization transforms.
677 // FIXME: It would seem like these should come first in the optimization
678 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
680 MPM.addPass(GlobalDCEPass());
681 MPM.addPass(ConstantMergePass());
687 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
689 assert(Level != O0 && "Must request optimizations for the default pipeline!");
691 ModulePassManager MPM(DebugLogging);
693 // Force any function attributes we want the rest of the pipeline to observe.
694 MPM.addPass(ForceFunctionAttrsPass());
696 // Add the core simplification pipeline.
697 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
699 // Now add the optimization pipeline.
700 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
706 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
708 assert(Level != O0 && "Must request optimizations for the default pipeline!");
710 ModulePassManager MPM(DebugLogging);
712 // Force any function attributes we want the rest of the pipeline to observe.
713 MPM.addPass(ForceFunctionAttrsPass());
715 // If we are planning to perform ThinLTO later, we don't bloat the code with
716 // unrolling/vectorization/... now. Just simplify the module as much as we
718 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
720 // Run partial inlining pass to partially inline functions that have
722 // FIXME: It isn't clear whether this is really the right place to run this
723 // in ThinLTO. Because there is another canonicalization and simplification
724 // phase that will run after the thin link, running this here ends up with
725 // less information than will be available later and it may grow functions in
726 // ways that aren't beneficial.
727 if (RunPartialInlining)
728 MPM.addPass(PartialInlinerPass());
730 // Reduce the size of the IR as much as possible.
731 MPM.addPass(GlobalOptPass());
733 // Rename anon globals to be able to export them in the summary.
734 MPM.addPass(NameAnonGlobalPass());
740 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
742 // FIXME: The summary index is not hooked in the new pass manager yet.
743 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
746 ModulePassManager MPM(DebugLogging);
748 // Force any function attributes we want the rest of the pipeline to observe.
749 MPM.addPass(ForceFunctionAttrsPass());
751 // During the ThinLTO backend phase we perform early indirect call promotion
752 // here, before globalopt. Otherwise imported available_externally functions
753 // look unreferenced and are removed.
754 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
755 PGOOpt && PGOOpt->SamplePGO &&
756 !PGOOpt->ProfileUseFile.empty()));
758 // Add the core simplification pipeline.
759 MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
761 // Now add the optimization pipeline.
762 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
768 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
770 assert(Level != O0 && "Must request optimizations for the default pipeline!");
771 // FIXME: We should use a customized pre-link pipeline!
772 return buildPerModuleDefaultPipeline(Level, DebugLogging);
775 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
777 assert(Level != O0 && "Must request optimizations for the default pipeline!");
778 ModulePassManager MPM(DebugLogging);
780 // Remove unused virtual tables to improve the quality of code generated by
781 // whole-program devirtualization and bitset lowering.
782 MPM.addPass(GlobalDCEPass());
784 // Force any function attributes we want the rest of the pipeline to observe.
785 MPM.addPass(ForceFunctionAttrsPass());
787 // Do basic inference of function attributes from known properties of system
788 // libraries and other oracles.
789 MPM.addPass(InferFunctionAttrsPass());
792 // Indirect call promotion. This should promote all the targets that are
793 // left by the earlier promotion pass that promotes intra-module targets.
794 // This two-step promotion is to save the compile time. For LTO, it should
795 // produce the same result as if we only do promotion here.
796 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
797 PGOOpt && PGOOpt->SamplePGO));
799 // Propagate constants at call sites into the functions they call. This
800 // opens opportunities for globalopt (and inlining) by substituting function
801 // pointers passed as arguments to direct uses of functions.
802 MPM.addPass(IPSCCPPass());
805 // Now deduce any function attributes based in the current code.
806 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
807 PostOrderFunctionAttrsPass()));
809 // Do RPO function attribute inference across the module to forward-propagate
810 // attributes where applicable.
811 // FIXME: Is this really an optimization rather than a canonicalization?
812 MPM.addPass(ReversePostOrderFunctionAttrsPass());
814 // Use inragne annotations on GEP indices to split globals where beneficial.
815 MPM.addPass(GlobalSplitPass());
817 // Run whole program optimization of virtual call when the list of callees
819 MPM.addPass(WholeProgramDevirtPass());
825 // Optimize globals to try and fold them into constants.
826 MPM.addPass(GlobalOptPass());
828 // Promote any localized globals to SSA registers.
829 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
831 // Linking modules together can lead to duplicate global constant, only
832 // keep one copy of each constant.
833 MPM.addPass(ConstantMergePass());
835 // Remove unused arguments from functions.
836 MPM.addPass(DeadArgumentEliminationPass());
838 // Reduce the code after globalopt and ipsccp. Both can open up significant
839 // simplification opportunities, and both can propagate functions through
840 // function pointers. When this happens, we often have to resolve varargs
841 // calls, etc, so let instcombine do this.
842 // FIXME: add peephole extensions here as the legacy PM does.
843 MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass()));
845 // Note: historically, the PruneEH pass was run first to deduce nounwind and
846 // generally clean up exception handling overhead. It isn't clear this is
847 // valuable as the inliner doesn't currently care whether it is inlining an
849 // Run the inliner now.
850 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(InlinerPass()));
852 // Optimize globals again after we ran the inliner.
853 MPM.addPass(GlobalOptPass());
855 // Garbage collect dead functions.
856 // FIXME: Add ArgumentPromotion pass after once it's ported.
857 MPM.addPass(GlobalDCEPass());
859 FunctionPassManager FPM(DebugLogging);
861 // The IPO Passes may leave cruft around. Clean up after them.
862 // FIXME: add peephole extensions here as the legacy PM does.
863 FPM.addPass(InstCombinePass());
864 FPM.addPass(JumpThreadingPass());
869 // Run a few AA driver optimizations here and now to cleanup the code.
870 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
872 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
873 PostOrderFunctionAttrsPass()));
874 // FIXME: here we run IP alias analysis in the legacy PM.
876 FunctionPassManager MainFPM;
878 // FIXME: once we fix LoopPass Manager, add LICM here.
879 // FIXME: once we provide support for enabling MLSM, add it here.
880 // FIXME: once we provide support for enabling NewGVN, add it here.
882 MainFPM.addPass(NewGVNPass());
884 MainFPM.addPass(GVN());
886 // Remove dead memcpy()'s.
887 MainFPM.addPass(MemCpyOptPass());
890 MainFPM.addPass(DSEPass());
892 // FIXME: at this point, we run a bunch of loop passes:
893 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
894 // loopVectorize. Enable them once the remaining issue with LPM
897 MainFPM.addPass(InstCombinePass());
898 MainFPM.addPass(SimplifyCFGPass());
899 MainFPM.addPass(SCCPPass());
900 MainFPM.addPass(InstCombinePass());
901 MainFPM.addPass(BDCEPass());
903 // FIXME: We may want to run SLPVectorizer here.
904 // After vectorization, assume intrinsics may tell us more
905 // about pointer alignments.
907 MainFPM.add(AlignmentFromAssumptionsPass());
910 // FIXME: Conditionally run LoadCombine here, after it's ported
911 // (in case we still have this pass, given its questionable usefulness).
913 // FIXME: add peephole extensions to the PM here.
914 MainFPM.addPass(InstCombinePass());
915 MainFPM.addPass(JumpThreadingPass());
916 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
918 // Create a function that performs CFI checks for cross-DSO calls with
919 // targets in the current module.
920 MPM.addPass(CrossDSOCFIPass());
922 // Lower type metadata and the type.test intrinsic. This pass supports
923 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
924 // to be run at link time if CFI is enabled. This pass does nothing if
926 // Enable once we add support for the summary in the new PM.
928 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
929 PassSummaryAction::None,
933 // Add late LTO optimization passes.
934 // Delete basic blocks, which optimization passes may have killed.
935 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
937 // Drop bodies of available eternally objects to improve GlobalDCE.
938 MPM.addPass(EliminateAvailableExternallyPass());
940 // Now that we have optimized the program, discard unreachable functions.
941 MPM.addPass(GlobalDCEPass());
943 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
947 AAManager PassBuilder::buildDefaultAAPipeline() {
950 // The order in which these are registered determines their priority when
953 // First we register the basic alias analysis that provides the majority of
954 // per-function local AA logic. This is a stateless, on-demand local set of
956 AA.registerFunctionAnalysis<BasicAA>();
958 // Next we query fast, specialized alias analyses that wrap IR-embedded
959 // information about aliasing.
960 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
961 AA.registerFunctionAnalysis<TypeBasedAA>();
963 // Add support for querying global aliasing information when available.
964 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
965 // analysis, all that the `AAManager` can do is query for any *cached*
966 // results from `GlobalsAA` through a readonly proxy.
967 AA.registerModuleAnalysis<GlobalsAA>();
972 static Optional<int> parseRepeatPassName(StringRef Name) {
973 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
976 if (Name.getAsInteger(0, Count) || Count <= 0)
981 static Optional<int> parseDevirtPassName(StringRef Name) {
982 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
985 if (Name.getAsInteger(0, Count) || Count <= 0)
990 /// Tests whether a pass name starts with a valid prefix for a default pipeline
992 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
993 return Name.startswith("default") || Name.startswith("thinlto") ||
994 Name.startswith("lto");
997 static bool isModulePassName(StringRef Name) {
998 // Manually handle aliases for pre-configured pipeline fragments.
999 if (startsWithDefaultPipelineAliasPrefix(Name))
1000 return DefaultAliasRegex.match(Name);
1002 // Explicitly handle pass manager names.
1003 if (Name == "module")
1005 if (Name == "cgscc")
1007 if (Name == "function")
1010 // Explicitly handle custom-parsed pass names.
1011 if (parseRepeatPassName(Name))
1014 #define MODULE_PASS(NAME, CREATE_PASS) \
1017 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1018 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1020 #include "PassRegistry.def"
1025 static bool isCGSCCPassName(StringRef Name) {
1026 // Explicitly handle pass manager names.
1027 if (Name == "cgscc")
1029 if (Name == "function")
1032 // Explicitly handle custom-parsed pass names.
1033 if (parseRepeatPassName(Name))
1035 if (parseDevirtPassName(Name))
1038 #define CGSCC_PASS(NAME, CREATE_PASS) \
1041 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1042 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1044 #include "PassRegistry.def"
1049 static bool isFunctionPassName(StringRef Name) {
1050 // Explicitly handle pass manager names.
1051 if (Name == "function")
1056 // Explicitly handle custom-parsed pass names.
1057 if (parseRepeatPassName(Name))
1060 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1063 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1064 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1066 #include "PassRegistry.def"
1071 static bool isLoopPassName(StringRef Name) {
1072 // Explicitly handle pass manager names.
1076 // Explicitly handle custom-parsed pass names.
1077 if (parseRepeatPassName(Name))
1080 #define LOOP_PASS(NAME, CREATE_PASS) \
1083 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1084 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1086 #include "PassRegistry.def"
1091 Optional<std::vector<PassBuilder::PipelineElement>>
1092 PassBuilder::parsePipelineText(StringRef Text) {
1093 std::vector<PipelineElement> ResultPipeline;
1095 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1098 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1099 size_t Pos = Text.find_first_of(",()");
1100 Pipeline.push_back({Text.substr(0, Pos), {}});
1102 // If we have a single terminating name, we're done.
1103 if (Pos == Text.npos)
1106 char Sep = Text[Pos];
1107 Text = Text.substr(Pos + 1);
1109 // Just a name ending in a comma, continue.
1113 // Push the inner pipeline onto the stack to continue processing.
1114 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1118 assert(Sep == ')' && "Bogus separator!");
1119 // When handling the close parenthesis, we greedily consume them to avoid
1120 // empty strings in the pipeline.
1122 // If we try to pop the outer pipeline we have unbalanced parentheses.
1123 if (PipelineStack.size() == 1)
1126 PipelineStack.pop_back();
1127 } while (Text.consume_front(")"));
1129 // Check if we've finished parsing.
1133 // Otherwise, the end of an inner pipeline always has to be followed by
1134 // a comma, and then we can continue.
1135 if (!Text.consume_front(","))
1139 if (PipelineStack.size() > 1)
1140 // Unbalanced paretheses.
1143 assert(PipelineStack.back() == &ResultPipeline &&
1144 "Wrong pipeline at the bottom of the stack!");
1145 return {std::move(ResultPipeline)};
1148 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1149 const PipelineElement &E, bool VerifyEachPass,
1150 bool DebugLogging) {
1151 auto &Name = E.Name;
1152 auto &InnerPipeline = E.InnerPipeline;
1154 // First handle complex passes like the pass managers which carry pipelines.
1155 if (!InnerPipeline.empty()) {
1156 if (Name == "module") {
1157 ModulePassManager NestedMPM(DebugLogging);
1158 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1161 MPM.addPass(std::move(NestedMPM));
1164 if (Name == "cgscc") {
1165 CGSCCPassManager CGPM(DebugLogging);
1166 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1169 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
1173 if (Name == "function") {
1174 FunctionPassManager FPM(DebugLogging);
1175 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1178 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1181 if (auto Count = parseRepeatPassName(Name)) {
1182 ModulePassManager NestedMPM(DebugLogging);
1183 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1186 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1189 // Normal passes can't have pipelines.
1193 // Manually handle aliases for pre-configured pipeline fragments.
1194 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1195 SmallVector<StringRef, 3> Matches;
1196 if (!DefaultAliasRegex.match(Name, &Matches))
1198 assert(Matches.size() == 3 && "Must capture two matched strings!");
1200 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1208 // At O0 we do nothing at all!
1211 if (Matches[1] == "default") {
1212 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1213 } else if (Matches[1] == "thinlto-pre-link") {
1214 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1215 } else if (Matches[1] == "thinlto") {
1216 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1217 } else if (Matches[1] == "lto-pre-link") {
1218 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1220 assert(Matches[1] == "lto" && "Not one of the matched options!");
1221 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1226 // Finally expand the basic registered passes from the .inc file.
1227 #define MODULE_PASS(NAME, CREATE_PASS) \
1228 if (Name == NAME) { \
1229 MPM.addPass(CREATE_PASS); \
1232 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1233 if (Name == "require<" NAME ">") { \
1235 RequireAnalysisPass< \
1236 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1239 if (Name == "invalidate<" NAME ">") { \
1240 MPM.addPass(InvalidateAnalysisPass< \
1241 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1244 #include "PassRegistry.def"
1249 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1250 const PipelineElement &E, bool VerifyEachPass,
1251 bool DebugLogging) {
1252 auto &Name = E.Name;
1253 auto &InnerPipeline = E.InnerPipeline;
1255 // First handle complex passes like the pass managers which carry pipelines.
1256 if (!InnerPipeline.empty()) {
1257 if (Name == "cgscc") {
1258 CGSCCPassManager NestedCGPM(DebugLogging);
1259 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1262 // Add the nested pass manager with the appropriate adaptor.
1263 CGPM.addPass(std::move(NestedCGPM));
1266 if (Name == "function") {
1267 FunctionPassManager FPM(DebugLogging);
1268 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1271 // Add the nested pass manager with the appropriate adaptor.
1273 createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
1276 if (auto Count = parseRepeatPassName(Name)) {
1277 CGSCCPassManager NestedCGPM(DebugLogging);
1278 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1281 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1284 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1285 CGSCCPassManager NestedCGPM(DebugLogging);
1286 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1289 CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM),
1290 *MaxRepetitions, DebugLogging));
1293 // Normal passes can't have pipelines.
1297 // Now expand the basic registered passes from the .inc file.
1298 #define CGSCC_PASS(NAME, CREATE_PASS) \
1299 if (Name == NAME) { \
1300 CGPM.addPass(CREATE_PASS); \
1303 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1304 if (Name == "require<" NAME ">") { \
1305 CGPM.addPass(RequireAnalysisPass< \
1306 std::remove_reference<decltype(CREATE_PASS)>::type, \
1307 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1308 CGSCCUpdateResult &>()); \
1311 if (Name == "invalidate<" NAME ">") { \
1312 CGPM.addPass(InvalidateAnalysisPass< \
1313 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1316 #include "PassRegistry.def"
1321 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1322 const PipelineElement &E,
1323 bool VerifyEachPass, bool DebugLogging) {
1324 auto &Name = E.Name;
1325 auto &InnerPipeline = E.InnerPipeline;
1327 // First handle complex passes like the pass managers which carry pipelines.
1328 if (!InnerPipeline.empty()) {
1329 if (Name == "function") {
1330 FunctionPassManager NestedFPM(DebugLogging);
1331 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1334 // Add the nested pass manager with the appropriate adaptor.
1335 FPM.addPass(std::move(NestedFPM));
1338 if (Name == "loop") {
1339 LoopPassManager LPM(DebugLogging);
1340 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1343 // Add the nested pass manager with the appropriate adaptor.
1344 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1347 if (auto Count = parseRepeatPassName(Name)) {
1348 FunctionPassManager NestedFPM(DebugLogging);
1349 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1352 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1355 // Normal passes can't have pipelines.
1359 // Now expand the basic registered passes from the .inc file.
1360 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1361 if (Name == NAME) { \
1362 FPM.addPass(CREATE_PASS); \
1365 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1366 if (Name == "require<" NAME ">") { \
1368 RequireAnalysisPass< \
1369 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1372 if (Name == "invalidate<" NAME ">") { \
1373 FPM.addPass(InvalidateAnalysisPass< \
1374 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1377 #include "PassRegistry.def"
1382 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1383 bool VerifyEachPass, bool DebugLogging) {
1384 StringRef Name = E.Name;
1385 auto &InnerPipeline = E.InnerPipeline;
1387 // First handle complex passes like the pass managers which carry pipelines.
1388 if (!InnerPipeline.empty()) {
1389 if (Name == "loop") {
1390 LoopPassManager NestedLPM(DebugLogging);
1391 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1394 // Add the nested pass manager with the appropriate adaptor.
1395 LPM.addPass(std::move(NestedLPM));
1398 if (auto Count = parseRepeatPassName(Name)) {
1399 LoopPassManager NestedLPM(DebugLogging);
1400 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1403 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1406 // Normal passes can't have pipelines.
1410 // Now expand the basic registered passes from the .inc file.
1411 #define LOOP_PASS(NAME, CREATE_PASS) \
1412 if (Name == NAME) { \
1413 LPM.addPass(CREATE_PASS); \
1416 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1417 if (Name == "require<" NAME ">") { \
1418 LPM.addPass(RequireAnalysisPass< \
1419 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1420 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1424 if (Name == "invalidate<" NAME ">") { \
1425 LPM.addPass(InvalidateAnalysisPass< \
1426 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1429 #include "PassRegistry.def"
1434 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1435 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1436 if (Name == NAME) { \
1437 AA.registerModuleAnalysis< \
1438 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1441 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1442 if (Name == NAME) { \
1443 AA.registerFunctionAnalysis< \
1444 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1447 #include "PassRegistry.def"
1452 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1453 ArrayRef<PipelineElement> Pipeline,
1454 bool VerifyEachPass,
1455 bool DebugLogging) {
1456 for (const auto &Element : Pipeline) {
1457 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1459 // FIXME: No verifier support for Loop passes!
1464 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1465 ArrayRef<PipelineElement> Pipeline,
1466 bool VerifyEachPass,
1467 bool DebugLogging) {
1468 for (const auto &Element : Pipeline) {
1469 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1472 FPM.addPass(VerifierPass());
1477 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1478 ArrayRef<PipelineElement> Pipeline,
1479 bool VerifyEachPass,
1480 bool DebugLogging) {
1481 for (const auto &Element : Pipeline) {
1482 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1484 // FIXME: No verifier support for CGSCC passes!
1489 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1490 FunctionAnalysisManager &FAM,
1491 CGSCCAnalysisManager &CGAM,
1492 ModuleAnalysisManager &MAM) {
1493 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1494 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1495 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1496 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1497 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1498 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1499 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1502 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1503 ArrayRef<PipelineElement> Pipeline,
1504 bool VerifyEachPass,
1505 bool DebugLogging) {
1506 for (const auto &Element : Pipeline) {
1507 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1510 MPM.addPass(VerifierPass());
1515 // Primary pass pipeline description parsing routine.
1516 // FIXME: Should this routine accept a TargetMachine or require the caller to
1517 // pre-populate the analysis managers with target-specific stuff?
1518 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1519 StringRef PipelineText, bool VerifyEachPass,
1520 bool DebugLogging) {
1521 auto Pipeline = parsePipelineText(PipelineText);
1522 if (!Pipeline || Pipeline->empty())
1525 // If the first name isn't at the module layer, wrap the pipeline up
1527 StringRef FirstName = Pipeline->front().Name;
1529 if (!isModulePassName(FirstName)) {
1530 if (isCGSCCPassName(FirstName))
1531 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1532 else if (isFunctionPassName(FirstName))
1533 Pipeline = {{"function", std::move(*Pipeline)}};
1534 else if (isLoopPassName(FirstName))
1535 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1537 // Unknown pass name!
1541 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1544 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1545 // If the pipeline just consists of the word 'default' just replace the AA
1546 // manager with our default one.
1547 if (PipelineText == "default") {
1548 AA = buildDefaultAAPipeline();
1552 while (!PipelineText.empty()) {
1554 std::tie(Name, PipelineText) = PipelineText.split(',');
1555 if (!parseAAPassName(AA, Name))