1 //===- Parsing, selection, and construction of pass pipelines -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file provides the implementation of the PassBuilder based on our
11 /// static pass registry as well as related functionality. It also provides
12 /// helpers to aid in analyzing, debugging, and testing passes and pass
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Passes/PassBuilder.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/BlockFrequencyInfo.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/CFGPrinter.h"
26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
28 #include "llvm/Analysis/CGSCCPassManager.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/DDG.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/LoopCacheAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
42 #include "llvm/Analysis/MemorySSA.h"
43 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/PhiValues.h"
46 #include "llvm/Analysis/PostDominators.h"
47 #include "llvm/Analysis/ProfileSummaryInfo.h"
48 #include "llvm/Analysis/RegionInfo.h"
49 #include "llvm/Analysis/ScalarEvolution.h"
50 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
51 #include "llvm/Analysis/ScopedNoAliasAA.h"
52 #include "llvm/Analysis/StackSafetyAnalysis.h"
53 #include "llvm/Analysis/TargetLibraryInfo.h"
54 #include "llvm/Analysis/TargetTransformInfo.h"
55 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
56 #include "llvm/CodeGen/MachineModuleInfo.h"
57 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
58 #include "llvm/CodeGen/UnreachableBlockElim.h"
59 #include "llvm/IR/Dominators.h"
60 #include "llvm/IR/IRPrintingPasses.h"
61 #include "llvm/IR/PassManager.h"
62 #include "llvm/IR/SafepointIRVerifier.h"
63 #include "llvm/IR/Verifier.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/FormatVariadic.h"
66 #include "llvm/Support/Regex.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
69 #include "llvm/Transforms/IPO/AlwaysInliner.h"
70 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
71 #include "llvm/Transforms/IPO/Attributor.h"
72 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
73 #include "llvm/Transforms/IPO/ConstantMerge.h"
74 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
75 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
76 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
77 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
78 #include "llvm/Transforms/IPO/FunctionAttrs.h"
79 #include "llvm/Transforms/IPO/FunctionImport.h"
80 #include "llvm/Transforms/IPO/GlobalDCE.h"
81 #include "llvm/Transforms/IPO/GlobalOpt.h"
82 #include "llvm/Transforms/IPO/GlobalSplit.h"
83 #include "llvm/Transforms/IPO/HotColdSplitting.h"
84 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
85 #include "llvm/Transforms/IPO/Inliner.h"
86 #include "llvm/Transforms/IPO/Internalize.h"
87 #include "llvm/Transforms/IPO/LowerTypeTests.h"
88 #include "llvm/Transforms/IPO/PartialInlining.h"
89 #include "llvm/Transforms/IPO/SCCP.h"
90 #include "llvm/Transforms/IPO/SampleProfile.h"
91 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
92 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
93 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
94 #include "llvm/Transforms/InstCombine/InstCombine.h"
95 #include "llvm/Transforms/Instrumentation.h"
96 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
97 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
98 #include "llvm/Transforms/Instrumentation/CGProfile.h"
99 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
100 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
101 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
102 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
103 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
104 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
105 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
106 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
107 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
108 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
109 #include "llvm/Transforms/Scalar/ADCE.h"
110 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
111 #include "llvm/Transforms/Scalar/BDCE.h"
112 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
113 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
114 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
115 #include "llvm/Transforms/Scalar/DCE.h"
116 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
117 #include "llvm/Transforms/Scalar/DivRemPairs.h"
118 #include "llvm/Transforms/Scalar/EarlyCSE.h"
119 #include "llvm/Transforms/Scalar/Float2Int.h"
120 #include "llvm/Transforms/Scalar/GVN.h"
121 #include "llvm/Transforms/Scalar/GuardWidening.h"
122 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
123 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
124 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
125 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
126 #include "llvm/Transforms/Scalar/JumpThreading.h"
127 #include "llvm/Transforms/Scalar/LICM.h"
128 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
129 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
130 #include "llvm/Transforms/Scalar/LoopDeletion.h"
131 #include "llvm/Transforms/Scalar/LoopDistribute.h"
132 #include "llvm/Transforms/Scalar/LoopFuse.h"
133 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
134 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
135 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
136 #include "llvm/Transforms/Scalar/LoopPassManager.h"
137 #include "llvm/Transforms/Scalar/LoopPredication.h"
138 #include "llvm/Transforms/Scalar/LoopRotation.h"
139 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
140 #include "llvm/Transforms/Scalar/LoopSink.h"
141 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
142 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
143 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
144 #include "llvm/Transforms/Scalar/LowerAtomic.h"
145 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
146 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
147 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
148 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
149 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
150 #include "llvm/Transforms/Scalar/MergeICmps.h"
151 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
152 #include "llvm/Transforms/Scalar/NaryReassociate.h"
153 #include "llvm/Transforms/Scalar/NewGVN.h"
154 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
155 #include "llvm/Transforms/Scalar/Reassociate.h"
156 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
157 #include "llvm/Transforms/Scalar/SCCP.h"
158 #include "llvm/Transforms/Scalar/SROA.h"
159 #include "llvm/Transforms/Scalar/Scalarizer.h"
160 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
161 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
162 #include "llvm/Transforms/Scalar/Sink.h"
163 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
164 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
165 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
166 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
167 #include "llvm/Transforms/Utils/AddDiscriminators.h"
168 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
169 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
170 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
171 #include "llvm/Transforms/Utils/LCSSA.h"
172 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
173 #include "llvm/Transforms/Utils/LoopSimplify.h"
174 #include "llvm/Transforms/Utils/LowerInvoke.h"
175 #include "llvm/Transforms/Utils/Mem2Reg.h"
176 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
177 #include "llvm/Transforms/Utils/SymbolRewriter.h"
178 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
179 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
180 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
182 using namespace llvm
;
184 static cl::opt
<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
185 cl::ReallyHidden
, cl::init(4));
187 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
188 cl::Hidden
, cl::ZeroOrMore
,
189 cl::desc("Run Partial inlinining pass"));
192 RunNewGVN("enable-npm-newgvn", cl::init(false),
193 cl::Hidden
, cl::ZeroOrMore
,
194 cl::desc("Run NewGVN instead of GVN"));
196 static cl::opt
<bool> EnableGVNHoist(
197 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden
,
198 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
200 static cl::opt
<bool> EnableGVNSink(
201 "enable-npm-gvn-sink", cl::init(false), cl::Hidden
,
202 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
204 static cl::opt
<bool> EnableUnrollAndJam(
205 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden
,
206 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
208 static cl::opt
<bool> EnableSyntheticCounts(
209 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden
, cl::ZeroOrMore
,
210 cl::desc("Run synthetic function entry count generation "
213 static const Regex
DefaultAliasRegex(
214 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
216 // This option is used in simplifying testing SampleFDO optimizations for
219 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden
,
220 cl::desc("Enable control height reduction optimization (CHR)"));
222 PipelineTuningOptions::PipelineTuningOptions() {
223 LoopInterleaving
= EnableLoopInterleaving
;
224 LoopVectorization
= EnableLoopVectorization
;
225 SLPVectorization
= RunSLPVectorization
;
226 LoopUnrolling
= true;
227 ForgetAllSCEVInLoopUnroll
= ForgetSCEVInLoopUnroll
;
228 LicmMssaOptCap
= SetLicmMssaOptCap
;
229 LicmMssaNoAccForPromotionCap
= SetLicmMssaNoAccForPromotionCap
;
232 extern cl::opt
<bool> EnableHotColdSplit
;
233 extern cl::opt
<bool> EnableOrderFileInstrumentation
;
235 extern cl::opt
<bool> FlattenedProfileUsed
;
237 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level
) {
239 case PassBuilder::O0
:
240 case PassBuilder::O1
:
241 case PassBuilder::O2
:
242 case PassBuilder::O3
:
245 case PassBuilder::Os
:
246 case PassBuilder::Oz
:
249 llvm_unreachable("Invalid optimization level!");
254 /// No-op module pass which does nothing.
255 struct NoOpModulePass
{
256 PreservedAnalyses
run(Module
&M
, ModuleAnalysisManager
&) {
257 return PreservedAnalyses::all();
259 static StringRef
name() { return "NoOpModulePass"; }
262 /// No-op module analysis.
263 class NoOpModuleAnalysis
: public AnalysisInfoMixin
<NoOpModuleAnalysis
> {
264 friend AnalysisInfoMixin
<NoOpModuleAnalysis
>;
265 static AnalysisKey Key
;
269 Result
run(Module
&, ModuleAnalysisManager
&) { return Result(); }
270 static StringRef
name() { return "NoOpModuleAnalysis"; }
273 /// No-op CGSCC pass which does nothing.
274 struct NoOpCGSCCPass
{
275 PreservedAnalyses
run(LazyCallGraph::SCC
&C
, CGSCCAnalysisManager
&,
276 LazyCallGraph
&, CGSCCUpdateResult
&UR
) {
277 return PreservedAnalyses::all();
279 static StringRef
name() { return "NoOpCGSCCPass"; }
282 /// No-op CGSCC analysis.
283 class NoOpCGSCCAnalysis
: public AnalysisInfoMixin
<NoOpCGSCCAnalysis
> {
284 friend AnalysisInfoMixin
<NoOpCGSCCAnalysis
>;
285 static AnalysisKey Key
;
289 Result
run(LazyCallGraph::SCC
&, CGSCCAnalysisManager
&, LazyCallGraph
&G
) {
292 static StringRef
name() { return "NoOpCGSCCAnalysis"; }
295 /// No-op function pass which does nothing.
296 struct NoOpFunctionPass
{
297 PreservedAnalyses
run(Function
&F
, FunctionAnalysisManager
&) {
298 return PreservedAnalyses::all();
300 static StringRef
name() { return "NoOpFunctionPass"; }
303 /// No-op function analysis.
304 class NoOpFunctionAnalysis
: public AnalysisInfoMixin
<NoOpFunctionAnalysis
> {
305 friend AnalysisInfoMixin
<NoOpFunctionAnalysis
>;
306 static AnalysisKey Key
;
310 Result
run(Function
&, FunctionAnalysisManager
&) { return Result(); }
311 static StringRef
name() { return "NoOpFunctionAnalysis"; }
314 /// No-op loop pass which does nothing.
315 struct NoOpLoopPass
{
316 PreservedAnalyses
run(Loop
&L
, LoopAnalysisManager
&,
317 LoopStandardAnalysisResults
&, LPMUpdater
&) {
318 return PreservedAnalyses::all();
320 static StringRef
name() { return "NoOpLoopPass"; }
323 /// No-op loop analysis.
324 class NoOpLoopAnalysis
: public AnalysisInfoMixin
<NoOpLoopAnalysis
> {
325 friend AnalysisInfoMixin
<NoOpLoopAnalysis
>;
326 static AnalysisKey Key
;
330 Result
run(Loop
&, LoopAnalysisManager
&, LoopStandardAnalysisResults
&) {
333 static StringRef
name() { return "NoOpLoopAnalysis"; }
336 AnalysisKey
NoOpModuleAnalysis::Key
;
337 AnalysisKey
NoOpCGSCCAnalysis::Key
;
338 AnalysisKey
NoOpFunctionAnalysis::Key
;
339 AnalysisKey
NoOpLoopAnalysis::Key
;
341 } // End anonymous namespace.
343 void PassBuilder::invokePeepholeEPCallbacks(
344 FunctionPassManager
&FPM
, PassBuilder::OptimizationLevel Level
) {
345 for (auto &C
: PeepholeEPCallbacks
)
349 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager
&MAM
) {
350 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
351 MAM.registerPass([&] { return CREATE_PASS; });
352 #include "PassRegistry.def"
354 for (auto &C
: ModuleAnalysisRegistrationCallbacks
)
358 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager
&CGAM
) {
359 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
360 CGAM.registerPass([&] { return CREATE_PASS; });
361 #include "PassRegistry.def"
363 for (auto &C
: CGSCCAnalysisRegistrationCallbacks
)
367 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager
&FAM
) {
368 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
369 FAM.registerPass([&] { return CREATE_PASS; });
370 #include "PassRegistry.def"
372 for (auto &C
: FunctionAnalysisRegistrationCallbacks
)
376 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager
&LAM
) {
377 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
378 LAM.registerPass([&] { return CREATE_PASS; });
379 #include "PassRegistry.def"
381 for (auto &C
: LoopAnalysisRegistrationCallbacks
)
386 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level
,
389 assert(Level
!= O0
&& "Must request optimizations!");
390 FunctionPassManager
FPM(DebugLogging
);
392 // Form SSA out of local memory accesses after breaking apart aggregates into
396 // Catch trivial redundancies
397 FPM
.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
399 // Hoisting of scalars and load expressions.
401 FPM
.addPass(GVNHoistPass());
403 // Global value numbering based sinking.
405 FPM
.addPass(GVNSinkPass());
406 FPM
.addPass(SimplifyCFGPass());
409 // Speculative execution if the target has divergent branches; otherwise nop.
410 FPM
.addPass(SpeculativeExecutionPass());
412 // Optimize based on known information about branches, and cleanup afterward.
413 FPM
.addPass(JumpThreadingPass());
414 FPM
.addPass(CorrelatedValuePropagationPass());
415 FPM
.addPass(SimplifyCFGPass());
417 FPM
.addPass(AggressiveInstCombinePass());
418 FPM
.addPass(InstCombinePass());
420 if (!isOptimizingForSize(Level
))
421 FPM
.addPass(LibCallsShrinkWrapPass());
423 invokePeepholeEPCallbacks(FPM
, Level
);
425 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
426 // using the size value profile. Don't perform this when optimizing for size.
427 if (PGOOpt
&& PGOOpt
->Action
== PGOOptions::IRUse
&&
428 !isOptimizingForSize(Level
))
429 FPM
.addPass(PGOMemOPSizeOpt());
431 FPM
.addPass(TailCallElimPass());
432 FPM
.addPass(SimplifyCFGPass());
434 // Form canonically associated expression trees, and simplify the trees using
435 // basic mathematical properties. For example, this will form (nearly)
436 // minimal multiplication trees.
437 FPM
.addPass(ReassociatePass());
439 // Add the primary loop simplification pipeline.
440 // FIXME: Currently this is split into two loop pass pipelines because we run
441 // some function passes in between them. These can and should be removed
442 // and/or replaced by scheduling the loop pass equivalents in the correct
443 // positions. But those equivalent passes aren't powerful enough yet.
444 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
445 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
446 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
447 // `LoopInstSimplify`.
448 LoopPassManager
LPM1(DebugLogging
), LPM2(DebugLogging
);
450 // Simplify the loop body. We do this initially to clean up after other loop
451 // passes run, either when iterating on a loop or on inner loops with
452 // implications on the outer loop.
453 LPM1
.addPass(LoopInstSimplifyPass());
454 LPM1
.addPass(LoopSimplifyCFGPass());
456 // Rotate Loop - disable header duplication at -Oz
457 LPM1
.addPass(LoopRotatePass(Level
!= Oz
));
458 LPM1
.addPass(LICMPass(PTO
.LicmMssaOptCap
, PTO
.LicmMssaNoAccForPromotionCap
));
459 LPM1
.addPass(SimpleLoopUnswitchPass());
460 LPM2
.addPass(IndVarSimplifyPass());
461 LPM2
.addPass(LoopIdiomRecognizePass());
463 for (auto &C
: LateLoopOptimizationsEPCallbacks
)
466 LPM2
.addPass(LoopDeletionPass());
467 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
468 // because it changes IR to makes profile annotation in back compile
470 if ((Phase
!= ThinLTOPhase::PreLink
|| !PGOOpt
||
471 PGOOpt
->Action
!= PGOOptions::SampleUse
) &&
474 LoopFullUnrollPass(Level
, false, PTO
.ForgetAllSCEVInLoopUnroll
));
476 for (auto &C
: LoopOptimizerEndEPCallbacks
)
479 // We provide the opt remark emitter pass for LICM to use. We only need to do
480 // this once as it is immutable.
481 FPM
.addPass(RequireAnalysisPass
<OptimizationRemarkEmitterAnalysis
, Function
>());
482 FPM
.addPass(createFunctionToLoopPassAdaptor(
483 std::move(LPM1
), EnableMSSALoopDependency
, DebugLogging
));
484 FPM
.addPass(SimplifyCFGPass());
485 FPM
.addPass(InstCombinePass());
486 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
487 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
488 // *All* loop passes must preserve it, in order to be able to use it.
489 FPM
.addPass(createFunctionToLoopPassAdaptor(
490 std::move(LPM2
), /*UseMemorySSA=*/false, DebugLogging
));
492 // Eliminate redundancies.
494 // These passes add substantial compile time so skip them at O1.
495 FPM
.addPass(MergedLoadStoreMotionPass());
497 FPM
.addPass(NewGVNPass());
502 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
503 FPM
.addPass(MemCpyOptPass());
505 // Sparse conditional constant propagation.
506 // FIXME: It isn't clear why we do this *after* loop passes rather than
508 FPM
.addPass(SCCPPass());
510 // Delete dead bit computations (instcombine runs after to fold away the dead
511 // computations, and then ADCE will run later to exploit any new DCE
512 // opportunities that creates).
513 FPM
.addPass(BDCEPass());
515 // Run instcombine after redundancy and dead bit elimination to exploit
516 // opportunities opened up by them.
517 FPM
.addPass(InstCombinePass());
518 invokePeepholeEPCallbacks(FPM
, Level
);
520 // Re-consider control flow based optimizations after redundancy elimination,
522 FPM
.addPass(JumpThreadingPass());
523 FPM
.addPass(CorrelatedValuePropagationPass());
524 FPM
.addPass(DSEPass());
525 FPM
.addPass(createFunctionToLoopPassAdaptor(
526 LICMPass(PTO
.LicmMssaOptCap
, PTO
.LicmMssaNoAccForPromotionCap
),
527 EnableMSSALoopDependency
, DebugLogging
));
529 for (auto &C
: ScalarOptimizerLateEPCallbacks
)
532 // Finally, do an expensive DCE pass to catch all the dead code exposed by
533 // the simplifications and basic cleanup after all the simplifications.
534 FPM
.addPass(ADCEPass());
535 FPM
.addPass(SimplifyCFGPass());
536 FPM
.addPass(InstCombinePass());
537 invokePeepholeEPCallbacks(FPM
, Level
);
539 if (EnableCHR
&& Level
== O3
&& PGOOpt
&&
540 (PGOOpt
->Action
== PGOOptions::IRUse
||
541 PGOOpt
->Action
== PGOOptions::SampleUse
))
542 FPM
.addPass(ControlHeightReductionPass());
547 void PassBuilder::addPGOInstrPasses(ModulePassManager
&MPM
, bool DebugLogging
,
548 PassBuilder::OptimizationLevel Level
,
549 bool RunProfileGen
, bool IsCS
,
550 std::string ProfileFile
,
551 std::string ProfileRemappingFile
) {
552 assert(Level
!= O0
&& "Not expecting O0 here!");
553 // Generally running simplification passes and the inliner with an high
554 // threshold results in smaller executables, but there may be cases where
555 // the size grows, so let's be conservative here and skip this simplification
556 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
558 if (!isOptimizingForSize(Level
) && !IsCS
) {
561 // In the old pass manager, this is a cl::opt. Should still this be one?
562 IP
.DefaultThreshold
= 75;
564 // FIXME: The hint threshold has the same value used by the regular inliner.
565 // This should probably be lowered after performance testing.
566 // FIXME: this comment is cargo culted from the old pass manager, revisit).
567 IP
.HintThreshold
= 325;
569 CGSCCPassManager
CGPipeline(DebugLogging
);
571 CGPipeline
.addPass(InlinerPass(IP
));
573 FunctionPassManager FPM
;
575 FPM
.addPass(EarlyCSEPass()); // Catch trivial redundancies.
576 FPM
.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
577 FPM
.addPass(InstCombinePass()); // Combine silly sequences.
578 invokePeepholeEPCallbacks(FPM
, Level
);
580 CGPipeline
.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM
)));
582 MPM
.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline
)));
584 // Delete anything that is now dead to make sure that we don't instrument
585 // dead code. Instrumentation can end up keeping dead code around and
586 // dramatically increase code size.
587 MPM
.addPass(GlobalDCEPass());
590 if (!RunProfileGen
) {
591 assert(!ProfileFile
.empty() && "Profile use expecting a profile file!");
592 MPM
.addPass(PGOInstrumentationUse(ProfileFile
, ProfileRemappingFile
, IsCS
));
593 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
594 // RequireAnalysisPass for PSI before subsequent non-module passes.
595 MPM
.addPass(RequireAnalysisPass
<ProfileSummaryAnalysis
, Module
>());
599 // Perform PGO instrumentation.
600 MPM
.addPass(PGOInstrumentationGen(IsCS
));
602 FunctionPassManager FPM
;
603 FPM
.addPass(createFunctionToLoopPassAdaptor(
604 LoopRotatePass(), EnableMSSALoopDependency
, DebugLogging
));
605 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(FPM
)));
607 // Add the profile lowering pass.
608 InstrProfOptions Options
;
609 if (!ProfileFile
.empty())
610 Options
.InstrProfileOutput
= ProfileFile
;
611 // Do counter promotion at Level greater than O0.
612 Options
.DoCounterPromotion
= true;
613 Options
.UseBFIInPromotion
= IsCS
;
614 MPM
.addPass(InstrProfiling(Options
, IsCS
));
617 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager
&MPM
,
618 bool DebugLogging
, bool RunProfileGen
,
619 bool IsCS
, std::string ProfileFile
,
620 std::string ProfileRemappingFile
) {
621 if (!RunProfileGen
) {
622 assert(!ProfileFile
.empty() && "Profile use expecting a profile file!");
623 MPM
.addPass(PGOInstrumentationUse(ProfileFile
, ProfileRemappingFile
, IsCS
));
624 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
625 // RequireAnalysisPass for PSI before subsequent non-module passes.
626 MPM
.addPass(RequireAnalysisPass
<ProfileSummaryAnalysis
, Module
>());
630 // Perform PGO instrumentation.
631 MPM
.addPass(PGOInstrumentationGen(IsCS
));
632 // Add the profile lowering pass.
633 InstrProfOptions Options
;
634 if (!ProfileFile
.empty())
635 Options
.InstrProfileOutput
= ProfileFile
;
636 // Do not do counter promotion at O0.
637 Options
.DoCounterPromotion
= false;
638 Options
.UseBFIInPromotion
= IsCS
;
639 MPM
.addPass(InstrProfiling(Options
, IsCS
));
643 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level
) {
644 auto O3
= PassBuilder::O3
;
645 unsigned OptLevel
= Level
> O3
? 2 : Level
;
646 unsigned SizeLevel
= Level
> O3
? Level
- O3
: 0;
647 return getInlineParams(OptLevel
, SizeLevel
);
651 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level
,
654 ModulePassManager
MPM(DebugLogging
);
656 bool HasSampleProfile
= PGOOpt
&& (PGOOpt
->Action
== PGOOptions::SampleUse
);
658 // In ThinLTO mode, when flattened profile is used, all the available
659 // profile information will be annotated in PreLink phase so there is
660 // no need to load the profile again in PostLink.
661 bool LoadSampleProfile
=
663 !(FlattenedProfileUsed
&& Phase
== ThinLTOPhase::PostLink
);
665 // During the ThinLTO backend phase we perform early indirect call promotion
666 // here, before globalopt. Otherwise imported available_externally functions
667 // look unreferenced and are removed. If we are going to load the sample
668 // profile then defer until later.
669 // TODO: See if we can move later and consolidate with the location where
670 // we perform ICP when we are loading a sample profile.
671 // TODO: We pass HasSampleProfile (whether there was a sample profile file
672 // passed to the compile) to the SamplePGO flag of ICP. This is used to
673 // determine whether the new direct calls are annotated with prof metadata.
674 // Ideally this should be determined from whether the IR is annotated with
675 // sample profile, and not whether the a sample profile was provided on the
676 // command line. E.g. for flattened profiles where we will not be reloading
677 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
678 // provide the sample profile file.
679 if (Phase
== ThinLTOPhase::PostLink
&& !LoadSampleProfile
)
680 MPM
.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile
));
682 // Do basic inference of function attributes from known properties of system
683 // libraries and other oracles.
684 MPM
.addPass(InferFunctionAttrsPass());
686 // Create an early function pass manager to cleanup the output of the
688 FunctionPassManager
EarlyFPM(DebugLogging
);
689 EarlyFPM
.addPass(SimplifyCFGPass());
690 EarlyFPM
.addPass(SROA());
691 EarlyFPM
.addPass(EarlyCSEPass());
692 EarlyFPM
.addPass(LowerExpectIntrinsicPass());
694 EarlyFPM
.addPass(CallSiteSplittingPass());
696 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
697 // to convert bitcast to direct calls so that they can be inlined during the
698 // profile annotation prepration step.
699 // More details about SamplePGO design can be found in:
700 // https://research.google.com/pubs/pub45290.html
701 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
702 if (LoadSampleProfile
)
703 EarlyFPM
.addPass(InstCombinePass());
704 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM
)));
706 if (LoadSampleProfile
) {
707 // Annotate sample profile right after early FPM to ensure freshness of
709 MPM
.addPass(SampleProfileLoaderPass(PGOOpt
->ProfileFile
,
710 PGOOpt
->ProfileRemappingFile
,
711 Phase
== ThinLTOPhase::PreLink
));
712 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
713 // RequireAnalysisPass for PSI before subsequent non-module passes.
714 MPM
.addPass(RequireAnalysisPass
<ProfileSummaryAnalysis
, Module
>());
715 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
716 // for the profile annotation to be accurate in the ThinLTO backend.
717 if (Phase
!= ThinLTOPhase::PreLink
)
718 // We perform early indirect call promotion here, before globalopt.
719 // This is important for the ThinLTO backend phase because otherwise
720 // imported available_externally functions look unreferenced and are
722 MPM
.addPass(PGOIndirectCallPromotion(Phase
== ThinLTOPhase::PostLink
,
723 true /* SamplePGO */));
726 // Interprocedural constant propagation now that basic cleanup has occurred
727 // and prior to optimizing globals.
728 // FIXME: This position in the pipeline hasn't been carefully considered in
729 // years, it should be re-analyzed.
730 MPM
.addPass(IPSCCPPass());
732 // Attach metadata to indirect call sites indicating the set of functions
733 // they may target at run-time. This should follow IPSCCP.
734 MPM
.addPass(CalledValuePropagationPass());
736 // Optimize globals to try and fold them into constants.
737 MPM
.addPass(GlobalOptPass());
739 // Promote any localized globals to SSA registers.
740 // FIXME: Should this instead by a run of SROA?
741 // FIXME: We should probably run instcombine and simplify-cfg afterward to
742 // delete control flows that are dead once globals have been folded to
744 MPM
.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
746 // Remove any dead arguments exposed by cleanups and constand folding
748 MPM
.addPass(DeadArgumentEliminationPass());
750 // Create a small function pass pipeline to cleanup after all the global
752 FunctionPassManager
GlobalCleanupPM(DebugLogging
);
753 GlobalCleanupPM
.addPass(InstCombinePass());
754 invokePeepholeEPCallbacks(GlobalCleanupPM
, Level
);
756 GlobalCleanupPM
.addPass(SimplifyCFGPass());
757 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM
)));
759 // Add all the requested passes for instrumentation PGO, if requested.
760 if (PGOOpt
&& Phase
!= ThinLTOPhase::PostLink
&&
761 (PGOOpt
->Action
== PGOOptions::IRInstr
||
762 PGOOpt
->Action
== PGOOptions::IRUse
)) {
763 addPGOInstrPasses(MPM
, DebugLogging
, Level
,
764 /* RunProfileGen */ PGOOpt
->Action
== PGOOptions::IRInstr
,
765 /* IsCS */ false, PGOOpt
->ProfileFile
,
766 PGOOpt
->ProfileRemappingFile
);
767 MPM
.addPass(PGOIndirectCallPromotion(false, false));
769 if (PGOOpt
&& Phase
!= ThinLTOPhase::PostLink
&&
770 PGOOpt
->CSAction
== PGOOptions::CSIRInstr
)
771 MPM
.addPass(PGOInstrumentationGenCreateVar(PGOOpt
->CSProfileGenFile
));
773 // Synthesize function entry counts for non-PGO compilation.
774 if (EnableSyntheticCounts
&& !PGOOpt
)
775 MPM
.addPass(SyntheticCountsPropagation());
777 // Require the GlobalsAA analysis for the module so we can query it within
778 // the CGSCC pipeline.
779 MPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
781 // Require the ProfileSummaryAnalysis for the module so we can query it within
783 MPM
.addPass(RequireAnalysisPass
<ProfileSummaryAnalysis
, Module
>());
785 // Now begin the main postorder CGSCC pipeline.
786 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
787 // manager and trying to emulate its precise behavior. Much of this doesn't
788 // make a lot of sense and we should revisit the core CGSCC structure.
789 CGSCCPassManager
MainCGPipeline(DebugLogging
);
791 // Note: historically, the PruneEH pass was run first to deduce nounwind and
792 // generally clean up exception handling overhead. It isn't clear this is
793 // valuable as the inliner doesn't currently care whether it is inlining an
796 // Run the inliner first. The theory is that we are walking bottom-up and so
797 // the callees have already been fully optimized, and we want to inline them
798 // into the callers so that our optimizations can reflect that.
799 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
800 // because it makes profile annotation in the backend inaccurate.
801 InlineParams IP
= getInlineParamsFromOptLevel(Level
);
802 if (Phase
== ThinLTOPhase::PreLink
&& PGOOpt
&&
803 PGOOpt
->Action
== PGOOptions::SampleUse
)
804 IP
.HotCallSiteThreshold
= 0;
805 MainCGPipeline
.addPass(InlinerPass(IP
));
807 // Now deduce any function attributes based in the current code.
808 MainCGPipeline
.addPass(PostOrderFunctionAttrsPass());
810 // When at O3 add argument promotion to the pass pipeline.
811 // FIXME: It isn't at all clear why this should be limited to O3.
813 MainCGPipeline
.addPass(ArgumentPromotionPass());
815 // Lastly, add the core function simplification pipeline nested inside the
817 MainCGPipeline
.addPass(createCGSCCToFunctionPassAdaptor(
818 buildFunctionSimplificationPipeline(Level
, Phase
, DebugLogging
)));
820 for (auto &C
: CGSCCOptimizerLateEPCallbacks
)
821 C(MainCGPipeline
, Level
);
823 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
824 // to detect when we devirtualize indirect calls and iterate the SCC passes
825 // in that case to try and catch knock-on inlining or function attrs
826 // opportunities. Then we add it to the module pipeline by walking the SCCs
827 // in postorder (or bottom-up).
829 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
830 std::move(MainCGPipeline
), MaxDevirtIterations
)));
835 ModulePassManager
PassBuilder::buildModuleOptimizationPipeline(
836 OptimizationLevel Level
, bool DebugLogging
, bool LTOPreLink
) {
837 ModulePassManager
MPM(DebugLogging
);
839 // Optimize globals now that the module is fully simplified.
840 MPM
.addPass(GlobalOptPass());
841 MPM
.addPass(GlobalDCEPass());
843 // Run partial inlining pass to partially inline functions that have
845 if (RunPartialInlining
)
846 MPM
.addPass(PartialInlinerPass());
848 // Remove avail extern fns and globals definitions since we aren't compiling
849 // an object file for later LTO. For LTO we want to preserve these so they
850 // are eligible for inlining at link-time. Note if they are unreferenced they
851 // will be removed by GlobalDCE later, so this only impacts referenced
852 // available externally globals. Eventually they will be suppressed during
853 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
854 // may make globals referenced by available external functions dead and saves
855 // running remaining passes on the eliminated functions. These should be
856 // preserved during prelinking for link-time inlining decisions.
858 MPM
.addPass(EliminateAvailableExternallyPass());
860 if (EnableOrderFileInstrumentation
)
861 MPM
.addPass(InstrOrderFilePass());
863 // Do RPO function attribute inference across the module to forward-propagate
864 // attributes where applicable.
865 // FIXME: Is this really an optimization rather than a canonicalization?
866 MPM
.addPass(ReversePostOrderFunctionAttrsPass());
868 // Do a post inline PGO instrumentation and use pass. This is a context
869 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
870 // cross-module inline has not been done yet. The context sensitive
871 // instrumentation is after all the inlines are done.
872 if (!LTOPreLink
&& PGOOpt
) {
873 if (PGOOpt
->CSAction
== PGOOptions::CSIRInstr
)
874 addPGOInstrPasses(MPM
, DebugLogging
, Level
, /* RunProfileGen */ true,
875 /* IsCS */ true, PGOOpt
->CSProfileGenFile
,
876 PGOOpt
->ProfileRemappingFile
);
877 else if (PGOOpt
->CSAction
== PGOOptions::CSIRUse
)
878 addPGOInstrPasses(MPM
, DebugLogging
, Level
, /* RunProfileGen */ false,
879 /* IsCS */ true, PGOOpt
->ProfileFile
,
880 PGOOpt
->ProfileRemappingFile
);
883 // Re-require GloblasAA here prior to function passes. This is particularly
884 // useful as the above will have inlined, DCE'ed, and function-attr
885 // propagated everything. We should at this point have a reasonably minimal
886 // and richly annotated call graph. By computing aliasing and mod/ref
887 // information for all local globals here, the late loop passes and notably
888 // the vectorizer will be able to use them to help recognize vectorizable
889 // memory operations.
890 MPM
.addPass(RequireAnalysisPass
<GlobalsAA
, Module
>());
892 FunctionPassManager
OptimizePM(DebugLogging
);
893 OptimizePM
.addPass(Float2IntPass());
894 // FIXME: We need to run some loop optimizations to re-rotate loops after
895 // simplify-cfg and others undo their rotation.
897 // Optimize the loop execution. These passes operate on entire loop nests
898 // rather than on each loop in an inside-out manner, and so they are actually
901 for (auto &C
: VectorizerStartEPCallbacks
)
902 C(OptimizePM
, Level
);
904 // First rotate loops that may have been un-rotated by prior passes.
905 OptimizePM
.addPass(createFunctionToLoopPassAdaptor(
906 LoopRotatePass(), EnableMSSALoopDependency
, DebugLogging
));
908 // Distribute loops to allow partial vectorization. I.e. isolate dependences
909 // into separate loop that would otherwise inhibit vectorization. This is
910 // currently only performed for loops marked with the metadata
911 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
912 OptimizePM
.addPass(LoopDistributePass());
914 // Now run the core loop vectorizer.
915 OptimizePM
.addPass(LoopVectorizePass(
916 LoopVectorizeOptions(!PTO
.LoopInterleaving
, !PTO
.LoopVectorization
)));
918 // Eliminate loads by forwarding stores from the previous iteration to loads
919 // of the current iteration.
920 OptimizePM
.addPass(LoopLoadEliminationPass());
922 // Cleanup after the loop optimization passes.
923 OptimizePM
.addPass(InstCombinePass());
925 // Now that we've formed fast to execute loop structures, we do further
926 // optimizations. These are run afterward as they might block doing complex
927 // analyses and transforms such as what are needed for loop vectorization.
929 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
930 // GVN, loop transforms, and others have already run, so it's now better to
931 // convert to more optimized IR using more aggressive simplify CFG options.
932 // The extra sinking transform can create larger basic blocks, so do this
933 // before SLP vectorization.
934 OptimizePM
.addPass(SimplifyCFGPass(SimplifyCFGOptions().
935 forwardSwitchCondToPhi(true).
936 convertSwitchToLookupTable(true).
937 needCanonicalLoops(false).
938 sinkCommonInsts(true)));
940 // Optimize parallel scalar instruction chains into SIMD instructions.
941 if (PTO
.SLPVectorization
)
942 OptimizePM
.addPass(SLPVectorizerPass());
944 OptimizePM
.addPass(InstCombinePass());
946 // Unroll small loops to hide loop backedge latency and saturate any parallel
947 // execution resources of an out-of-order processor. We also then need to
948 // clean up redundancies and loop invariant code.
949 // FIXME: It would be really good to use a loop-integrated instruction
950 // combiner for cleanup here so that the unrolling and LICM can be pipelined
951 // across the loop nests.
952 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
953 if (EnableUnrollAndJam
) {
955 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level
)));
957 if (PTO
.LoopUnrolling
)
958 OptimizePM
.addPass(LoopUnrollPass(
959 LoopUnrollOptions(Level
, false, PTO
.ForgetAllSCEVInLoopUnroll
)));
960 OptimizePM
.addPass(WarnMissedTransformationsPass());
961 OptimizePM
.addPass(InstCombinePass());
962 OptimizePM
.addPass(RequireAnalysisPass
<OptimizationRemarkEmitterAnalysis
, Function
>());
963 OptimizePM
.addPass(createFunctionToLoopPassAdaptor(
964 LICMPass(PTO
.LicmMssaOptCap
, PTO
.LicmMssaNoAccForPromotionCap
),
965 EnableMSSALoopDependency
, DebugLogging
));
967 // Now that we've vectorized and unrolled loops, we may have more refined
968 // alignment information, try to re-derive it here.
969 OptimizePM
.addPass(AlignmentFromAssumptionsPass());
971 // Split out cold code. Splitting is done late to avoid hiding context from
972 // other optimizations and inadvertently regressing performance. The tradeoff
973 // is that this has a higher code size cost than splitting early.
974 if (EnableHotColdSplit
&& !LTOPreLink
)
975 MPM
.addPass(HotColdSplittingPass());
977 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
978 // canonicalization pass that enables other optimizations. As a result,
979 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
981 OptimizePM
.addPass(LoopSinkPass());
983 // And finally clean up LCSSA form before generating code.
984 OptimizePM
.addPass(InstSimplifyPass());
986 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
987 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
988 // flattening of blocks.
989 OptimizePM
.addPass(DivRemPairsPass());
991 // LoopSink (and other loop passes since the last simplifyCFG) might have
992 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
993 OptimizePM
.addPass(SimplifyCFGPass());
995 // Optimize PHIs by speculating around them when profitable. Note that this
996 // pass needs to be run after any PRE or similar pass as it is essentially
997 // inserting redundancies into the program. This even includes SimplifyCFG.
998 OptimizePM
.addPass(SpeculateAroundPHIsPass());
1000 for (auto &C
: OptimizerLastEPCallbacks
)
1001 C(OptimizePM
, Level
);
1003 // Add the core optimizing pipeline.
1004 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM
)));
1006 MPM
.addPass(CGProfilePass());
1008 // Now we need to do some global optimization transforms.
1009 // FIXME: It would seem like these should come first in the optimization
1010 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1012 MPM
.addPass(GlobalDCEPass());
1013 MPM
.addPass(ConstantMergePass());
1019 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level
,
1020 bool DebugLogging
, bool LTOPreLink
) {
1021 assert(Level
!= O0
&& "Must request optimizations for the default pipeline!");
1023 ModulePassManager
MPM(DebugLogging
);
1025 // Force any function attributes we want the rest of the pipeline to observe.
1026 MPM
.addPass(ForceFunctionAttrsPass());
1028 // Apply module pipeline start EP callback.
1029 for (auto &C
: PipelineStartEPCallbacks
)
1032 if (PGOOpt
&& PGOOpt
->SamplePGOSupport
)
1033 MPM
.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1035 // Add the core simplification pipeline.
1036 MPM
.addPass(buildModuleSimplificationPipeline(Level
, ThinLTOPhase::None
,
1039 // Now add the optimization pipeline.
1040 MPM
.addPass(buildModuleOptimizationPipeline(Level
, DebugLogging
, LTOPreLink
));
1046 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level
,
1047 bool DebugLogging
) {
1048 assert(Level
!= O0
&& "Must request optimizations for the default pipeline!");
1050 ModulePassManager
MPM(DebugLogging
);
1052 // Force any function attributes we want the rest of the pipeline to observe.
1053 MPM
.addPass(ForceFunctionAttrsPass());
1055 if (PGOOpt
&& PGOOpt
->SamplePGOSupport
)
1056 MPM
.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1058 // Apply module pipeline start EP callback.
1059 for (auto &C
: PipelineStartEPCallbacks
)
1062 // If we are planning to perform ThinLTO later, we don't bloat the code with
1063 // unrolling/vectorization/... now. Just simplify the module as much as we
1065 MPM
.addPass(buildModuleSimplificationPipeline(Level
, ThinLTOPhase::PreLink
,
1068 // Run partial inlining pass to partially inline functions that have
1070 // FIXME: It isn't clear whether this is really the right place to run this
1071 // in ThinLTO. Because there is another canonicalization and simplification
1072 // phase that will run after the thin link, running this here ends up with
1073 // less information than will be available later and it may grow functions in
1074 // ways that aren't beneficial.
1075 if (RunPartialInlining
)
1076 MPM
.addPass(PartialInlinerPass());
1078 // Reduce the size of the IR as much as possible.
1079 MPM
.addPass(GlobalOptPass());
1084 ModulePassManager
PassBuilder::buildThinLTODefaultPipeline(
1085 OptimizationLevel Level
, bool DebugLogging
,
1086 const ModuleSummaryIndex
*ImportSummary
) {
1087 ModulePassManager
MPM(DebugLogging
);
1089 if (ImportSummary
) {
1090 // These passes import type identifier resolutions for whole-program
1091 // devirtualization and CFI. They must run early because other passes may
1092 // disturb the specific instruction patterns that these passes look for,
1093 // creating dependencies on resolutions that may not appear in the summary.
1095 // For example, GVN may transform the pattern assume(type.test) appearing in
1096 // two basic blocks into assume(phi(type.test, type.test)), which would
1097 // transform a dependency on a WPD resolution into a dependency on a type
1098 // identifier resolution for CFI.
1100 // Also, WPD has access to more precise information than ICP and can
1101 // devirtualize more effectively, so it should operate on the IR first.
1103 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1104 // metadata and intrinsics.
1105 MPM
.addPass(WholeProgramDevirtPass(nullptr, ImportSummary
));
1106 MPM
.addPass(LowerTypeTestsPass(nullptr, ImportSummary
));
1112 // Force any function attributes we want the rest of the pipeline to observe.
1113 MPM
.addPass(ForceFunctionAttrsPass());
1115 // Add the core simplification pipeline.
1116 MPM
.addPass(buildModuleSimplificationPipeline(Level
, ThinLTOPhase::PostLink
,
1119 // Now add the optimization pipeline.
1120 MPM
.addPass(buildModuleOptimizationPipeline(Level
, DebugLogging
));
1126 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level
,
1127 bool DebugLogging
) {
1128 assert(Level
!= O0
&& "Must request optimizations for the default pipeline!");
1129 // FIXME: We should use a customized pre-link pipeline!
1130 return buildPerModuleDefaultPipeline(Level
, DebugLogging
,
1131 /* LTOPreLink */true);
1135 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level
, bool DebugLogging
,
1136 ModuleSummaryIndex
*ExportSummary
) {
1137 ModulePassManager
MPM(DebugLogging
);
1140 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1141 // metadata and intrinsics.
1142 MPM
.addPass(WholeProgramDevirtPass(ExportSummary
, nullptr));
1143 MPM
.addPass(LowerTypeTestsPass(ExportSummary
, nullptr));
1147 if (PGOOpt
&& PGOOpt
->Action
== PGOOptions::SampleUse
) {
1148 // Load sample profile before running the LTO optimization pipeline.
1149 MPM
.addPass(SampleProfileLoaderPass(PGOOpt
->ProfileFile
,
1150 PGOOpt
->ProfileRemappingFile
,
1151 false /* ThinLTOPhase::PreLink */));
1152 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1153 // RequireAnalysisPass for PSI before subsequent non-module passes.
1154 MPM
.addPass(RequireAnalysisPass
<ProfileSummaryAnalysis
, Module
>());
1157 // Remove unused virtual tables to improve the quality of code generated by
1158 // whole-program devirtualization and bitset lowering.
1159 MPM
.addPass(GlobalDCEPass());
1161 // Force any function attributes we want the rest of the pipeline to observe.
1162 MPM
.addPass(ForceFunctionAttrsPass());
1164 // Do basic inference of function attributes from known properties of system
1165 // libraries and other oracles.
1166 MPM
.addPass(InferFunctionAttrsPass());
1169 FunctionPassManager
EarlyFPM(DebugLogging
);
1170 EarlyFPM
.addPass(CallSiteSplittingPass());
1171 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM
)));
1173 // Indirect call promotion. This should promote all the targets that are
1174 // left by the earlier promotion pass that promotes intra-module targets.
1175 // This two-step promotion is to save the compile time. For LTO, it should
1176 // produce the same result as if we only do promotion here.
1177 MPM
.addPass(PGOIndirectCallPromotion(
1178 true /* InLTO */, PGOOpt
&& PGOOpt
->Action
== PGOOptions::SampleUse
));
1179 // Propagate constants at call sites into the functions they call. This
1180 // opens opportunities for globalopt (and inlining) by substituting function
1181 // pointers passed as arguments to direct uses of functions.
1182 MPM
.addPass(IPSCCPPass());
1184 // Attach metadata to indirect call sites indicating the set of functions
1185 // they may target at run-time. This should follow IPSCCP.
1186 MPM
.addPass(CalledValuePropagationPass());
1189 // Now deduce any function attributes based in the current code.
1190 MPM
.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1191 PostOrderFunctionAttrsPass()));
1193 // Do RPO function attribute inference across the module to forward-propagate
1194 // attributes where applicable.
1195 // FIXME: Is this really an optimization rather than a canonicalization?
1196 MPM
.addPass(ReversePostOrderFunctionAttrsPass());
1198 // Use in-range annotations on GEP indices to split globals where beneficial.
1199 MPM
.addPass(GlobalSplitPass());
1201 // Run whole program optimization of virtual call when the list of callees
1203 MPM
.addPass(WholeProgramDevirtPass(ExportSummary
, nullptr));
1205 // Stop here at -O1.
1207 // The LowerTypeTestsPass needs to run to lower type metadata and the
1208 // type.test intrinsics. The pass does nothing if CFI is disabled.
1209 MPM
.addPass(LowerTypeTestsPass(ExportSummary
, nullptr));
1213 // Optimize globals to try and fold them into constants.
1214 MPM
.addPass(GlobalOptPass());
1216 // Promote any localized globals to SSA registers.
1217 MPM
.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1219 // Linking modules together can lead to duplicate global constant, only
1220 // keep one copy of each constant.
1221 MPM
.addPass(ConstantMergePass());
1223 // Remove unused arguments from functions.
1224 MPM
.addPass(DeadArgumentEliminationPass());
1226 // Reduce the code after globalopt and ipsccp. Both can open up significant
1227 // simplification opportunities, and both can propagate functions through
1228 // function pointers. When this happens, we often have to resolve varargs
1229 // calls, etc, so let instcombine do this.
1230 FunctionPassManager
PeepholeFPM(DebugLogging
);
1232 PeepholeFPM
.addPass(AggressiveInstCombinePass());
1233 PeepholeFPM
.addPass(InstCombinePass());
1234 invokePeepholeEPCallbacks(PeepholeFPM
, Level
);
1236 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM
)));
1238 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1239 // generally clean up exception handling overhead. It isn't clear this is
1240 // valuable as the inliner doesn't currently care whether it is inlining an
1241 // invoke or a call.
1242 // Run the inliner now.
1243 MPM
.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1244 InlinerPass(getInlineParamsFromOptLevel(Level
))));
1246 // Optimize globals again after we ran the inliner.
1247 MPM
.addPass(GlobalOptPass());
1249 // Garbage collect dead functions.
1250 // FIXME: Add ArgumentPromotion pass after once it's ported.
1251 MPM
.addPass(GlobalDCEPass());
1253 FunctionPassManager
FPM(DebugLogging
);
1254 // The IPO Passes may leave cruft around. Clean up after them.
1255 FPM
.addPass(InstCombinePass());
1256 invokePeepholeEPCallbacks(FPM
, Level
);
1258 FPM
.addPass(JumpThreadingPass());
1260 // Do a post inline PGO instrumentation and use pass. This is a context
1261 // sensitive PGO pass.
1263 if (PGOOpt
->CSAction
== PGOOptions::CSIRInstr
)
1264 addPGOInstrPasses(MPM
, DebugLogging
, Level
, /* RunProfileGen */ true,
1265 /* IsCS */ true, PGOOpt
->CSProfileGenFile
,
1266 PGOOpt
->ProfileRemappingFile
);
1267 else if (PGOOpt
->CSAction
== PGOOptions::CSIRUse
)
1268 addPGOInstrPasses(MPM
, DebugLogging
, Level
, /* RunProfileGen */ false,
1269 /* IsCS */ true, PGOOpt
->ProfileFile
,
1270 PGOOpt
->ProfileRemappingFile
);
1274 FPM
.addPass(SROA());
1276 // LTO provides additional opportunities for tailcall elimination due to
1277 // link-time inlining, and visibility of nocapture attribute.
1278 FPM
.addPass(TailCallElimPass());
1280 // Run a few AA driver optimizations here and now to cleanup the code.
1281 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(FPM
)));
1283 MPM
.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1284 PostOrderFunctionAttrsPass()));
1285 // FIXME: here we run IP alias analysis in the legacy PM.
1287 FunctionPassManager MainFPM
;
1289 // FIXME: once we fix LoopPass Manager, add LICM here.
1290 // FIXME: once we provide support for enabling MLSM, add it here.
1292 MainFPM
.addPass(NewGVNPass());
1294 MainFPM
.addPass(GVN());
1296 // Remove dead memcpy()'s.
1297 MainFPM
.addPass(MemCpyOptPass());
1299 // Nuke dead stores.
1300 MainFPM
.addPass(DSEPass());
1302 // FIXME: at this point, we run a bunch of loop passes:
1303 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
1304 // loopVectorize. Enable them once the remaining issue with LPM
1307 MainFPM
.addPass(InstCombinePass());
1308 MainFPM
.addPass(SimplifyCFGPass());
1309 MainFPM
.addPass(SCCPPass());
1310 MainFPM
.addPass(InstCombinePass());
1311 MainFPM
.addPass(BDCEPass());
1313 // FIXME: We may want to run SLPVectorizer here.
1314 // After vectorization, assume intrinsics may tell us more
1315 // about pointer alignments.
1317 MainFPM
.add(AlignmentFromAssumptionsPass());
1320 // FIXME: Conditionally run LoadCombine here, after it's ported
1321 // (in case we still have this pass, given its questionable usefulness).
1323 MainFPM
.addPass(InstCombinePass());
1324 invokePeepholeEPCallbacks(MainFPM
, Level
);
1325 MainFPM
.addPass(JumpThreadingPass());
1326 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM
)));
1328 // Create a function that performs CFI checks for cross-DSO calls with
1329 // targets in the current module.
1330 MPM
.addPass(CrossDSOCFIPass());
1332 // Lower type metadata and the type.test intrinsic. This pass supports
1333 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1334 // to be run at link time if CFI is enabled. This pass does nothing if
1336 MPM
.addPass(LowerTypeTestsPass(ExportSummary
, nullptr));
1338 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1339 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1340 if (EnableHotColdSplit
)
1341 MPM
.addPass(HotColdSplittingPass());
1343 // Add late LTO optimization passes.
1344 // Delete basic blocks, which optimization passes may have killed.
1345 MPM
.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1347 // Drop bodies of available eternally objects to improve GlobalDCE.
1348 MPM
.addPass(EliminateAvailableExternallyPass());
1350 // Now that we have optimized the program, discard unreachable functions.
1351 MPM
.addPass(GlobalDCEPass());
1353 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
1357 AAManager
PassBuilder::buildDefaultAAPipeline() {
1360 // The order in which these are registered determines their priority when
1363 // First we register the basic alias analysis that provides the majority of
1364 // per-function local AA logic. This is a stateless, on-demand local set of
1366 AA
.registerFunctionAnalysis
<BasicAA
>();
1368 // Next we query fast, specialized alias analyses that wrap IR-embedded
1369 // information about aliasing.
1370 AA
.registerFunctionAnalysis
<ScopedNoAliasAA
>();
1371 AA
.registerFunctionAnalysis
<TypeBasedAA
>();
1373 // Add support for querying global aliasing information when available.
1374 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1375 // analysis, all that the `AAManager` can do is query for any *cached*
1376 // results from `GlobalsAA` through a readonly proxy.
1377 AA
.registerModuleAnalysis
<GlobalsAA
>();
1382 static Optional
<int> parseRepeatPassName(StringRef Name
) {
1383 if (!Name
.consume_front("repeat<") || !Name
.consume_back(">"))
1386 if (Name
.getAsInteger(0, Count
) || Count
<= 0)
1391 static Optional
<int> parseDevirtPassName(StringRef Name
) {
1392 if (!Name
.consume_front("devirt<") || !Name
.consume_back(">"))
1395 if (Name
.getAsInteger(0, Count
) || Count
<= 0)
1400 static bool checkParametrizedPassName(StringRef Name
, StringRef PassName
) {
1401 if (!Name
.consume_front(PassName
))
1403 // normal pass name w/o parameters == default parameters
1406 return Name
.startswith("<") && Name
.endswith(">");
1411 /// This performs customized parsing of pass name with parameters.
1413 /// We do not need parametrization of passes in textual pipeline very often,
1414 /// yet on a rare occasion ability to specify parameters right there can be
1417 /// \p Name - parameterized specification of a pass from a textual pipeline
1418 /// is a string in a form of :
1419 /// PassName '<' parameter-list '>'
1421 /// Parameter list is being parsed by the parser callable argument, \p Parser,
1422 /// It takes a string-ref of parameters and returns either StringError or a
1423 /// parameter list in a form of a custom parameters type, all wrapped into
1424 /// Expected<> template class.
1426 template <typename ParametersParseCallableT
>
1427 auto parsePassParameters(ParametersParseCallableT
&&Parser
, StringRef Name
,
1428 StringRef PassName
) -> decltype(Parser(StringRef
{})) {
1429 using ParametersT
= typename
decltype(Parser(StringRef
{}))::value_type
;
1431 StringRef Params
= Name
;
1432 if (!Params
.consume_front(PassName
)) {
1434 "unable to strip pass name from parametrized pass specification");
1437 return ParametersT
{};
1438 if (!Params
.consume_front("<") || !Params
.consume_back(">")) {
1439 assert(false && "invalid format for parametrized pass name");
1442 Expected
<ParametersT
> Result
= Parser(Params
);
1443 assert((Result
|| Result
.template errorIsA
<StringError
>()) &&
1444 "Pass parameter parser can only return StringErrors.");
1445 return std::move(Result
);
1448 /// Parser of parameters for LoopUnroll pass.
1449 Expected
<LoopUnrollOptions
> parseLoopUnrollOptions(StringRef Params
) {
1450 LoopUnrollOptions UnrollOpts
;
1451 while (!Params
.empty()) {
1452 StringRef ParamName
;
1453 std::tie(ParamName
, Params
) = Params
.split(';');
1454 int OptLevel
= StringSwitch
<int>(ParamName
)
1460 if (OptLevel
>= 0) {
1461 UnrollOpts
.setOptLevel(OptLevel
);
1464 if (ParamName
.consume_front("full-unroll-max=")) {
1466 if (ParamName
.getAsInteger(0, Count
))
1467 return make_error
<StringError
>(
1468 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName
).str(),
1469 inconvertibleErrorCode());
1470 UnrollOpts
.setFullUnrollMaxCount(Count
);
1474 bool Enable
= !ParamName
.consume_front("no-");
1475 if (ParamName
== "partial") {
1476 UnrollOpts
.setPartial(Enable
);
1477 } else if (ParamName
== "peeling") {
1478 UnrollOpts
.setPeeling(Enable
);
1479 } else if (ParamName
== "profile-peeling") {
1480 UnrollOpts
.setProfileBasedPeeling(Enable
);
1481 } else if (ParamName
== "runtime") {
1482 UnrollOpts
.setRuntime(Enable
);
1483 } else if (ParamName
== "upperbound") {
1484 UnrollOpts
.setUpperBound(Enable
);
1486 return make_error
<StringError
>(
1487 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName
).str(),
1488 inconvertibleErrorCode());
1494 Expected
<MemorySanitizerOptions
> parseMSanPassOptions(StringRef Params
) {
1495 MemorySanitizerOptions Result
;
1496 while (!Params
.empty()) {
1497 StringRef ParamName
;
1498 std::tie(ParamName
, Params
) = Params
.split(';');
1500 if (ParamName
== "recover") {
1501 Result
.Recover
= true;
1502 } else if (ParamName
== "kernel") {
1503 Result
.Kernel
= true;
1504 } else if (ParamName
.consume_front("track-origins=")) {
1505 if (ParamName
.getAsInteger(0, Result
.TrackOrigins
))
1506 return make_error
<StringError
>(
1507 formatv("invalid argument to MemorySanitizer pass track-origins "
1508 "parameter: '{0}' ",
1511 inconvertibleErrorCode());
1513 return make_error
<StringError
>(
1514 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName
)
1516 inconvertibleErrorCode());
1522 /// Parser of parameters for SimplifyCFG pass.
1523 Expected
<SimplifyCFGOptions
> parseSimplifyCFGOptions(StringRef Params
) {
1524 SimplifyCFGOptions Result
;
1525 while (!Params
.empty()) {
1526 StringRef ParamName
;
1527 std::tie(ParamName
, Params
) = Params
.split(';');
1529 bool Enable
= !ParamName
.consume_front("no-");
1530 if (ParamName
== "forward-switch-cond") {
1531 Result
.forwardSwitchCondToPhi(Enable
);
1532 } else if (ParamName
== "switch-to-lookup") {
1533 Result
.convertSwitchToLookupTable(Enable
);
1534 } else if (ParamName
== "keep-loops") {
1535 Result
.needCanonicalLoops(Enable
);
1536 } else if (ParamName
== "sink-common-insts") {
1537 Result
.sinkCommonInsts(Enable
);
1538 } else if (Enable
&& ParamName
.consume_front("bonus-inst-threshold=")) {
1539 APInt BonusInstThreshold
;
1540 if (ParamName
.getAsInteger(0, BonusInstThreshold
))
1541 return make_error
<StringError
>(
1542 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1543 "parameter: '{0}' ",
1545 inconvertibleErrorCode());
1546 Result
.bonusInstThreshold(BonusInstThreshold
.getSExtValue());
1548 return make_error
<StringError
>(
1549 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName
).str(),
1550 inconvertibleErrorCode());
1556 /// Parser of parameters for LoopVectorize pass.
1557 Expected
<LoopVectorizeOptions
> parseLoopVectorizeOptions(StringRef Params
) {
1558 LoopVectorizeOptions Opts
;
1559 while (!Params
.empty()) {
1560 StringRef ParamName
;
1561 std::tie(ParamName
, Params
) = Params
.split(';');
1563 bool Enable
= !ParamName
.consume_front("no-");
1564 if (ParamName
== "interleave-forced-only") {
1565 Opts
.setInterleaveOnlyWhenForced(Enable
);
1566 } else if (ParamName
== "vectorize-forced-only") {
1567 Opts
.setVectorizeOnlyWhenForced(Enable
);
1569 return make_error
<StringError
>(
1570 formatv("invalid LoopVectorize parameter '{0}' ", ParamName
).str(),
1571 inconvertibleErrorCode());
1577 Expected
<bool> parseLoopUnswitchOptions(StringRef Params
) {
1578 bool Result
= false;
1579 while (!Params
.empty()) {
1580 StringRef ParamName
;
1581 std::tie(ParamName
, Params
) = Params
.split(';');
1583 bool Enable
= !ParamName
.consume_front("no-");
1584 if (ParamName
== "nontrivial") {
1587 return make_error
<StringError
>(
1588 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName
)
1590 inconvertibleErrorCode());
1596 Expected
<bool> parseMergedLoadStoreMotionOptions(StringRef Params
) {
1597 bool Result
= false;
1598 while (!Params
.empty()) {
1599 StringRef ParamName
;
1600 std::tie(ParamName
, Params
) = Params
.split(';');
1602 bool Enable
= !ParamName
.consume_front("no-");
1603 if (ParamName
== "split-footer-bb") {
1606 return make_error
<StringError
>(
1607 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1610 inconvertibleErrorCode());
1617 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1619 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name
) {
1620 return Name
.startswith("default") || Name
.startswith("thinlto") ||
1621 Name
.startswith("lto");
1624 /// Tests whether registered callbacks will accept a given pass name.
1626 /// When parsing a pipeline text, the type of the outermost pipeline may be
1627 /// omitted, in which case the type is automatically determined from the first
1628 /// pass name in the text. This may be a name that is handled through one of the
1629 /// callbacks. We check this through the oridinary parsing callbacks by setting
1630 /// up a dummy PassManager in order to not force the client to also handle this
1632 template <typename PassManagerT
, typename CallbacksT
>
1633 static bool callbacksAcceptPassName(StringRef Name
, CallbacksT
&Callbacks
) {
1634 if (!Callbacks
.empty()) {
1635 PassManagerT DummyPM
;
1636 for (auto &CB
: Callbacks
)
1637 if (CB(Name
, DummyPM
, {}))
1643 template <typename CallbacksT
>
1644 static bool isModulePassName(StringRef Name
, CallbacksT
&Callbacks
) {
1645 // Manually handle aliases for pre-configured pipeline fragments.
1646 if (startsWithDefaultPipelineAliasPrefix(Name
))
1647 return DefaultAliasRegex
.match(Name
);
1649 // Explicitly handle pass manager names.
1650 if (Name
== "module")
1652 if (Name
== "cgscc")
1654 if (Name
== "function")
1657 // Explicitly handle custom-parsed pass names.
1658 if (parseRepeatPassName(Name
))
1661 #define MODULE_PASS(NAME, CREATE_PASS) \
1664 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1665 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1667 #include "PassRegistry.def"
1669 return callbacksAcceptPassName
<ModulePassManager
>(Name
, Callbacks
);
1672 template <typename CallbacksT
>
1673 static bool isCGSCCPassName(StringRef Name
, CallbacksT
&Callbacks
) {
1674 // Explicitly handle pass manager names.
1675 if (Name
== "cgscc")
1677 if (Name
== "function")
1680 // Explicitly handle custom-parsed pass names.
1681 if (parseRepeatPassName(Name
))
1683 if (parseDevirtPassName(Name
))
1686 #define CGSCC_PASS(NAME, CREATE_PASS) \
1689 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1690 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1692 #include "PassRegistry.def"
1694 return callbacksAcceptPassName
<CGSCCPassManager
>(Name
, Callbacks
);
1697 template <typename CallbacksT
>
1698 static bool isFunctionPassName(StringRef Name
, CallbacksT
&Callbacks
) {
1699 // Explicitly handle pass manager names.
1700 if (Name
== "function")
1702 if (Name
== "loop" || Name
== "loop-mssa")
1705 // Explicitly handle custom-parsed pass names.
1706 if (parseRepeatPassName(Name
))
1709 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1712 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1713 if (checkParametrizedPassName(Name, NAME)) \
1715 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1716 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1718 #include "PassRegistry.def"
1720 return callbacksAcceptPassName
<FunctionPassManager
>(Name
, Callbacks
);
1723 template <typename CallbacksT
>
1724 static bool isLoopPassName(StringRef Name
, CallbacksT
&Callbacks
) {
1725 // Explicitly handle pass manager names.
1726 if (Name
== "loop" || Name
== "loop-mssa")
1729 // Explicitly handle custom-parsed pass names.
1730 if (parseRepeatPassName(Name
))
1733 #define LOOP_PASS(NAME, CREATE_PASS) \
1736 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1737 if (checkParametrizedPassName(Name, NAME)) \
1739 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1740 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1742 #include "PassRegistry.def"
1744 return callbacksAcceptPassName
<LoopPassManager
>(Name
, Callbacks
);
1747 Optional
<std::vector
<PassBuilder::PipelineElement
>>
1748 PassBuilder::parsePipelineText(StringRef Text
) {
1749 std::vector
<PipelineElement
> ResultPipeline
;
1751 SmallVector
<std::vector
<PipelineElement
> *, 4> PipelineStack
= {
1754 std::vector
<PipelineElement
> &Pipeline
= *PipelineStack
.back();
1755 size_t Pos
= Text
.find_first_of(",()");
1756 Pipeline
.push_back({Text
.substr(0, Pos
), {}});
1758 // If we have a single terminating name, we're done.
1759 if (Pos
== Text
.npos
)
1762 char Sep
= Text
[Pos
];
1763 Text
= Text
.substr(Pos
+ 1);
1765 // Just a name ending in a comma, continue.
1769 // Push the inner pipeline onto the stack to continue processing.
1770 PipelineStack
.push_back(&Pipeline
.back().InnerPipeline
);
1774 assert(Sep
== ')' && "Bogus separator!");
1775 // When handling the close parenthesis, we greedily consume them to avoid
1776 // empty strings in the pipeline.
1778 // If we try to pop the outer pipeline we have unbalanced parentheses.
1779 if (PipelineStack
.size() == 1)
1782 PipelineStack
.pop_back();
1783 } while (Text
.consume_front(")"));
1785 // Check if we've finished parsing.
1789 // Otherwise, the end of an inner pipeline always has to be followed by
1790 // a comma, and then we can continue.
1791 if (!Text
.consume_front(","))
1795 if (PipelineStack
.size() > 1)
1796 // Unbalanced paretheses.
1799 assert(PipelineStack
.back() == &ResultPipeline
&&
1800 "Wrong pipeline at the bottom of the stack!");
1801 return {std::move(ResultPipeline
)};
1804 Error
PassBuilder::parseModulePass(ModulePassManager
&MPM
,
1805 const PipelineElement
&E
,
1806 bool VerifyEachPass
, bool DebugLogging
) {
1807 auto &Name
= E
.Name
;
1808 auto &InnerPipeline
= E
.InnerPipeline
;
1810 // First handle complex passes like the pass managers which carry pipelines.
1811 if (!InnerPipeline
.empty()) {
1812 if (Name
== "module") {
1813 ModulePassManager
NestedMPM(DebugLogging
);
1814 if (auto Err
= parseModulePassPipeline(NestedMPM
, InnerPipeline
,
1815 VerifyEachPass
, DebugLogging
))
1817 MPM
.addPass(std::move(NestedMPM
));
1818 return Error::success();
1820 if (Name
== "cgscc") {
1821 CGSCCPassManager
CGPM(DebugLogging
);
1822 if (auto Err
= parseCGSCCPassPipeline(CGPM
, InnerPipeline
, VerifyEachPass
,
1825 MPM
.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM
)));
1826 return Error::success();
1828 if (Name
== "function") {
1829 FunctionPassManager
FPM(DebugLogging
);
1830 if (auto Err
= parseFunctionPassPipeline(FPM
, InnerPipeline
,
1831 VerifyEachPass
, DebugLogging
))
1833 MPM
.addPass(createModuleToFunctionPassAdaptor(std::move(FPM
)));
1834 return Error::success();
1836 if (auto Count
= parseRepeatPassName(Name
)) {
1837 ModulePassManager
NestedMPM(DebugLogging
);
1838 if (auto Err
= parseModulePassPipeline(NestedMPM
, InnerPipeline
,
1839 VerifyEachPass
, DebugLogging
))
1841 MPM
.addPass(createRepeatedPass(*Count
, std::move(NestedMPM
)));
1842 return Error::success();
1845 for (auto &C
: ModulePipelineParsingCallbacks
)
1846 if (C(Name
, MPM
, InnerPipeline
))
1847 return Error::success();
1849 // Normal passes can't have pipelines.
1850 return make_error
<StringError
>(
1851 formatv("invalid use of '{0}' pass as module pipeline", Name
).str(),
1852 inconvertibleErrorCode());
1856 // Manually handle aliases for pre-configured pipeline fragments.
1857 if (startsWithDefaultPipelineAliasPrefix(Name
)) {
1858 SmallVector
<StringRef
, 3> Matches
;
1859 if (!DefaultAliasRegex
.match(Name
, &Matches
))
1860 return make_error
<StringError
>(
1861 formatv("unknown default pipeline alias '{0}'", Name
).str(),
1862 inconvertibleErrorCode());
1864 assert(Matches
.size() == 3 && "Must capture two matched strings!");
1866 OptimizationLevel L
= StringSwitch
<OptimizationLevel
>(Matches
[2])
1874 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1875 if (PGOOpt
&& Matches
[1] != "thinlto" &&
1876 (PGOOpt
->Action
== PGOOptions::IRInstr
||
1877 PGOOpt
->Action
== PGOOptions::IRUse
))
1878 addPGOInstrPassesForO0(
1880 /* RunProfileGen */ (PGOOpt
->Action
== PGOOptions::IRInstr
),
1881 /* IsCS */ false, PGOOpt
->ProfileFile
,
1882 PGOOpt
->ProfileRemappingFile
);
1883 // Do nothing else at all!
1884 return Error::success();
1887 if (Matches
[1] == "default") {
1888 MPM
.addPass(buildPerModuleDefaultPipeline(L
, DebugLogging
));
1889 } else if (Matches
[1] == "thinlto-pre-link") {
1890 MPM
.addPass(buildThinLTOPreLinkDefaultPipeline(L
, DebugLogging
));
1891 } else if (Matches
[1] == "thinlto") {
1892 MPM
.addPass(buildThinLTODefaultPipeline(L
, DebugLogging
, nullptr));
1893 } else if (Matches
[1] == "lto-pre-link") {
1894 MPM
.addPass(buildLTOPreLinkDefaultPipeline(L
, DebugLogging
));
1896 assert(Matches
[1] == "lto" && "Not one of the matched options!");
1897 MPM
.addPass(buildLTODefaultPipeline(L
, DebugLogging
, nullptr));
1899 return Error::success();
1902 // Finally expand the basic registered passes from the .inc file.
1903 #define MODULE_PASS(NAME, CREATE_PASS) \
1904 if (Name == NAME) { \
1905 MPM.addPass(CREATE_PASS); \
1906 return Error::success(); \
1908 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1909 if (Name == "require<" NAME ">") { \
1911 RequireAnalysisPass< \
1912 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1913 return Error::success(); \
1915 if (Name == "invalidate<" NAME ">") { \
1916 MPM.addPass(InvalidateAnalysisPass< \
1917 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1918 return Error::success(); \
1920 #include "PassRegistry.def"
1922 for (auto &C
: ModulePipelineParsingCallbacks
)
1923 if (C(Name
, MPM
, InnerPipeline
))
1924 return Error::success();
1925 return make_error
<StringError
>(
1926 formatv("unknown module pass '{0}'", Name
).str(),
1927 inconvertibleErrorCode());
1930 Error
PassBuilder::parseCGSCCPass(CGSCCPassManager
&CGPM
,
1931 const PipelineElement
&E
, bool VerifyEachPass
,
1932 bool DebugLogging
) {
1933 auto &Name
= E
.Name
;
1934 auto &InnerPipeline
= E
.InnerPipeline
;
1936 // First handle complex passes like the pass managers which carry pipelines.
1937 if (!InnerPipeline
.empty()) {
1938 if (Name
== "cgscc") {
1939 CGSCCPassManager
NestedCGPM(DebugLogging
);
1940 if (auto Err
= parseCGSCCPassPipeline(NestedCGPM
, InnerPipeline
,
1941 VerifyEachPass
, DebugLogging
))
1943 // Add the nested pass manager with the appropriate adaptor.
1944 CGPM
.addPass(std::move(NestedCGPM
));
1945 return Error::success();
1947 if (Name
== "function") {
1948 FunctionPassManager
FPM(DebugLogging
);
1949 if (auto Err
= parseFunctionPassPipeline(FPM
, InnerPipeline
,
1950 VerifyEachPass
, DebugLogging
))
1952 // Add the nested pass manager with the appropriate adaptor.
1953 CGPM
.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM
)));
1954 return Error::success();
1956 if (auto Count
= parseRepeatPassName(Name
)) {
1957 CGSCCPassManager
NestedCGPM(DebugLogging
);
1958 if (auto Err
= parseCGSCCPassPipeline(NestedCGPM
, InnerPipeline
,
1959 VerifyEachPass
, DebugLogging
))
1961 CGPM
.addPass(createRepeatedPass(*Count
, std::move(NestedCGPM
)));
1962 return Error::success();
1964 if (auto MaxRepetitions
= parseDevirtPassName(Name
)) {
1965 CGSCCPassManager
NestedCGPM(DebugLogging
);
1966 if (auto Err
= parseCGSCCPassPipeline(NestedCGPM
, InnerPipeline
,
1967 VerifyEachPass
, DebugLogging
))
1970 createDevirtSCCRepeatedPass(std::move(NestedCGPM
), *MaxRepetitions
));
1971 return Error::success();
1974 for (auto &C
: CGSCCPipelineParsingCallbacks
)
1975 if (C(Name
, CGPM
, InnerPipeline
))
1976 return Error::success();
1978 // Normal passes can't have pipelines.
1979 return make_error
<StringError
>(
1980 formatv("invalid use of '{0}' pass as cgscc pipeline", Name
).str(),
1981 inconvertibleErrorCode());
1984 // Now expand the basic registered passes from the .inc file.
1985 #define CGSCC_PASS(NAME, CREATE_PASS) \
1986 if (Name == NAME) { \
1987 CGPM.addPass(CREATE_PASS); \
1988 return Error::success(); \
1990 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1991 if (Name == "require<" NAME ">") { \
1992 CGPM.addPass(RequireAnalysisPass< \
1993 std::remove_reference<decltype(CREATE_PASS)>::type, \
1994 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1995 CGSCCUpdateResult &>()); \
1996 return Error::success(); \
1998 if (Name == "invalidate<" NAME ">") { \
1999 CGPM.addPass(InvalidateAnalysisPass< \
2000 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2001 return Error::success(); \
2003 #include "PassRegistry.def"
2005 for (auto &C
: CGSCCPipelineParsingCallbacks
)
2006 if (C(Name
, CGPM
, InnerPipeline
))
2007 return Error::success();
2008 return make_error
<StringError
>(
2009 formatv("unknown cgscc pass '{0}'", Name
).str(),
2010 inconvertibleErrorCode());
2013 Error
PassBuilder::parseFunctionPass(FunctionPassManager
&FPM
,
2014 const PipelineElement
&E
,
2015 bool VerifyEachPass
, bool DebugLogging
) {
2016 auto &Name
= E
.Name
;
2017 auto &InnerPipeline
= E
.InnerPipeline
;
2019 // First handle complex passes like the pass managers which carry pipelines.
2020 if (!InnerPipeline
.empty()) {
2021 if (Name
== "function") {
2022 FunctionPassManager
NestedFPM(DebugLogging
);
2023 if (auto Err
= parseFunctionPassPipeline(NestedFPM
, InnerPipeline
,
2024 VerifyEachPass
, DebugLogging
))
2026 // Add the nested pass manager with the appropriate adaptor.
2027 FPM
.addPass(std::move(NestedFPM
));
2028 return Error::success();
2030 if (Name
== "loop" || Name
== "loop-mssa") {
2031 LoopPassManager
LPM(DebugLogging
);
2032 if (auto Err
= parseLoopPassPipeline(LPM
, InnerPipeline
, VerifyEachPass
,
2035 // Add the nested pass manager with the appropriate adaptor.
2036 bool UseMemorySSA
= (Name
== "loop-mssa");
2037 FPM
.addPass(createFunctionToLoopPassAdaptor(std::move(LPM
), UseMemorySSA
,
2039 return Error::success();
2041 if (auto Count
= parseRepeatPassName(Name
)) {
2042 FunctionPassManager
NestedFPM(DebugLogging
);
2043 if (auto Err
= parseFunctionPassPipeline(NestedFPM
, InnerPipeline
,
2044 VerifyEachPass
, DebugLogging
))
2046 FPM
.addPass(createRepeatedPass(*Count
, std::move(NestedFPM
)));
2047 return Error::success();
2050 for (auto &C
: FunctionPipelineParsingCallbacks
)
2051 if (C(Name
, FPM
, InnerPipeline
))
2052 return Error::success();
2054 // Normal passes can't have pipelines.
2055 return make_error
<StringError
>(
2056 formatv("invalid use of '{0}' pass as function pipeline", Name
).str(),
2057 inconvertibleErrorCode());
2060 // Now expand the basic registered passes from the .inc file.
2061 #define FUNCTION_PASS(NAME, CREATE_PASS) \
2062 if (Name == NAME) { \
2063 FPM.addPass(CREATE_PASS); \
2064 return Error::success(); \
2066 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2067 if (checkParametrizedPassName(Name, NAME)) { \
2068 auto Params = parsePassParameters(PARSER, Name, NAME); \
2070 return Params.takeError(); \
2071 FPM.addPass(CREATE_PASS(Params.get())); \
2072 return Error::success(); \
2074 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2075 if (Name == "require<" NAME ">") { \
2077 RequireAnalysisPass< \
2078 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
2079 return Error::success(); \
2081 if (Name == "invalidate<" NAME ">") { \
2082 FPM.addPass(InvalidateAnalysisPass< \
2083 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2084 return Error::success(); \
2086 #include "PassRegistry.def"
2088 for (auto &C
: FunctionPipelineParsingCallbacks
)
2089 if (C(Name
, FPM
, InnerPipeline
))
2090 return Error::success();
2091 return make_error
<StringError
>(
2092 formatv("unknown function pass '{0}'", Name
).str(),
2093 inconvertibleErrorCode());
2096 Error
PassBuilder::parseLoopPass(LoopPassManager
&LPM
, const PipelineElement
&E
,
2097 bool VerifyEachPass
, bool DebugLogging
) {
2098 StringRef Name
= E
.Name
;
2099 auto &InnerPipeline
= E
.InnerPipeline
;
2101 // First handle complex passes like the pass managers which carry pipelines.
2102 if (!InnerPipeline
.empty()) {
2103 if (Name
== "loop") {
2104 LoopPassManager
NestedLPM(DebugLogging
);
2105 if (auto Err
= parseLoopPassPipeline(NestedLPM
, InnerPipeline
,
2106 VerifyEachPass
, DebugLogging
))
2108 // Add the nested pass manager with the appropriate adaptor.
2109 LPM
.addPass(std::move(NestedLPM
));
2110 return Error::success();
2112 if (auto Count
= parseRepeatPassName(Name
)) {
2113 LoopPassManager
NestedLPM(DebugLogging
);
2114 if (auto Err
= parseLoopPassPipeline(NestedLPM
, InnerPipeline
,
2115 VerifyEachPass
, DebugLogging
))
2117 LPM
.addPass(createRepeatedPass(*Count
, std::move(NestedLPM
)));
2118 return Error::success();
2121 for (auto &C
: LoopPipelineParsingCallbacks
)
2122 if (C(Name
, LPM
, InnerPipeline
))
2123 return Error::success();
2125 // Normal passes can't have pipelines.
2126 return make_error
<StringError
>(
2127 formatv("invalid use of '{0}' pass as loop pipeline", Name
).str(),
2128 inconvertibleErrorCode());
2131 // Now expand the basic registered passes from the .inc file.
2132 #define LOOP_PASS(NAME, CREATE_PASS) \
2133 if (Name == NAME) { \
2134 LPM.addPass(CREATE_PASS); \
2135 return Error::success(); \
2137 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2138 if (checkParametrizedPassName(Name, NAME)) { \
2139 auto Params = parsePassParameters(PARSER, Name, NAME); \
2141 return Params.takeError(); \
2142 LPM.addPass(CREATE_PASS(Params.get())); \
2143 return Error::success(); \
2145 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2146 if (Name == "require<" NAME ">") { \
2147 LPM.addPass(RequireAnalysisPass< \
2148 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2149 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2151 return Error::success(); \
2153 if (Name == "invalidate<" NAME ">") { \
2154 LPM.addPass(InvalidateAnalysisPass< \
2155 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2156 return Error::success(); \
2158 #include "PassRegistry.def"
2160 for (auto &C
: LoopPipelineParsingCallbacks
)
2161 if (C(Name
, LPM
, InnerPipeline
))
2162 return Error::success();
2163 return make_error
<StringError
>(formatv("unknown loop pass '{0}'", Name
).str(),
2164 inconvertibleErrorCode());
2167 bool PassBuilder::parseAAPassName(AAManager
&AA
, StringRef Name
) {
2168 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2169 if (Name == NAME) { \
2170 AA.registerModuleAnalysis< \
2171 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2174 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2175 if (Name == NAME) { \
2176 AA.registerFunctionAnalysis< \
2177 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2180 #include "PassRegistry.def"
2182 for (auto &C
: AAParsingCallbacks
)
2188 Error
PassBuilder::parseLoopPassPipeline(LoopPassManager
&LPM
,
2189 ArrayRef
<PipelineElement
> Pipeline
,
2190 bool VerifyEachPass
,
2191 bool DebugLogging
) {
2192 for (const auto &Element
: Pipeline
) {
2193 if (auto Err
= parseLoopPass(LPM
, Element
, VerifyEachPass
, DebugLogging
))
2195 // FIXME: No verifier support for Loop passes!
2197 return Error::success();
2200 Error
PassBuilder::parseFunctionPassPipeline(FunctionPassManager
&FPM
,
2201 ArrayRef
<PipelineElement
> Pipeline
,
2202 bool VerifyEachPass
,
2203 bool DebugLogging
) {
2204 for (const auto &Element
: Pipeline
) {
2206 parseFunctionPass(FPM
, Element
, VerifyEachPass
, DebugLogging
))
2209 FPM
.addPass(VerifierPass());
2211 return Error::success();
2214 Error
PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager
&CGPM
,
2215 ArrayRef
<PipelineElement
> Pipeline
,
2216 bool VerifyEachPass
,
2217 bool DebugLogging
) {
2218 for (const auto &Element
: Pipeline
) {
2219 if (auto Err
= parseCGSCCPass(CGPM
, Element
, VerifyEachPass
, DebugLogging
))
2221 // FIXME: No verifier support for CGSCC passes!
2223 return Error::success();
2226 void PassBuilder::crossRegisterProxies(LoopAnalysisManager
&LAM
,
2227 FunctionAnalysisManager
&FAM
,
2228 CGSCCAnalysisManager
&CGAM
,
2229 ModuleAnalysisManager
&MAM
) {
2230 MAM
.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM
); });
2231 MAM
.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM
); });
2232 CGAM
.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM
); });
2233 FAM
.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM
); });
2234 FAM
.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM
); });
2235 FAM
.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM
); });
2236 LAM
.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM
); });
2239 Error
PassBuilder::parseModulePassPipeline(ModulePassManager
&MPM
,
2240 ArrayRef
<PipelineElement
> Pipeline
,
2241 bool VerifyEachPass
,
2242 bool DebugLogging
) {
2243 for (const auto &Element
: Pipeline
) {
2244 if (auto Err
= parseModulePass(MPM
, Element
, VerifyEachPass
, DebugLogging
))
2247 MPM
.addPass(VerifierPass());
2249 return Error::success();
2252 // Primary pass pipeline description parsing routine for a \c ModulePassManager
2253 // FIXME: Should this routine accept a TargetMachine or require the caller to
2254 // pre-populate the analysis managers with target-specific stuff?
2255 Error
PassBuilder::parsePassPipeline(ModulePassManager
&MPM
,
2256 StringRef PipelineText
,
2257 bool VerifyEachPass
, bool DebugLogging
) {
2258 auto Pipeline
= parsePipelineText(PipelineText
);
2259 if (!Pipeline
|| Pipeline
->empty())
2260 return make_error
<StringError
>(
2261 formatv("invalid pipeline '{0}'", PipelineText
).str(),
2262 inconvertibleErrorCode());
2264 // If the first name isn't at the module layer, wrap the pipeline up
2266 StringRef FirstName
= Pipeline
->front().Name
;
2268 if (!isModulePassName(FirstName
, ModulePipelineParsingCallbacks
)) {
2269 if (isCGSCCPassName(FirstName
, CGSCCPipelineParsingCallbacks
)) {
2270 Pipeline
= {{"cgscc", std::move(*Pipeline
)}};
2271 } else if (isFunctionPassName(FirstName
,
2272 FunctionPipelineParsingCallbacks
)) {
2273 Pipeline
= {{"function", std::move(*Pipeline
)}};
2274 } else if (isLoopPassName(FirstName
, LoopPipelineParsingCallbacks
)) {
2275 Pipeline
= {{"function", {{"loop", std::move(*Pipeline
)}}}};
2277 for (auto &C
: TopLevelPipelineParsingCallbacks
)
2278 if (C(MPM
, *Pipeline
, VerifyEachPass
, DebugLogging
))
2279 return Error::success();
2281 // Unknown pass or pipeline name!
2282 auto &InnerPipeline
= Pipeline
->front().InnerPipeline
;
2283 return make_error
<StringError
>(
2284 formatv("unknown {0} name '{1}'",
2285 (InnerPipeline
.empty() ? "pass" : "pipeline"), FirstName
)
2287 inconvertibleErrorCode());
2292 parseModulePassPipeline(MPM
, *Pipeline
, VerifyEachPass
, DebugLogging
))
2294 return Error::success();
2297 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
2298 Error
PassBuilder::parsePassPipeline(CGSCCPassManager
&CGPM
,
2299 StringRef PipelineText
,
2300 bool VerifyEachPass
, bool DebugLogging
) {
2301 auto Pipeline
= parsePipelineText(PipelineText
);
2302 if (!Pipeline
|| Pipeline
->empty())
2303 return make_error
<StringError
>(
2304 formatv("invalid pipeline '{0}'", PipelineText
).str(),
2305 inconvertibleErrorCode());
2307 StringRef FirstName
= Pipeline
->front().Name
;
2308 if (!isCGSCCPassName(FirstName
, CGSCCPipelineParsingCallbacks
))
2309 return make_error
<StringError
>(
2310 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName
,
2313 inconvertibleErrorCode());
2316 parseCGSCCPassPipeline(CGPM
, *Pipeline
, VerifyEachPass
, DebugLogging
))
2318 return Error::success();
2321 // Primary pass pipeline description parsing routine for a \c
2322 // FunctionPassManager
2323 Error
PassBuilder::parsePassPipeline(FunctionPassManager
&FPM
,
2324 StringRef PipelineText
,
2325 bool VerifyEachPass
, bool DebugLogging
) {
2326 auto Pipeline
= parsePipelineText(PipelineText
);
2327 if (!Pipeline
|| Pipeline
->empty())
2328 return make_error
<StringError
>(
2329 formatv("invalid pipeline '{0}'", PipelineText
).str(),
2330 inconvertibleErrorCode());
2332 StringRef FirstName
= Pipeline
->front().Name
;
2333 if (!isFunctionPassName(FirstName
, FunctionPipelineParsingCallbacks
))
2334 return make_error
<StringError
>(
2335 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName
,
2338 inconvertibleErrorCode());
2340 if (auto Err
= parseFunctionPassPipeline(FPM
, *Pipeline
, VerifyEachPass
,
2343 return Error::success();
2346 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2347 Error
PassBuilder::parsePassPipeline(LoopPassManager
&CGPM
,
2348 StringRef PipelineText
,
2349 bool VerifyEachPass
, bool DebugLogging
) {
2350 auto Pipeline
= parsePipelineText(PipelineText
);
2351 if (!Pipeline
|| Pipeline
->empty())
2352 return make_error
<StringError
>(
2353 formatv("invalid pipeline '{0}'", PipelineText
).str(),
2354 inconvertibleErrorCode());
2357 parseLoopPassPipeline(CGPM
, *Pipeline
, VerifyEachPass
, DebugLogging
))
2360 return Error::success();
2363 Error
PassBuilder::parseAAPipeline(AAManager
&AA
, StringRef PipelineText
) {
2364 // If the pipeline just consists of the word 'default' just replace the AA
2365 // manager with our default one.
2366 if (PipelineText
== "default") {
2367 AA
= buildDefaultAAPipeline();
2368 return Error::success();
2371 while (!PipelineText
.empty()) {
2373 std::tie(Name
, PipelineText
) = PipelineText
.split(',');
2374 if (!parseAAPassName(AA
, Name
))
2375 return make_error
<StringError
>(
2376 formatv("unknown alias analysis name '{0}'", Name
).str(),
2377 inconvertibleErrorCode());
2380 return Error::success();