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/BranchProbabilityInfo.h"
26 #include "llvm/Analysis/CFGPrinter.h"
27 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
28 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
29 #include "llvm/Analysis/CGSCCPassManager.h"
30 #include "llvm/Analysis/CallGraph.h"
31 #include "llvm/Analysis/DemandedBits.h"
32 #include "llvm/Analysis/DependenceAnalysis.h"
33 #include "llvm/Analysis/DominanceFrontier.h"
34 #include "llvm/Analysis/GlobalsModRef.h"
35 #include "llvm/Analysis/IVUsers.h"
36 #include "llvm/Analysis/LazyCallGraph.h"
37 #include "llvm/Analysis/LazyValueInfo.h"
38 #include "llvm/Analysis/LoopAccessAnalysis.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
41 #include "llvm/Analysis/MemorySSA.h"
42 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/PostDominators.h"
45 #include "llvm/Analysis/ProfileSummaryInfo.h"
46 #include "llvm/Analysis/RegionInfo.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
49 #include "llvm/Analysis/ScopedNoAliasAA.h"
50 #include "llvm/Analysis/TargetLibraryInfo.h"
51 #include "llvm/Analysis/TargetTransformInfo.h"
52 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
53 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
54 #include "llvm/CodeGen/UnreachableBlockElim.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/IRPrintingPasses.h"
57 #include "llvm/IR/PassManager.h"
58 #include "llvm/IR/Verifier.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/Regex.h"
61 #include "llvm/Target/TargetMachine.h"
62 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
63 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
64 #include "llvm/Transforms/IPO/AlwaysInliner.h"
65 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
66 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
67 #include "llvm/Transforms/IPO/ConstantMerge.h"
68 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
69 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
70 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
71 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
72 #include "llvm/Transforms/IPO/FunctionAttrs.h"
73 #include "llvm/Transforms/IPO/FunctionImport.h"
74 #include "llvm/Transforms/IPO/GlobalDCE.h"
75 #include "llvm/Transforms/IPO/GlobalOpt.h"
76 #include "llvm/Transforms/IPO/GlobalSplit.h"
77 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
78 #include "llvm/Transforms/IPO/Inliner.h"
79 #include "llvm/Transforms/IPO/Internalize.h"
80 #include "llvm/Transforms/IPO/LowerTypeTests.h"
81 #include "llvm/Transforms/IPO/PartialInlining.h"
82 #include "llvm/Transforms/IPO/SCCP.h"
83 #include "llvm/Transforms/IPO/SampleProfile.h"
84 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
85 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
86 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
87 #include "llvm/Transforms/InstCombine/InstCombine.h"
88 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
89 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
90 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
91 #include "llvm/Transforms/Scalar/ADCE.h"
92 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
93 #include "llvm/Transforms/Scalar/BDCE.h"
94 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
95 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
96 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
97 #include "llvm/Transforms/Scalar/DCE.h"
98 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
99 #include "llvm/Transforms/Scalar/DivRemPairs.h"
100 #include "llvm/Transforms/Scalar/EarlyCSE.h"
101 #include "llvm/Transforms/Scalar/Float2Int.h"
102 #include "llvm/Transforms/Scalar/GVN.h"
103 #include "llvm/Transforms/Scalar/GuardWidening.h"
104 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
105 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
106 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
107 #include "llvm/Transforms/Scalar/JumpThreading.h"
108 #include "llvm/Transforms/Scalar/LICM.h"
109 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
110 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
111 #include "llvm/Transforms/Scalar/LoopDeletion.h"
112 #include "llvm/Transforms/Scalar/LoopDistribute.h"
113 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
114 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
115 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
116 #include "llvm/Transforms/Scalar/LoopPassManager.h"
117 #include "llvm/Transforms/Scalar/LoopPredication.h"
118 #include "llvm/Transforms/Scalar/LoopRotation.h"
119 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
120 #include "llvm/Transforms/Scalar/LoopSink.h"
121 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
122 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
123 #include "llvm/Transforms/Scalar/LowerAtomic.h"
124 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
125 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
126 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
127 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
128 #include "llvm/Transforms/Scalar/NaryReassociate.h"
129 #include "llvm/Transforms/Scalar/NewGVN.h"
130 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
131 #include "llvm/Transforms/Scalar/Reassociate.h"
132 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
133 #include "llvm/Transforms/Scalar/SCCP.h"
134 #include "llvm/Transforms/Scalar/SROA.h"
135 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
136 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
137 #include "llvm/Transforms/Scalar/Sink.h"
138 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
139 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
140 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
141 #include "llvm/Transforms/Utils/AddDiscriminators.h"
142 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
143 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
144 #include "llvm/Transforms/Utils/LCSSA.h"
145 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
146 #include "llvm/Transforms/Utils/LoopSimplify.h"
147 #include "llvm/Transforms/Utils/LowerInvoke.h"
148 #include "llvm/Transforms/Utils/Mem2Reg.h"
149 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
150 #include "llvm/Transforms/Utils/SimplifyInstructions.h"
151 #include "llvm/Transforms/Utils/SymbolRewriter.h"
152 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
153 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
155 using namespace llvm;
157 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
158 cl::ReallyHidden, cl::init(4));
160 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
161 cl::Hidden, cl::ZeroOrMore,
162 cl::desc("Run Partial inlinining pass"));
165 RunNewGVN("enable-npm-newgvn", cl::init(false),
166 cl::Hidden, cl::ZeroOrMore,
167 cl::desc("Run NewGVN instead of GVN"));
169 static cl::opt<bool> EnableEarlyCSEMemSSA(
170 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden,
171 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)"));
173 static cl::opt<bool> EnableGVNHoist(
174 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
175 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
177 static cl::opt<bool> EnableGVNSink(
178 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
179 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
181 static cl::opt<bool> EnableSyntheticCounts(
182 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
183 cl::desc("Run synthetic function entry count generation "
186 static Regex DefaultAliasRegex(
187 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
189 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
191 case PassBuilder::O0:
192 case PassBuilder::O1:
193 case PassBuilder::O2:
194 case PassBuilder::O3:
197 case PassBuilder::Os:
198 case PassBuilder::Oz:
201 llvm_unreachable("Invalid optimization level!");
206 /// No-op module pass which does nothing.
207 struct NoOpModulePass {
208 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
209 return PreservedAnalyses::all();
211 static StringRef name() { return "NoOpModulePass"; }
214 /// No-op module analysis.
215 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
216 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
217 static AnalysisKey Key;
221 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
222 static StringRef name() { return "NoOpModuleAnalysis"; }
225 /// No-op CGSCC pass which does nothing.
226 struct NoOpCGSCCPass {
227 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
228 LazyCallGraph &, CGSCCUpdateResult &UR) {
229 return PreservedAnalyses::all();
231 static StringRef name() { return "NoOpCGSCCPass"; }
234 /// No-op CGSCC analysis.
235 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
236 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
237 static AnalysisKey Key;
241 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
244 static StringRef name() { return "NoOpCGSCCAnalysis"; }
247 /// No-op function pass which does nothing.
248 struct NoOpFunctionPass {
249 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
250 return PreservedAnalyses::all();
252 static StringRef name() { return "NoOpFunctionPass"; }
255 /// No-op function analysis.
256 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
257 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
258 static AnalysisKey Key;
262 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
263 static StringRef name() { return "NoOpFunctionAnalysis"; }
266 /// No-op loop pass which does nothing.
267 struct NoOpLoopPass {
268 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
269 LoopStandardAnalysisResults &, LPMUpdater &) {
270 return PreservedAnalyses::all();
272 static StringRef name() { return "NoOpLoopPass"; }
275 /// No-op loop analysis.
276 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
277 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
278 static AnalysisKey Key;
282 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
285 static StringRef name() { return "NoOpLoopAnalysis"; }
288 AnalysisKey NoOpModuleAnalysis::Key;
289 AnalysisKey NoOpCGSCCAnalysis::Key;
290 AnalysisKey NoOpFunctionAnalysis::Key;
291 AnalysisKey NoOpLoopAnalysis::Key;
293 } // End anonymous namespace.
295 void PassBuilder::invokePeepholeEPCallbacks(
296 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
297 for (auto &C : PeepholeEPCallbacks)
301 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
302 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
303 MAM.registerPass([&] { return CREATE_PASS; });
304 #include "PassRegistry.def"
306 for (auto &C : ModuleAnalysisRegistrationCallbacks)
310 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
311 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
312 CGAM.registerPass([&] { return CREATE_PASS; });
313 #include "PassRegistry.def"
315 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
319 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
320 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
321 FAM.registerPass([&] { return CREATE_PASS; });
322 #include "PassRegistry.def"
324 for (auto &C : FunctionAnalysisRegistrationCallbacks)
328 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
329 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
330 LAM.registerPass([&] { return CREATE_PASS; });
331 #include "PassRegistry.def"
333 for (auto &C : LoopAnalysisRegistrationCallbacks)
338 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
341 assert(Level != O0 && "Must request optimizations!");
342 FunctionPassManager FPM(DebugLogging);
344 // Form SSA out of local memory accesses after breaking apart aggregates into
348 // Catch trivial redundancies
349 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA));
351 // Hoisting of scalars and load expressions.
353 FPM.addPass(GVNHoistPass());
355 // Global value numbering based sinking.
357 FPM.addPass(GVNSinkPass());
358 FPM.addPass(SimplifyCFGPass());
361 // Speculative execution if the target has divergent branches; otherwise nop.
362 FPM.addPass(SpeculativeExecutionPass());
364 // Optimize based on known information about branches, and cleanup afterward.
365 FPM.addPass(JumpThreadingPass());
366 FPM.addPass(CorrelatedValuePropagationPass());
367 FPM.addPass(SimplifyCFGPass());
369 FPM.addPass(AggressiveInstCombinePass());
370 FPM.addPass(InstCombinePass());
372 if (!isOptimizingForSize(Level))
373 FPM.addPass(LibCallsShrinkWrapPass());
375 invokePeepholeEPCallbacks(FPM, Level);
377 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
378 // using the size value profile. Don't perform this when optimizing for size.
379 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() &&
380 !isOptimizingForSize(Level))
381 FPM.addPass(PGOMemOPSizeOpt());
383 FPM.addPass(TailCallElimPass());
384 FPM.addPass(SimplifyCFGPass());
386 // Form canonically associated expression trees, and simplify the trees using
387 // basic mathematical properties. For example, this will form (nearly)
388 // minimal multiplication trees.
389 FPM.addPass(ReassociatePass());
391 // Add the primary loop simplification pipeline.
392 // FIXME: Currently this is split into two loop pass pipelines because we run
393 // some function passes in between them. These can and should be replaced by
394 // loop pass equivalenst but those aren't ready yet. Specifically,
395 // `SimplifyCFGPass` and `InstCombinePass` are used. We have
396 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
397 // the other we have is `LoopInstSimplify`.
398 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
400 // Rotate Loop - disable header duplication at -Oz
401 LPM1.addPass(LoopRotatePass(Level != Oz));
402 LPM1.addPass(LICMPass());
403 LPM1.addPass(SimpleLoopUnswitchPass());
404 LPM2.addPass(IndVarSimplifyPass());
405 LPM2.addPass(LoopIdiomRecognizePass());
407 for (auto &C : LateLoopOptimizationsEPCallbacks)
410 LPM2.addPass(LoopDeletionPass());
411 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
412 // because it changes IR to makes profile annotation in back compile
414 if (Phase != ThinLTOPhase::PreLink ||
415 !PGOOpt || PGOOpt->SampleProfileFile.empty())
416 LPM2.addPass(LoopFullUnrollPass(Level));
418 for (auto &C : LoopOptimizerEndEPCallbacks)
421 // We provide the opt remark emitter pass for LICM to use. We only need to do
422 // this once as it is immutable.
423 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
424 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging));
425 FPM.addPass(SimplifyCFGPass());
426 FPM.addPass(InstCombinePass());
427 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging));
429 // Eliminate redundancies.
431 // These passes add substantial compile time so skip them at O1.
432 FPM.addPass(MergedLoadStoreMotionPass());
434 FPM.addPass(NewGVNPass());
439 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
440 FPM.addPass(MemCpyOptPass());
442 // Sparse conditional constant propagation.
443 // FIXME: It isn't clear why we do this *after* loop passes rather than
445 FPM.addPass(SCCPPass());
447 // Delete dead bit computations (instcombine runs after to fold away the dead
448 // computations, and then ADCE will run later to exploit any new DCE
449 // opportunities that creates).
450 FPM.addPass(BDCEPass());
452 // Run instcombine after redundancy and dead bit elimination to exploit
453 // opportunities opened up by them.
454 FPM.addPass(InstCombinePass());
455 invokePeepholeEPCallbacks(FPM, Level);
457 // Re-consider control flow based optimizations after redundancy elimination,
459 FPM.addPass(JumpThreadingPass());
460 FPM.addPass(CorrelatedValuePropagationPass());
461 FPM.addPass(DSEPass());
462 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
464 for (auto &C : ScalarOptimizerLateEPCallbacks)
467 // Finally, do an expensive DCE pass to catch all the dead code exposed by
468 // the simplifications and basic cleanup after all the simplifications.
469 FPM.addPass(ADCEPass());
470 FPM.addPass(SimplifyCFGPass());
471 FPM.addPass(InstCombinePass());
472 invokePeepholeEPCallbacks(FPM, Level);
477 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
478 PassBuilder::OptimizationLevel Level,
480 std::string ProfileGenFile,
481 std::string ProfileUseFile) {
482 // Generally running simplification passes and the inliner with an high
483 // threshold results in smaller executables, but there may be cases where
484 // the size grows, so let's be conservative here and skip this simplification
486 if (!isOptimizingForSize(Level)) {
489 // In the old pass manager, this is a cl::opt. Should still this be one?
490 IP.DefaultThreshold = 75;
492 // FIXME: The hint threshold has the same value used by the regular inliner.
493 // This should probably be lowered after performance testing.
494 // FIXME: this comment is cargo culted from the old pass manager, revisit).
495 IP.HintThreshold = 325;
497 CGSCCPassManager CGPipeline(DebugLogging);
499 CGPipeline.addPass(InlinerPass(IP));
501 FunctionPassManager FPM;
503 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
504 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
505 FPM.addPass(InstCombinePass()); // Combine silly sequences.
506 invokePeepholeEPCallbacks(FPM, Level);
508 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
510 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
513 // Delete anything that is now dead to make sure that we don't instrument
514 // dead code. Instrumentation can end up keeping dead code around and
515 // dramatically increase code size.
516 MPM.addPass(GlobalDCEPass());
519 MPM.addPass(PGOInstrumentationGen());
521 FunctionPassManager FPM;
523 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
524 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
526 // Add the profile lowering pass.
527 InstrProfOptions Options;
528 if (!ProfileGenFile.empty())
529 Options.InstrProfileOutput = ProfileGenFile;
530 Options.DoCounterPromotion = true;
531 MPM.addPass(InstrProfiling(Options));
534 if (!ProfileUseFile.empty())
535 MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
539 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
540 auto O3 = PassBuilder::O3;
541 unsigned OptLevel = Level > O3 ? 2 : Level;
542 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
543 return getInlineParams(OptLevel, SizeLevel);
547 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
550 ModulePassManager MPM(DebugLogging);
552 // Do basic inference of function attributes from known properties of system
553 // libraries and other oracles.
554 MPM.addPass(InferFunctionAttrsPass());
556 // Create an early function pass manager to cleanup the output of the
558 FunctionPassManager EarlyFPM(DebugLogging);
559 EarlyFPM.addPass(SimplifyCFGPass());
560 EarlyFPM.addPass(SROA());
561 EarlyFPM.addPass(EarlyCSEPass());
562 EarlyFPM.addPass(LowerExpectIntrinsicPass());
564 EarlyFPM.addPass(CallSiteSplittingPass());
566 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
567 // to convert bitcast to direct calls so that they can be inlined during the
568 // profile annotation prepration step.
569 // More details about SamplePGO design can be found in:
570 // https://research.google.com/pubs/pub45290.html
571 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
572 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() &&
573 Phase == ThinLTOPhase::PostLink)
574 EarlyFPM.addPass(InstCombinePass());
575 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
577 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) {
578 // Annotate sample profile right after early FPM to ensure freshness of
580 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile,
581 Phase == ThinLTOPhase::PreLink));
582 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
583 // for the profile annotation to be accurate in the ThinLTO backend.
584 if (Phase != ThinLTOPhase::PreLink)
585 // We perform early indirect call promotion here, before globalopt.
586 // This is important for the ThinLTO backend phase because otherwise
587 // imported available_externally functions look unreferenced and are
589 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
593 // Interprocedural constant propagation now that basic cleanup has occurred
594 // and prior to optimizing globals.
595 // FIXME: This position in the pipeline hasn't been carefully considered in
596 // years, it should be re-analyzed.
597 MPM.addPass(IPSCCPPass());
599 // Attach metadata to indirect call sites indicating the set of functions
600 // they may target at run-time. This should follow IPSCCP.
601 MPM.addPass(CalledValuePropagationPass());
603 // Optimize globals to try and fold them into constants.
604 MPM.addPass(GlobalOptPass());
606 // Promote any localized globals to SSA registers.
607 // FIXME: Should this instead by a run of SROA?
608 // FIXME: We should probably run instcombine and simplify-cfg afterward to
609 // delete control flows that are dead once globals have been folded to
611 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
613 // Remove any dead arguments exposed by cleanups and constand folding
615 MPM.addPass(DeadArgumentEliminationPass());
617 // Create a small function pass pipeline to cleanup after all the global
619 FunctionPassManager GlobalCleanupPM(DebugLogging);
620 GlobalCleanupPM.addPass(InstCombinePass());
621 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
623 GlobalCleanupPM.addPass(SimplifyCFGPass());
624 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
626 // Add all the requested passes for instrumentation PGO, if requested.
627 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
628 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) {
629 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
630 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
631 MPM.addPass(PGOIndirectCallPromotion(false, false));
634 // Synthesize function entry counts for non-PGO compilation.
635 if (EnableSyntheticCounts && !PGOOpt)
636 MPM.addPass(SyntheticCountsPropagation());
638 // Require the GlobalsAA analysis for the module so we can query it within
639 // the CGSCC pipeline.
640 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
642 // Require the ProfileSummaryAnalysis for the module so we can query it within
644 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
646 // Now begin the main postorder CGSCC pipeline.
647 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
648 // manager and trying to emulate its precise behavior. Much of this doesn't
649 // make a lot of sense and we should revisit the core CGSCC structure.
650 CGSCCPassManager MainCGPipeline(DebugLogging);
652 // Note: historically, the PruneEH pass was run first to deduce nounwind and
653 // generally clean up exception handling overhead. It isn't clear this is
654 // valuable as the inliner doesn't currently care whether it is inlining an
657 // Run the inliner first. The theory is that we are walking bottom-up and so
658 // the callees have already been fully optimized, and we want to inline them
659 // into the callers so that our optimizations can reflect that.
660 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
661 // because it makes profile annotation in the backend inaccurate.
662 InlineParams IP = getInlineParamsFromOptLevel(Level);
663 if (Phase == ThinLTOPhase::PreLink &&
664 PGOOpt && !PGOOpt->SampleProfileFile.empty())
665 IP.HotCallSiteThreshold = 0;
666 MainCGPipeline.addPass(InlinerPass(IP));
668 // Now deduce any function attributes based in the current code.
669 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
671 // When at O3 add argument promotion to the pass pipeline.
672 // FIXME: It isn't at all clear why this should be limited to O3.
674 MainCGPipeline.addPass(ArgumentPromotionPass());
676 // Lastly, add the core function simplification pipeline nested inside the
678 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
679 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
681 for (auto &C : CGSCCOptimizerLateEPCallbacks)
682 C(MainCGPipeline, Level);
684 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
685 // to detect when we devirtualize indirect calls and iterate the SCC passes
686 // in that case to try and catch knock-on inlining or function attrs
687 // opportunities. Then we add it to the module pipeline by walking the SCCs
688 // in postorder (or bottom-up).
690 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
691 std::move(MainCGPipeline), MaxDevirtIterations)));
697 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
699 ModulePassManager MPM(DebugLogging);
701 // Optimize globals now that the module is fully simplified.
702 MPM.addPass(GlobalOptPass());
703 MPM.addPass(GlobalDCEPass());
705 // Run partial inlining pass to partially inline functions that have
707 if (RunPartialInlining)
708 MPM.addPass(PartialInlinerPass());
710 // Remove avail extern fns and globals definitions since we aren't compiling
711 // an object file for later LTO. For LTO we want to preserve these so they
712 // are eligible for inlining at link-time. Note if they are unreferenced they
713 // will be removed by GlobalDCE later, so this only impacts referenced
714 // available externally globals. Eventually they will be suppressed during
715 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
716 // may make globals referenced by available external functions dead and saves
717 // running remaining passes on the eliminated functions.
718 MPM.addPass(EliminateAvailableExternallyPass());
720 // Do RPO function attribute inference across the module to forward-propagate
721 // attributes where applicable.
722 // FIXME: Is this really an optimization rather than a canonicalization?
723 MPM.addPass(ReversePostOrderFunctionAttrsPass());
725 // Re-require GloblasAA here prior to function passes. This is particularly
726 // useful as the above will have inlined, DCE'ed, and function-attr
727 // propagated everything. We should at this point have a reasonably minimal
728 // and richly annotated call graph. By computing aliasing and mod/ref
729 // information for all local globals here, the late loop passes and notably
730 // the vectorizer will be able to use them to help recognize vectorizable
731 // memory operations.
732 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
734 FunctionPassManager OptimizePM(DebugLogging);
735 OptimizePM.addPass(Float2IntPass());
736 // FIXME: We need to run some loop optimizations to re-rotate loops after
737 // simplify-cfg and others undo their rotation.
739 // Optimize the loop execution. These passes operate on entire loop nests
740 // rather than on each loop in an inside-out manner, and so they are actually
743 for (auto &C : VectorizerStartEPCallbacks)
744 C(OptimizePM, Level);
746 // First rotate loops that may have been un-rotated by prior passes.
748 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging));
750 // Distribute loops to allow partial vectorization. I.e. isolate dependences
751 // into separate loop that would otherwise inhibit vectorization. This is
752 // currently only performed for loops marked with the metadata
753 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
754 OptimizePM.addPass(LoopDistributePass());
756 // Now run the core loop vectorizer.
757 OptimizePM.addPass(LoopVectorizePass());
759 // Eliminate loads by forwarding stores from the previous iteration to loads
760 // of the current iteration.
761 OptimizePM.addPass(LoopLoadEliminationPass());
763 // Cleanup after the loop optimization passes.
764 OptimizePM.addPass(InstCombinePass());
766 // Now that we've formed fast to execute loop structures, we do further
767 // optimizations. These are run afterward as they might block doing complex
768 // analyses and transforms such as what are needed for loop vectorization.
770 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
771 // GVN, loop transforms, and others have already run, so it's now better to
772 // convert to more optimized IR using more aggressive simplify CFG options.
773 // The extra sinking transform can create larger basic blocks, so do this
774 // before SLP vectorization.
775 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
776 forwardSwitchCondToPhi(true).
777 convertSwitchToLookupTable(true).
778 needCanonicalLoops(false).
779 sinkCommonInsts(true)));
781 // Optimize parallel scalar instruction chains into SIMD instructions.
782 OptimizePM.addPass(SLPVectorizerPass());
784 OptimizePM.addPass(InstCombinePass());
786 // Unroll small loops to hide loop backedge latency and saturate any parallel
787 // execution resources of an out-of-order processor. We also then need to
788 // clean up redundancies and loop invariant code.
789 // FIXME: It would be really good to use a loop-integrated instruction
790 // combiner for cleanup here so that the unrolling and LICM can be pipelined
791 // across the loop nests.
792 OptimizePM.addPass(LoopUnrollPass(Level));
793 OptimizePM.addPass(InstCombinePass());
794 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
795 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging));
797 // Now that we've vectorized and unrolled loops, we may have more refined
798 // alignment information, try to re-derive it here.
799 OptimizePM.addPass(AlignmentFromAssumptionsPass());
801 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
802 // canonicalization pass that enables other optimizations. As a result,
803 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
805 OptimizePM.addPass(LoopSinkPass());
807 // And finally clean up LCSSA form before generating code.
808 OptimizePM.addPass(InstSimplifierPass());
810 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
811 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
812 // flattening of blocks.
813 OptimizePM.addPass(DivRemPairsPass());
815 // LoopSink (and other loop passes since the last simplifyCFG) might have
816 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
817 OptimizePM.addPass(SimplifyCFGPass());
819 // Optimize PHIs by speculating around them when profitable. Note that this
820 // pass needs to be run after any PRE or similar pass as it is essentially
821 // inserting redudnancies into the progrem. This even includes SimplifyCFG.
822 OptimizePM.addPass(SpeculateAroundPHIsPass());
824 // Add the core optimizing pipeline.
825 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
827 // Now we need to do some global optimization transforms.
828 // FIXME: It would seem like these should come first in the optimization
829 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
831 MPM.addPass(GlobalDCEPass());
832 MPM.addPass(ConstantMergePass());
838 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
840 assert(Level != O0 && "Must request optimizations for the default pipeline!");
842 ModulePassManager MPM(DebugLogging);
844 // Force any function attributes we want the rest of the pipeline to observe.
845 MPM.addPass(ForceFunctionAttrsPass());
847 // Apply module pipeline start EP callback.
848 for (auto &C : PipelineStartEPCallbacks)
851 if (PGOOpt && PGOOpt->SamplePGOSupport)
852 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
854 // Add the core simplification pipeline.
855 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
858 // Now add the optimization pipeline.
859 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
865 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
867 assert(Level != O0 && "Must request optimizations for the default pipeline!");
869 ModulePassManager MPM(DebugLogging);
871 // Force any function attributes we want the rest of the pipeline to observe.
872 MPM.addPass(ForceFunctionAttrsPass());
874 if (PGOOpt && PGOOpt->SamplePGOSupport)
875 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
877 // Apply module pipeline start EP callback.
878 for (auto &C : PipelineStartEPCallbacks)
881 // If we are planning to perform ThinLTO later, we don't bloat the code with
882 // unrolling/vectorization/... now. Just simplify the module as much as we
884 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
887 // Run partial inlining pass to partially inline functions that have
889 // FIXME: It isn't clear whether this is really the right place to run this
890 // in ThinLTO. Because there is another canonicalization and simplification
891 // phase that will run after the thin link, running this here ends up with
892 // less information than will be available later and it may grow functions in
893 // ways that aren't beneficial.
894 if (RunPartialInlining)
895 MPM.addPass(PartialInlinerPass());
897 // Reduce the size of the IR as much as possible.
898 MPM.addPass(GlobalOptPass());
904 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
906 // FIXME: The summary index is not hooked in the new pass manager yet.
907 // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
910 ModulePassManager MPM(DebugLogging);
912 // Force any function attributes we want the rest of the pipeline to observe.
913 MPM.addPass(ForceFunctionAttrsPass());
915 // During the ThinLTO backend phase we perform early indirect call promotion
916 // here, before globalopt. Otherwise imported available_externally functions
917 // look unreferenced and are removed.
918 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic
920 if (!PGOOpt || PGOOpt->SampleProfileFile.empty())
921 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
922 false /* SamplePGO */));
924 // Add the core simplification pipeline.
925 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
928 // Now add the optimization pipeline.
929 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
935 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
937 assert(Level != O0 && "Must request optimizations for the default pipeline!");
938 // FIXME: We should use a customized pre-link pipeline!
939 return buildPerModuleDefaultPipeline(Level, DebugLogging);
942 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
944 assert(Level != O0 && "Must request optimizations for the default pipeline!");
945 ModulePassManager MPM(DebugLogging);
947 // Remove unused virtual tables to improve the quality of code generated by
948 // whole-program devirtualization and bitset lowering.
949 MPM.addPass(GlobalDCEPass());
951 // Force any function attributes we want the rest of the pipeline to observe.
952 MPM.addPass(ForceFunctionAttrsPass());
954 // Do basic inference of function attributes from known properties of system
955 // libraries and other oracles.
956 MPM.addPass(InferFunctionAttrsPass());
959 FunctionPassManager EarlyFPM(DebugLogging);
960 EarlyFPM.addPass(CallSiteSplittingPass());
961 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
963 // Indirect call promotion. This should promote all the targets that are
964 // left by the earlier promotion pass that promotes intra-module targets.
965 // This two-step promotion is to save the compile time. For LTO, it should
966 // produce the same result as if we only do promotion here.
967 MPM.addPass(PGOIndirectCallPromotion(
968 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty()));
969 // Propagate constants at call sites into the functions they call. This
970 // opens opportunities for globalopt (and inlining) by substituting function
971 // pointers passed as arguments to direct uses of functions.
972 MPM.addPass(IPSCCPPass());
974 // Attach metadata to indirect call sites indicating the set of functions
975 // they may target at run-time. This should follow IPSCCP.
976 MPM.addPass(CalledValuePropagationPass());
979 // Now deduce any function attributes based in the current code.
980 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
981 PostOrderFunctionAttrsPass()));
983 // Do RPO function attribute inference across the module to forward-propagate
984 // attributes where applicable.
985 // FIXME: Is this really an optimization rather than a canonicalization?
986 MPM.addPass(ReversePostOrderFunctionAttrsPass());
988 // Use inragne annotations on GEP indices to split globals where beneficial.
989 MPM.addPass(GlobalSplitPass());
991 // Run whole program optimization of virtual call when the list of callees
993 MPM.addPass(WholeProgramDevirtPass());
999 // Optimize globals to try and fold them into constants.
1000 MPM.addPass(GlobalOptPass());
1002 // Promote any localized globals to SSA registers.
1003 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1005 // Linking modules together can lead to duplicate global constant, only
1006 // keep one copy of each constant.
1007 MPM.addPass(ConstantMergePass());
1009 // Remove unused arguments from functions.
1010 MPM.addPass(DeadArgumentEliminationPass());
1012 // Reduce the code after globalopt and ipsccp. Both can open up significant
1013 // simplification opportunities, and both can propagate functions through
1014 // function pointers. When this happens, we often have to resolve varargs
1015 // calls, etc, so let instcombine do this.
1016 FunctionPassManager PeepholeFPM(DebugLogging);
1018 PeepholeFPM.addPass(AggressiveInstCombinePass());
1019 PeepholeFPM.addPass(InstCombinePass());
1020 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1022 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1024 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1025 // generally clean up exception handling overhead. It isn't clear this is
1026 // valuable as the inliner doesn't currently care whether it is inlining an
1027 // invoke or a call.
1028 // Run the inliner now.
1029 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1030 InlinerPass(getInlineParamsFromOptLevel(Level))));
1032 // Optimize globals again after we ran the inliner.
1033 MPM.addPass(GlobalOptPass());
1035 // Garbage collect dead functions.
1036 // FIXME: Add ArgumentPromotion pass after once it's ported.
1037 MPM.addPass(GlobalDCEPass());
1039 FunctionPassManager FPM(DebugLogging);
1040 // The IPO Passes may leave cruft around. Clean up after them.
1041 FPM.addPass(InstCombinePass());
1042 invokePeepholeEPCallbacks(FPM, Level);
1044 FPM.addPass(JumpThreadingPass());
1047 FPM.addPass(SROA());
1049 // Run a few AA driver optimizations here and now to cleanup the code.
1050 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1052 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1053 PostOrderFunctionAttrsPass()));
1054 // FIXME: here we run IP alias analysis in the legacy PM.
1056 FunctionPassManager MainFPM;
1058 // FIXME: once we fix LoopPass Manager, add LICM here.
1059 // FIXME: once we provide support for enabling MLSM, add it here.
1060 // FIXME: once we provide support for enabling NewGVN, add it here.
1062 MainFPM.addPass(NewGVNPass());
1064 MainFPM.addPass(GVN());
1066 // Remove dead memcpy()'s.
1067 MainFPM.addPass(MemCpyOptPass());
1069 // Nuke dead stores.
1070 MainFPM.addPass(DSEPass());
1072 // FIXME: at this point, we run a bunch of loop passes:
1073 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
1074 // loopVectorize. Enable them once the remaining issue with LPM
1077 MainFPM.addPass(InstCombinePass());
1078 MainFPM.addPass(SimplifyCFGPass());
1079 MainFPM.addPass(SCCPPass());
1080 MainFPM.addPass(InstCombinePass());
1081 MainFPM.addPass(BDCEPass());
1083 // FIXME: We may want to run SLPVectorizer here.
1084 // After vectorization, assume intrinsics may tell us more
1085 // about pointer alignments.
1087 MainFPM.add(AlignmentFromAssumptionsPass());
1090 // FIXME: Conditionally run LoadCombine here, after it's ported
1091 // (in case we still have this pass, given its questionable usefulness).
1093 MainFPM.addPass(InstCombinePass());
1094 invokePeepholeEPCallbacks(MainFPM, Level);
1095 MainFPM.addPass(JumpThreadingPass());
1096 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1098 // Create a function that performs CFI checks for cross-DSO calls with
1099 // targets in the current module.
1100 MPM.addPass(CrossDSOCFIPass());
1102 // Lower type metadata and the type.test intrinsic. This pass supports
1103 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1104 // to be run at link time if CFI is enabled. This pass does nothing if
1106 // Enable once we add support for the summary in the new PM.
1108 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
1109 PassSummaryAction::None,
1113 // Add late LTO optimization passes.
1114 // Delete basic blocks, which optimization passes may have killed.
1115 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1117 // Drop bodies of available eternally objects to improve GlobalDCE.
1118 MPM.addPass(EliminateAvailableExternallyPass());
1120 // Now that we have optimized the program, discard unreachable functions.
1121 MPM.addPass(GlobalDCEPass());
1123 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
1127 AAManager PassBuilder::buildDefaultAAPipeline() {
1130 // The order in which these are registered determines their priority when
1133 // First we register the basic alias analysis that provides the majority of
1134 // per-function local AA logic. This is a stateless, on-demand local set of
1136 AA.registerFunctionAnalysis<BasicAA>();
1138 // Next we query fast, specialized alias analyses that wrap IR-embedded
1139 // information about aliasing.
1140 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1141 AA.registerFunctionAnalysis<TypeBasedAA>();
1143 // Add support for querying global aliasing information when available.
1144 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1145 // analysis, all that the `AAManager` can do is query for any *cached*
1146 // results from `GlobalsAA` through a readonly proxy.
1147 AA.registerModuleAnalysis<GlobalsAA>();
1152 static Optional<int> parseRepeatPassName(StringRef Name) {
1153 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1156 if (Name.getAsInteger(0, Count) || Count <= 0)
1161 static Optional<int> parseDevirtPassName(StringRef Name) {
1162 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1165 if (Name.getAsInteger(0, Count) || Count <= 0)
1170 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1172 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1173 return Name.startswith("default") || Name.startswith("thinlto") ||
1174 Name.startswith("lto");
1177 /// Tests whether registered callbacks will accept a given pass name.
1179 /// When parsing a pipeline text, the type of the outermost pipeline may be
1180 /// omitted, in which case the type is automatically determined from the first
1181 /// pass name in the text. This may be a name that is handled through one of the
1182 /// callbacks. We check this through the oridinary parsing callbacks by setting
1183 /// up a dummy PassManager in order to not force the client to also handle this
1185 template <typename PassManagerT, typename CallbacksT>
1186 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1187 if (!Callbacks.empty()) {
1188 PassManagerT DummyPM;
1189 for (auto &CB : Callbacks)
1190 if (CB(Name, DummyPM, {}))
1196 template <typename CallbacksT>
1197 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1198 // Manually handle aliases for pre-configured pipeline fragments.
1199 if (startsWithDefaultPipelineAliasPrefix(Name))
1200 return DefaultAliasRegex.match(Name);
1202 // Explicitly handle pass manager names.
1203 if (Name == "module")
1205 if (Name == "cgscc")
1207 if (Name == "function")
1210 // Explicitly handle custom-parsed pass names.
1211 if (parseRepeatPassName(Name))
1214 #define MODULE_PASS(NAME, CREATE_PASS) \
1217 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1218 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1220 #include "PassRegistry.def"
1222 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1225 template <typename CallbacksT>
1226 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1227 // Explicitly handle pass manager names.
1228 if (Name == "cgscc")
1230 if (Name == "function")
1233 // Explicitly handle custom-parsed pass names.
1234 if (parseRepeatPassName(Name))
1236 if (parseDevirtPassName(Name))
1239 #define CGSCC_PASS(NAME, CREATE_PASS) \
1242 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1243 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1245 #include "PassRegistry.def"
1247 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1250 template <typename CallbacksT>
1251 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1252 // Explicitly handle pass manager names.
1253 if (Name == "function")
1258 // Explicitly handle custom-parsed pass names.
1259 if (parseRepeatPassName(Name))
1262 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1265 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1266 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1268 #include "PassRegistry.def"
1270 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1273 template <typename CallbacksT>
1274 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1275 // Explicitly handle pass manager names.
1279 // Explicitly handle custom-parsed pass names.
1280 if (parseRepeatPassName(Name))
1283 #define LOOP_PASS(NAME, CREATE_PASS) \
1286 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1287 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1289 #include "PassRegistry.def"
1291 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1294 Optional<std::vector<PassBuilder::PipelineElement>>
1295 PassBuilder::parsePipelineText(StringRef Text) {
1296 std::vector<PipelineElement> ResultPipeline;
1298 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1301 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1302 size_t Pos = Text.find_first_of(",()");
1303 Pipeline.push_back({Text.substr(0, Pos), {}});
1305 // If we have a single terminating name, we're done.
1306 if (Pos == Text.npos)
1309 char Sep = Text[Pos];
1310 Text = Text.substr(Pos + 1);
1312 // Just a name ending in a comma, continue.
1316 // Push the inner pipeline onto the stack to continue processing.
1317 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1321 assert(Sep == ')' && "Bogus separator!");
1322 // When handling the close parenthesis, we greedily consume them to avoid
1323 // empty strings in the pipeline.
1325 // If we try to pop the outer pipeline we have unbalanced parentheses.
1326 if (PipelineStack.size() == 1)
1329 PipelineStack.pop_back();
1330 } while (Text.consume_front(")"));
1332 // Check if we've finished parsing.
1336 // Otherwise, the end of an inner pipeline always has to be followed by
1337 // a comma, and then we can continue.
1338 if (!Text.consume_front(","))
1342 if (PipelineStack.size() > 1)
1343 // Unbalanced paretheses.
1346 assert(PipelineStack.back() == &ResultPipeline &&
1347 "Wrong pipeline at the bottom of the stack!");
1348 return {std::move(ResultPipeline)};
1351 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1352 const PipelineElement &E, bool VerifyEachPass,
1353 bool DebugLogging) {
1354 auto &Name = E.Name;
1355 auto &InnerPipeline = E.InnerPipeline;
1357 // First handle complex passes like the pass managers which carry pipelines.
1358 if (!InnerPipeline.empty()) {
1359 if (Name == "module") {
1360 ModulePassManager NestedMPM(DebugLogging);
1361 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1364 MPM.addPass(std::move(NestedMPM));
1367 if (Name == "cgscc") {
1368 CGSCCPassManager CGPM(DebugLogging);
1369 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1372 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1375 if (Name == "function") {
1376 FunctionPassManager FPM(DebugLogging);
1377 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1380 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1383 if (auto Count = parseRepeatPassName(Name)) {
1384 ModulePassManager NestedMPM(DebugLogging);
1385 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1388 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1392 for (auto &C : ModulePipelineParsingCallbacks)
1393 if (C(Name, MPM, InnerPipeline))
1396 // Normal passes can't have pipelines.
1400 // Manually handle aliases for pre-configured pipeline fragments.
1401 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1402 SmallVector<StringRef, 3> Matches;
1403 if (!DefaultAliasRegex.match(Name, &Matches))
1405 assert(Matches.size() == 3 && "Must capture two matched strings!");
1407 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1415 // At O0 we do nothing at all!
1418 if (Matches[1] == "default") {
1419 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1420 } else if (Matches[1] == "thinlto-pre-link") {
1421 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1422 } else if (Matches[1] == "thinlto") {
1423 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1424 } else if (Matches[1] == "lto-pre-link") {
1425 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1427 assert(Matches[1] == "lto" && "Not one of the matched options!");
1428 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1433 // Finally expand the basic registered passes from the .inc file.
1434 #define MODULE_PASS(NAME, CREATE_PASS) \
1435 if (Name == NAME) { \
1436 MPM.addPass(CREATE_PASS); \
1439 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1440 if (Name == "require<" NAME ">") { \
1442 RequireAnalysisPass< \
1443 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1446 if (Name == "invalidate<" NAME ">") { \
1447 MPM.addPass(InvalidateAnalysisPass< \
1448 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1451 #include "PassRegistry.def"
1453 for (auto &C : ModulePipelineParsingCallbacks)
1454 if (C(Name, MPM, InnerPipeline))
1459 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1460 const PipelineElement &E, bool VerifyEachPass,
1461 bool DebugLogging) {
1462 auto &Name = E.Name;
1463 auto &InnerPipeline = E.InnerPipeline;
1465 // First handle complex passes like the pass managers which carry pipelines.
1466 if (!InnerPipeline.empty()) {
1467 if (Name == "cgscc") {
1468 CGSCCPassManager NestedCGPM(DebugLogging);
1469 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1472 // Add the nested pass manager with the appropriate adaptor.
1473 CGPM.addPass(std::move(NestedCGPM));
1476 if (Name == "function") {
1477 FunctionPassManager FPM(DebugLogging);
1478 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1481 // Add the nested pass manager with the appropriate adaptor.
1482 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1485 if (auto Count = parseRepeatPassName(Name)) {
1486 CGSCCPassManager NestedCGPM(DebugLogging);
1487 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1490 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1493 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1494 CGSCCPassManager NestedCGPM(DebugLogging);
1495 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1499 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1503 for (auto &C : CGSCCPipelineParsingCallbacks)
1504 if (C(Name, CGPM, InnerPipeline))
1507 // Normal passes can't have pipelines.
1511 // Now expand the basic registered passes from the .inc file.
1512 #define CGSCC_PASS(NAME, CREATE_PASS) \
1513 if (Name == NAME) { \
1514 CGPM.addPass(CREATE_PASS); \
1517 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1518 if (Name == "require<" NAME ">") { \
1519 CGPM.addPass(RequireAnalysisPass< \
1520 std::remove_reference<decltype(CREATE_PASS)>::type, \
1521 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1522 CGSCCUpdateResult &>()); \
1525 if (Name == "invalidate<" NAME ">") { \
1526 CGPM.addPass(InvalidateAnalysisPass< \
1527 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1530 #include "PassRegistry.def"
1532 for (auto &C : CGSCCPipelineParsingCallbacks)
1533 if (C(Name, CGPM, InnerPipeline))
1538 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1539 const PipelineElement &E,
1540 bool VerifyEachPass, bool DebugLogging) {
1541 auto &Name = E.Name;
1542 auto &InnerPipeline = E.InnerPipeline;
1544 // First handle complex passes like the pass managers which carry pipelines.
1545 if (!InnerPipeline.empty()) {
1546 if (Name == "function") {
1547 FunctionPassManager NestedFPM(DebugLogging);
1548 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1551 // Add the nested pass manager with the appropriate adaptor.
1552 FPM.addPass(std::move(NestedFPM));
1555 if (Name == "loop") {
1556 LoopPassManager LPM(DebugLogging);
1557 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1560 // Add the nested pass manager with the appropriate adaptor.
1562 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging));
1565 if (auto Count = parseRepeatPassName(Name)) {
1566 FunctionPassManager NestedFPM(DebugLogging);
1567 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1570 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1574 for (auto &C : FunctionPipelineParsingCallbacks)
1575 if (C(Name, FPM, InnerPipeline))
1578 // Normal passes can't have pipelines.
1582 // Now expand the basic registered passes from the .inc file.
1583 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1584 if (Name == NAME) { \
1585 FPM.addPass(CREATE_PASS); \
1588 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1589 if (Name == "require<" NAME ">") { \
1591 RequireAnalysisPass< \
1592 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1595 if (Name == "invalidate<" NAME ">") { \
1596 FPM.addPass(InvalidateAnalysisPass< \
1597 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1600 #include "PassRegistry.def"
1602 for (auto &C : FunctionPipelineParsingCallbacks)
1603 if (C(Name, FPM, InnerPipeline))
1608 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1609 bool VerifyEachPass, bool DebugLogging) {
1610 StringRef Name = E.Name;
1611 auto &InnerPipeline = E.InnerPipeline;
1613 // First handle complex passes like the pass managers which carry pipelines.
1614 if (!InnerPipeline.empty()) {
1615 if (Name == "loop") {
1616 LoopPassManager NestedLPM(DebugLogging);
1617 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1620 // Add the nested pass manager with the appropriate adaptor.
1621 LPM.addPass(std::move(NestedLPM));
1624 if (auto Count = parseRepeatPassName(Name)) {
1625 LoopPassManager NestedLPM(DebugLogging);
1626 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1629 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1633 for (auto &C : LoopPipelineParsingCallbacks)
1634 if (C(Name, LPM, InnerPipeline))
1637 // Normal passes can't have pipelines.
1641 // Now expand the basic registered passes from the .inc file.
1642 #define LOOP_PASS(NAME, CREATE_PASS) \
1643 if (Name == NAME) { \
1644 LPM.addPass(CREATE_PASS); \
1647 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1648 if (Name == "require<" NAME ">") { \
1649 LPM.addPass(RequireAnalysisPass< \
1650 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1651 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1655 if (Name == "invalidate<" NAME ">") { \
1656 LPM.addPass(InvalidateAnalysisPass< \
1657 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1660 #include "PassRegistry.def"
1662 for (auto &C : LoopPipelineParsingCallbacks)
1663 if (C(Name, LPM, InnerPipeline))
1668 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1669 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1670 if (Name == NAME) { \
1671 AA.registerModuleAnalysis< \
1672 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1675 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1676 if (Name == NAME) { \
1677 AA.registerFunctionAnalysis< \
1678 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1681 #include "PassRegistry.def"
1683 for (auto &C : AAParsingCallbacks)
1689 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1690 ArrayRef<PipelineElement> Pipeline,
1691 bool VerifyEachPass,
1692 bool DebugLogging) {
1693 for (const auto &Element : Pipeline) {
1694 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1696 // FIXME: No verifier support for Loop passes!
1701 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1702 ArrayRef<PipelineElement> Pipeline,
1703 bool VerifyEachPass,
1704 bool DebugLogging) {
1705 for (const auto &Element : Pipeline) {
1706 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1709 FPM.addPass(VerifierPass());
1714 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1715 ArrayRef<PipelineElement> Pipeline,
1716 bool VerifyEachPass,
1717 bool DebugLogging) {
1718 for (const auto &Element : Pipeline) {
1719 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1721 // FIXME: No verifier support for CGSCC passes!
1726 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1727 FunctionAnalysisManager &FAM,
1728 CGSCCAnalysisManager &CGAM,
1729 ModuleAnalysisManager &MAM) {
1730 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1731 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1732 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1733 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1734 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1735 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1736 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1739 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1740 ArrayRef<PipelineElement> Pipeline,
1741 bool VerifyEachPass,
1742 bool DebugLogging) {
1743 for (const auto &Element : Pipeline) {
1744 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1747 MPM.addPass(VerifierPass());
1752 // Primary pass pipeline description parsing routine for a \c ModulePassManager
1753 // FIXME: Should this routine accept a TargetMachine or require the caller to
1754 // pre-populate the analysis managers with target-specific stuff?
1755 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1756 StringRef PipelineText, bool VerifyEachPass,
1757 bool DebugLogging) {
1758 auto Pipeline = parsePipelineText(PipelineText);
1759 if (!Pipeline || Pipeline->empty())
1762 // If the first name isn't at the module layer, wrap the pipeline up
1764 StringRef FirstName = Pipeline->front().Name;
1766 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1767 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1768 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1769 } else if (isFunctionPassName(FirstName,
1770 FunctionPipelineParsingCallbacks)) {
1771 Pipeline = {{"function", std::move(*Pipeline)}};
1772 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
1773 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1775 for (auto &C : TopLevelPipelineParsingCallbacks)
1776 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
1779 // Unknown pass name!
1784 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1787 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1788 bool PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1789 StringRef PipelineText, bool VerifyEachPass,
1790 bool DebugLogging) {
1791 auto Pipeline = parsePipelineText(PipelineText);
1792 if (!Pipeline || Pipeline->empty())
1795 StringRef FirstName = Pipeline->front().Name;
1796 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1799 return parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1802 // Primary pass pipeline description parsing routine for a \c
1803 // FunctionPassManager
1804 bool PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1805 StringRef PipelineText, bool VerifyEachPass,
1806 bool DebugLogging) {
1807 auto Pipeline = parsePipelineText(PipelineText);
1808 if (!Pipeline || Pipeline->empty())
1811 StringRef FirstName = Pipeline->front().Name;
1812 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1815 return parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
1819 // Primary pass pipeline description parsing routine for a \c LoopPassManager
1820 bool PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1821 StringRef PipelineText, bool VerifyEachPass,
1822 bool DebugLogging) {
1823 auto Pipeline = parsePipelineText(PipelineText);
1824 if (!Pipeline || Pipeline->empty())
1827 return parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging);
1830 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1831 // If the pipeline just consists of the word 'default' just replace the AA
1832 // manager with our default one.
1833 if (PipelineText == "default") {
1834 AA = buildDefaultAAPipeline();
1838 while (!PipelineText.empty()) {
1840 std::tie(Name, PipelineText) = PipelineText.split(',');
1841 if (!parseAAPassName(AA, Name))