[yaml2obj/obj2yaml] - Add support for .stack_sizes sections.
[llvm-complete.git] / lib / Passes / PassBuilder.cpp
blob08be32b5adb89b1e29b53c947132a1517940284f
1 //===- Parsing, selection, and construction of pass pipelines -------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
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
13 /// pipelines.
14 ///
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/PreISelIntrinsicLowering.h"
57 #include "llvm/CodeGen/UnreachableBlockElim.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/IRPrintingPasses.h"
60 #include "llvm/IR/PassManager.h"
61 #include "llvm/IR/SafepointIRVerifier.h"
62 #include "llvm/IR/Verifier.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/FormatVariadic.h"
65 #include "llvm/Support/Regex.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
68 #include "llvm/Transforms/IPO/AlwaysInliner.h"
69 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
70 #include "llvm/Transforms/IPO/Attributor.h"
71 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
72 #include "llvm/Transforms/IPO/ConstantMerge.h"
73 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
74 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
75 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
76 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
77 #include "llvm/Transforms/IPO/FunctionAttrs.h"
78 #include "llvm/Transforms/IPO/FunctionImport.h"
79 #include "llvm/Transforms/IPO/GlobalDCE.h"
80 #include "llvm/Transforms/IPO/GlobalOpt.h"
81 #include "llvm/Transforms/IPO/GlobalSplit.h"
82 #include "llvm/Transforms/IPO/HotColdSplitting.h"
83 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
84 #include "llvm/Transforms/IPO/Inliner.h"
85 #include "llvm/Transforms/IPO/Internalize.h"
86 #include "llvm/Transforms/IPO/LowerTypeTests.h"
87 #include "llvm/Transforms/IPO/PartialInlining.h"
88 #include "llvm/Transforms/IPO/SCCP.h"
89 #include "llvm/Transforms/IPO/SampleProfile.h"
90 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
91 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
92 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
93 #include "llvm/Transforms/InstCombine/InstCombine.h"
94 #include "llvm/Transforms/Instrumentation.h"
95 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
96 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
97 #include "llvm/Transforms/Instrumentation/CGProfile.h"
98 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
99 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
100 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
101 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
102 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
103 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
104 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
105 #include "llvm/Transforms/Instrumentation/PoisonChecking.h"
106 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
107 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
108 #include "llvm/Transforms/Scalar/ADCE.h"
109 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
110 #include "llvm/Transforms/Scalar/BDCE.h"
111 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
112 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
113 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
114 #include "llvm/Transforms/Scalar/DCE.h"
115 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
116 #include "llvm/Transforms/Scalar/DivRemPairs.h"
117 #include "llvm/Transforms/Scalar/EarlyCSE.h"
118 #include "llvm/Transforms/Scalar/Float2Int.h"
119 #include "llvm/Transforms/Scalar/GVN.h"
120 #include "llvm/Transforms/Scalar/GuardWidening.h"
121 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
122 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
123 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
124 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
125 #include "llvm/Transforms/Scalar/JumpThreading.h"
126 #include "llvm/Transforms/Scalar/LICM.h"
127 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
128 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
129 #include "llvm/Transforms/Scalar/LoopDeletion.h"
130 #include "llvm/Transforms/Scalar/LoopDistribute.h"
131 #include "llvm/Transforms/Scalar/LoopFuse.h"
132 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
133 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
134 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
135 #include "llvm/Transforms/Scalar/LoopPassManager.h"
136 #include "llvm/Transforms/Scalar/LoopPredication.h"
137 #include "llvm/Transforms/Scalar/LoopRotation.h"
138 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
139 #include "llvm/Transforms/Scalar/LoopSink.h"
140 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
141 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
142 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
143 #include "llvm/Transforms/Scalar/LowerAtomic.h"
144 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
145 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
146 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
147 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
148 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
149 #include "llvm/Transforms/Scalar/MergeICmps.h"
150 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
151 #include "llvm/Transforms/Scalar/NaryReassociate.h"
152 #include "llvm/Transforms/Scalar/NewGVN.h"
153 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
154 #include "llvm/Transforms/Scalar/Reassociate.h"
155 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
156 #include "llvm/Transforms/Scalar/SCCP.h"
157 #include "llvm/Transforms/Scalar/SROA.h"
158 #include "llvm/Transforms/Scalar/Scalarizer.h"
159 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
160 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
161 #include "llvm/Transforms/Scalar/Sink.h"
162 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h"
163 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
164 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
165 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
166 #include "llvm/Transforms/Utils/AddDiscriminators.h"
167 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
168 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
169 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
170 #include "llvm/Transforms/Utils/LCSSA.h"
171 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
172 #include "llvm/Transforms/Utils/LoopSimplify.h"
173 #include "llvm/Transforms/Utils/LowerInvoke.h"
174 #include "llvm/Transforms/Utils/Mem2Reg.h"
175 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
176 #include "llvm/Transforms/Utils/SymbolRewriter.h"
177 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
178 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
179 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
181 using namespace llvm;
183 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
184 cl::ReallyHidden, cl::init(4));
185 static cl::opt<bool>
186 RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
187 cl::Hidden, cl::ZeroOrMore,
188 cl::desc("Run Partial inlinining pass"));
190 static cl::opt<bool>
191 RunNewGVN("enable-npm-newgvn", cl::init(false),
192 cl::Hidden, cl::ZeroOrMore,
193 cl::desc("Run NewGVN instead of GVN"));
195 static cl::opt<bool> EnableGVNHoist(
196 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
197 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
199 static cl::opt<bool> EnableGVNSink(
200 "enable-npm-gvn-sink", cl::init(false), cl::Hidden,
201 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
203 static cl::opt<bool> EnableUnrollAndJam(
204 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden,
205 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)"));
207 static cl::opt<bool> EnableSyntheticCounts(
208 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
209 cl::desc("Run synthetic function entry count generation "
210 "pass"));
212 static Regex DefaultAliasRegex(
213 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
215 // This option is used in simplifying testing SampleFDO optimizations for
216 // profile loading.
217 static cl::opt<bool>
218 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden,
219 cl::desc("Enable control height reduction optimization (CHR)"));
221 PipelineTuningOptions::PipelineTuningOptions() {
222 LoopInterleaving = EnableLoopInterleaving;
223 LoopVectorization = EnableLoopVectorization;
224 SLPVectorization = RunSLPVectorization;
225 LoopUnrolling = true;
226 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
227 LicmMssaOptCap = SetLicmMssaOptCap;
228 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
231 extern cl::opt<bool> EnableHotColdSplit;
232 extern cl::opt<bool> EnableOrderFileInstrumentation;
234 extern cl::opt<bool> FlattenedProfileUsed;
236 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
237 switch (Level) {
238 case PassBuilder::O0:
239 case PassBuilder::O1:
240 case PassBuilder::O2:
241 case PassBuilder::O3:
242 return false;
244 case PassBuilder::Os:
245 case PassBuilder::Oz:
246 return true;
248 llvm_unreachable("Invalid optimization level!");
251 namespace {
253 /// No-op module pass which does nothing.
254 struct NoOpModulePass {
255 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
256 return PreservedAnalyses::all();
258 static StringRef name() { return "NoOpModulePass"; }
261 /// No-op module analysis.
262 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
263 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
264 static AnalysisKey Key;
266 public:
267 struct Result {};
268 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
269 static StringRef name() { return "NoOpModuleAnalysis"; }
272 /// No-op CGSCC pass which does nothing.
273 struct NoOpCGSCCPass {
274 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
275 LazyCallGraph &, CGSCCUpdateResult &UR) {
276 return PreservedAnalyses::all();
278 static StringRef name() { return "NoOpCGSCCPass"; }
281 /// No-op CGSCC analysis.
282 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
283 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
284 static AnalysisKey Key;
286 public:
287 struct Result {};
288 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
289 return Result();
291 static StringRef name() { return "NoOpCGSCCAnalysis"; }
294 /// No-op function pass which does nothing.
295 struct NoOpFunctionPass {
296 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
297 return PreservedAnalyses::all();
299 static StringRef name() { return "NoOpFunctionPass"; }
302 /// No-op function analysis.
303 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
304 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
305 static AnalysisKey Key;
307 public:
308 struct Result {};
309 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
310 static StringRef name() { return "NoOpFunctionAnalysis"; }
313 /// No-op loop pass which does nothing.
314 struct NoOpLoopPass {
315 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
316 LoopStandardAnalysisResults &, LPMUpdater &) {
317 return PreservedAnalyses::all();
319 static StringRef name() { return "NoOpLoopPass"; }
322 /// No-op loop analysis.
323 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
324 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
325 static AnalysisKey Key;
327 public:
328 struct Result {};
329 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
330 return Result();
332 static StringRef name() { return "NoOpLoopAnalysis"; }
335 AnalysisKey NoOpModuleAnalysis::Key;
336 AnalysisKey NoOpCGSCCAnalysis::Key;
337 AnalysisKey NoOpFunctionAnalysis::Key;
338 AnalysisKey NoOpLoopAnalysis::Key;
340 } // End anonymous namespace.
342 void PassBuilder::invokePeepholeEPCallbacks(
343 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
344 for (auto &C : PeepholeEPCallbacks)
345 C(FPM, Level);
348 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
349 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
350 MAM.registerPass([&] { return CREATE_PASS; });
351 #include "PassRegistry.def"
353 for (auto &C : ModuleAnalysisRegistrationCallbacks)
354 C(MAM);
357 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
358 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
359 CGAM.registerPass([&] { return CREATE_PASS; });
360 #include "PassRegistry.def"
362 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
363 C(CGAM);
366 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
367 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
368 FAM.registerPass([&] { return CREATE_PASS; });
369 #include "PassRegistry.def"
371 for (auto &C : FunctionAnalysisRegistrationCallbacks)
372 C(FAM);
375 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
376 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
377 LAM.registerPass([&] { return CREATE_PASS; });
378 #include "PassRegistry.def"
380 for (auto &C : LoopAnalysisRegistrationCallbacks)
381 C(LAM);
384 FunctionPassManager
385 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
386 ThinLTOPhase Phase,
387 bool DebugLogging) {
388 assert(Level != O0 && "Must request optimizations!");
389 FunctionPassManager FPM(DebugLogging);
391 // Form SSA out of local memory accesses after breaking apart aggregates into
392 // scalars.
393 FPM.addPass(SROA());
395 // Catch trivial redundancies
396 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
398 // Hoisting of scalars and load expressions.
399 if (EnableGVNHoist)
400 FPM.addPass(GVNHoistPass());
402 // Global value numbering based sinking.
403 if (EnableGVNSink) {
404 FPM.addPass(GVNSinkPass());
405 FPM.addPass(SimplifyCFGPass());
408 // Speculative execution if the target has divergent branches; otherwise nop.
409 FPM.addPass(SpeculativeExecutionPass());
411 // Optimize based on known information about branches, and cleanup afterward.
412 FPM.addPass(JumpThreadingPass());
413 FPM.addPass(CorrelatedValuePropagationPass());
414 FPM.addPass(SimplifyCFGPass());
415 if (Level == O3)
416 FPM.addPass(AggressiveInstCombinePass());
417 FPM.addPass(InstCombinePass());
419 if (!isOptimizingForSize(Level))
420 FPM.addPass(LibCallsShrinkWrapPass());
422 invokePeepholeEPCallbacks(FPM, Level);
424 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
425 // using the size value profile. Don't perform this when optimizing for size.
426 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
427 !isOptimizingForSize(Level))
428 FPM.addPass(PGOMemOPSizeOpt());
430 FPM.addPass(TailCallElimPass());
431 FPM.addPass(SimplifyCFGPass());
433 // Form canonically associated expression trees, and simplify the trees using
434 // basic mathematical properties. For example, this will form (nearly)
435 // minimal multiplication trees.
436 FPM.addPass(ReassociatePass());
438 // Add the primary loop simplification pipeline.
439 // FIXME: Currently this is split into two loop pass pipelines because we run
440 // some function passes in between them. These can and should be removed
441 // and/or replaced by scheduling the loop pass equivalents in the correct
442 // positions. But those equivalent passes aren't powerful enough yet.
443 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
444 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
445 // fully replace `SimplifyCFGPass`, and the closest to the other we have is
446 // `LoopInstSimplify`.
447 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
449 // Simplify the loop body. We do this initially to clean up after other loop
450 // passes run, either when iterating on a loop or on inner loops with
451 // implications on the outer loop.
452 LPM1.addPass(LoopInstSimplifyPass());
453 LPM1.addPass(LoopSimplifyCFGPass());
455 // Rotate Loop - disable header duplication at -Oz
456 LPM1.addPass(LoopRotatePass(Level != Oz));
457 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap));
458 LPM1.addPass(SimpleLoopUnswitchPass());
459 LPM2.addPass(IndVarSimplifyPass());
460 LPM2.addPass(LoopIdiomRecognizePass());
462 for (auto &C : LateLoopOptimizationsEPCallbacks)
463 C(LPM2, Level);
465 LPM2.addPass(LoopDeletionPass());
466 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
467 // because it changes IR to makes profile annotation in back compile
468 // inaccurate.
469 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt ||
470 PGOOpt->Action != PGOOptions::SampleUse) &&
471 PTO.LoopUnrolling)
472 LPM2.addPass(
473 LoopFullUnrollPass(Level, false, PTO.ForgetAllSCEVInLoopUnroll));
475 for (auto &C : LoopOptimizerEndEPCallbacks)
476 C(LPM2, Level);
478 // We provide the opt remark emitter pass for LICM to use. We only need to do
479 // this once as it is immutable.
480 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
481 FPM.addPass(createFunctionToLoopPassAdaptor(
482 std::move(LPM1), EnableMSSALoopDependency, DebugLogging));
483 FPM.addPass(SimplifyCFGPass());
484 FPM.addPass(InstCombinePass());
485 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass,
486 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
487 // *All* loop passes must preserve it, in order to be able to use it.
488 FPM.addPass(createFunctionToLoopPassAdaptor(
489 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging));
491 // Eliminate redundancies.
492 if (Level != O1) {
493 // These passes add substantial compile time so skip them at O1.
494 FPM.addPass(MergedLoadStoreMotionPass());
495 if (RunNewGVN)
496 FPM.addPass(NewGVNPass());
497 else
498 FPM.addPass(GVN());
501 // Specially optimize memory movement as it doesn't look like dataflow in SSA.
502 FPM.addPass(MemCpyOptPass());
504 // Sparse conditional constant propagation.
505 // FIXME: It isn't clear why we do this *after* loop passes rather than
506 // before...
507 FPM.addPass(SCCPPass());
509 // Delete dead bit computations (instcombine runs after to fold away the dead
510 // computations, and then ADCE will run later to exploit any new DCE
511 // opportunities that creates).
512 FPM.addPass(BDCEPass());
514 // Run instcombine after redundancy and dead bit elimination to exploit
515 // opportunities opened up by them.
516 FPM.addPass(InstCombinePass());
517 invokePeepholeEPCallbacks(FPM, Level);
519 // Re-consider control flow based optimizations after redundancy elimination,
520 // redo DCE, etc.
521 FPM.addPass(JumpThreadingPass());
522 FPM.addPass(CorrelatedValuePropagationPass());
523 FPM.addPass(DSEPass());
524 FPM.addPass(createFunctionToLoopPassAdaptor(
525 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
526 EnableMSSALoopDependency, DebugLogging));
528 for (auto &C : ScalarOptimizerLateEPCallbacks)
529 C(FPM, Level);
531 // Finally, do an expensive DCE pass to catch all the dead code exposed by
532 // the simplifications and basic cleanup after all the simplifications.
533 FPM.addPass(ADCEPass());
534 FPM.addPass(SimplifyCFGPass());
535 FPM.addPass(InstCombinePass());
536 invokePeepholeEPCallbacks(FPM, Level);
538 if (EnableCHR && Level == O3 && PGOOpt &&
539 (PGOOpt->Action == PGOOptions::IRUse ||
540 PGOOpt->Action == PGOOptions::SampleUse))
541 FPM.addPass(ControlHeightReductionPass());
543 return FPM;
546 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
547 PassBuilder::OptimizationLevel Level,
548 bool RunProfileGen, bool IsCS,
549 std::string ProfileFile,
550 std::string ProfileRemappingFile) {
551 assert(Level != O0 && "Not expecting O0 here!");
552 // Generally running simplification passes and the inliner with an high
553 // threshold results in smaller executables, but there may be cases where
554 // the size grows, so let's be conservative here and skip this simplification
555 // at -Os/Oz. We will not do this inline for context sensistive PGO (when
556 // IsCS is true).
557 if (!isOptimizingForSize(Level) && !IsCS) {
558 InlineParams IP;
560 // In the old pass manager, this is a cl::opt. Should still this be one?
561 IP.DefaultThreshold = 75;
563 // FIXME: The hint threshold has the same value used by the regular inliner.
564 // This should probably be lowered after performance testing.
565 // FIXME: this comment is cargo culted from the old pass manager, revisit).
566 IP.HintThreshold = 325;
568 CGSCCPassManager CGPipeline(DebugLogging);
570 CGPipeline.addPass(InlinerPass(IP));
572 FunctionPassManager FPM;
573 FPM.addPass(SROA());
574 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies.
575 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
576 FPM.addPass(InstCombinePass()); // Combine silly sequences.
577 invokePeepholeEPCallbacks(FPM, Level);
579 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
581 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
583 // Delete anything that is now dead to make sure that we don't instrument
584 // dead code. Instrumentation can end up keeping dead code around and
585 // dramatically increase code size.
586 MPM.addPass(GlobalDCEPass());
589 if (!RunProfileGen) {
590 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
591 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
592 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
593 // RequireAnalysisPass for PSI before subsequent non-module passes.
594 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
595 return;
598 // Perform PGO instrumentation.
599 MPM.addPass(PGOInstrumentationGen(IsCS));
601 FunctionPassManager FPM;
602 FPM.addPass(createFunctionToLoopPassAdaptor(
603 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
604 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
606 // Add the profile lowering pass.
607 InstrProfOptions Options;
608 if (!ProfileFile.empty())
609 Options.InstrProfileOutput = ProfileFile;
610 // Do counter promotion at Level greater than O0.
611 Options.DoCounterPromotion = true;
612 Options.UseBFIInPromotion = IsCS;
613 MPM.addPass(InstrProfiling(Options, IsCS));
616 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
617 bool DebugLogging, bool RunProfileGen,
618 bool IsCS, std::string ProfileFile,
619 std::string ProfileRemappingFile) {
620 if (!RunProfileGen) {
621 assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
622 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
623 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
624 // RequireAnalysisPass for PSI before subsequent non-module passes.
625 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
626 return;
629 // Perform PGO instrumentation.
630 MPM.addPass(PGOInstrumentationGen(IsCS));
631 // Add the profile lowering pass.
632 InstrProfOptions Options;
633 if (!ProfileFile.empty())
634 Options.InstrProfileOutput = ProfileFile;
635 // Do not do counter promotion at O0.
636 Options.DoCounterPromotion = false;
637 Options.UseBFIInPromotion = IsCS;
638 MPM.addPass(InstrProfiling(Options, IsCS));
641 static InlineParams
642 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) {
643 auto O3 = PassBuilder::O3;
644 unsigned OptLevel = Level > O3 ? 2 : Level;
645 unsigned SizeLevel = Level > O3 ? Level - O3 : 0;
646 return getInlineParams(OptLevel, SizeLevel);
649 ModulePassManager
650 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
651 ThinLTOPhase Phase,
652 bool DebugLogging) {
653 ModulePassManager MPM(DebugLogging);
655 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
657 // In ThinLTO mode, when flattened profile is used, all the available
658 // profile information will be annotated in PreLink phase so there is
659 // no need to load the profile again in PostLink.
660 bool LoadSampleProfile =
661 HasSampleProfile &&
662 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink);
664 // During the ThinLTO backend phase we perform early indirect call promotion
665 // here, before globalopt. Otherwise imported available_externally functions
666 // look unreferenced and are removed. If we are going to load the sample
667 // profile then defer until later.
668 // TODO: See if we can move later and consolidate with the location where
669 // we perform ICP when we are loading a sample profile.
670 // TODO: We pass HasSampleProfile (whether there was a sample profile file
671 // passed to the compile) to the SamplePGO flag of ICP. This is used to
672 // determine whether the new direct calls are annotated with prof metadata.
673 // Ideally this should be determined from whether the IR is annotated with
674 // sample profile, and not whether the a sample profile was provided on the
675 // command line. E.g. for flattened profiles where we will not be reloading
676 // the sample profile in the ThinLTO backend, we ideally shouldn't have to
677 // provide the sample profile file.
678 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile)
679 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
681 // Do basic inference of function attributes from known properties of system
682 // libraries and other oracles.
683 MPM.addPass(InferFunctionAttrsPass());
685 // Create an early function pass manager to cleanup the output of the
686 // frontend.
687 FunctionPassManager EarlyFPM(DebugLogging);
688 EarlyFPM.addPass(SimplifyCFGPass());
689 EarlyFPM.addPass(SROA());
690 EarlyFPM.addPass(EarlyCSEPass());
691 EarlyFPM.addPass(LowerExpectIntrinsicPass());
692 if (Level == O3)
693 EarlyFPM.addPass(CallSiteSplittingPass());
695 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
696 // to convert bitcast to direct calls so that they can be inlined during the
697 // profile annotation prepration step.
698 // More details about SamplePGO design can be found in:
699 // https://research.google.com/pubs/pub45290.html
700 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
701 if (LoadSampleProfile)
702 EarlyFPM.addPass(InstCombinePass());
703 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
705 if (LoadSampleProfile) {
706 // Annotate sample profile right after early FPM to ensure freshness of
707 // the debug info.
708 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
709 PGOOpt->ProfileRemappingFile,
710 Phase == ThinLTOPhase::PreLink));
711 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
712 // RequireAnalysisPass for PSI before subsequent non-module passes.
713 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
714 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard
715 // for the profile annotation to be accurate in the ThinLTO backend.
716 if (Phase != ThinLTOPhase::PreLink)
717 // We perform early indirect call promotion here, before globalopt.
718 // This is important for the ThinLTO backend phase because otherwise
719 // imported available_externally functions look unreferenced and are
720 // removed.
721 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink,
722 true /* SamplePGO */));
725 // Interprocedural constant propagation now that basic cleanup has occurred
726 // and prior to optimizing globals.
727 // FIXME: This position in the pipeline hasn't been carefully considered in
728 // years, it should be re-analyzed.
729 MPM.addPass(IPSCCPPass());
731 // Attach metadata to indirect call sites indicating the set of functions
732 // they may target at run-time. This should follow IPSCCP.
733 MPM.addPass(CalledValuePropagationPass());
735 // Optimize globals to try and fold them into constants.
736 MPM.addPass(GlobalOptPass());
738 // Promote any localized globals to SSA registers.
739 // FIXME: Should this instead by a run of SROA?
740 // FIXME: We should probably run instcombine and simplify-cfg afterward to
741 // delete control flows that are dead once globals have been folded to
742 // constants.
743 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
745 // Remove any dead arguments exposed by cleanups and constand folding
746 // globals.
747 MPM.addPass(DeadArgumentEliminationPass());
749 // Create a small function pass pipeline to cleanup after all the global
750 // optimizations.
751 FunctionPassManager GlobalCleanupPM(DebugLogging);
752 GlobalCleanupPM.addPass(InstCombinePass());
753 invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
755 GlobalCleanupPM.addPass(SimplifyCFGPass());
756 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
758 // Add all the requested passes for instrumentation PGO, if requested.
759 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
760 (PGOOpt->Action == PGOOptions::IRInstr ||
761 PGOOpt->Action == PGOOptions::IRUse)) {
762 addPGOInstrPasses(MPM, DebugLogging, Level,
763 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
764 /* IsCS */ false, PGOOpt->ProfileFile,
765 PGOOpt->ProfileRemappingFile);
766 MPM.addPass(PGOIndirectCallPromotion(false, false));
768 if (PGOOpt && Phase != ThinLTOPhase::PostLink &&
769 PGOOpt->CSAction == PGOOptions::CSIRInstr)
770 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
772 // Synthesize function entry counts for non-PGO compilation.
773 if (EnableSyntheticCounts && !PGOOpt)
774 MPM.addPass(SyntheticCountsPropagation());
776 // Require the GlobalsAA analysis for the module so we can query it within
777 // the CGSCC pipeline.
778 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
780 // Require the ProfileSummaryAnalysis for the module so we can query it within
781 // the inliner pass.
782 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
784 // Now begin the main postorder CGSCC pipeline.
785 // FIXME: The current CGSCC pipeline has its origins in the legacy pass
786 // manager and trying to emulate its precise behavior. Much of this doesn't
787 // make a lot of sense and we should revisit the core CGSCC structure.
788 CGSCCPassManager MainCGPipeline(DebugLogging);
790 // Note: historically, the PruneEH pass was run first to deduce nounwind and
791 // generally clean up exception handling overhead. It isn't clear this is
792 // valuable as the inliner doesn't currently care whether it is inlining an
793 // invoke or a call.
795 // Run the inliner first. The theory is that we are walking bottom-up and so
796 // the callees have already been fully optimized, and we want to inline them
797 // into the callers so that our optimizations can reflect that.
798 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO
799 // because it makes profile annotation in the backend inaccurate.
800 InlineParams IP = getInlineParamsFromOptLevel(Level);
801 if (Phase == ThinLTOPhase::PreLink && PGOOpt &&
802 PGOOpt->Action == PGOOptions::SampleUse)
803 IP.HotCallSiteThreshold = 0;
804 MainCGPipeline.addPass(InlinerPass(IP));
806 // Now deduce any function attributes based in the current code.
807 MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
809 // When at O3 add argument promotion to the pass pipeline.
810 // FIXME: It isn't at all clear why this should be limited to O3.
811 if (Level == O3)
812 MainCGPipeline.addPass(ArgumentPromotionPass());
814 // Lastly, add the core function simplification pipeline nested inside the
815 // CGSCC walk.
816 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
817 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging)));
819 for (auto &C : CGSCCOptimizerLateEPCallbacks)
820 C(MainCGPipeline, Level);
822 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
823 // to detect when we devirtualize indirect calls and iterate the SCC passes
824 // in that case to try and catch knock-on inlining or function attrs
825 // opportunities. Then we add it to the module pipeline by walking the SCCs
826 // in postorder (or bottom-up).
827 MPM.addPass(
828 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
829 std::move(MainCGPipeline), MaxDevirtIterations)));
831 return MPM;
834 ModulePassManager PassBuilder::buildModuleOptimizationPipeline(
835 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) {
836 ModulePassManager MPM(DebugLogging);
838 // Optimize globals now that the module is fully simplified.
839 MPM.addPass(GlobalOptPass());
840 MPM.addPass(GlobalDCEPass());
842 // Run partial inlining pass to partially inline functions that have
843 // large bodies.
844 if (RunPartialInlining)
845 MPM.addPass(PartialInlinerPass());
847 // Remove avail extern fns and globals definitions since we aren't compiling
848 // an object file for later LTO. For LTO we want to preserve these so they
849 // are eligible for inlining at link-time. Note if they are unreferenced they
850 // will be removed by GlobalDCE later, so this only impacts referenced
851 // available externally globals. Eventually they will be suppressed during
852 // codegen, but eliminating here enables more opportunity for GlobalDCE as it
853 // may make globals referenced by available external functions dead and saves
854 // running remaining passes on the eliminated functions. These should be
855 // preserved during prelinking for link-time inlining decisions.
856 if (!LTOPreLink)
857 MPM.addPass(EliminateAvailableExternallyPass());
859 if (EnableOrderFileInstrumentation)
860 MPM.addPass(InstrOrderFilePass());
862 // Do RPO function attribute inference across the module to forward-propagate
863 // attributes where applicable.
864 // FIXME: Is this really an optimization rather than a canonicalization?
865 MPM.addPass(ReversePostOrderFunctionAttrsPass());
867 // Do a post inline PGO instrumentation and use pass. This is a context
868 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
869 // cross-module inline has not been done yet. The context sensitive
870 // instrumentation is after all the inlines are done.
871 if (!LTOPreLink && PGOOpt) {
872 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
873 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
874 /* IsCS */ true, PGOOpt->CSProfileGenFile,
875 PGOOpt->ProfileRemappingFile);
876 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
877 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
878 /* IsCS */ true, PGOOpt->ProfileFile,
879 PGOOpt->ProfileRemappingFile);
882 // Re-require GloblasAA here prior to function passes. This is particularly
883 // useful as the above will have inlined, DCE'ed, and function-attr
884 // propagated everything. We should at this point have a reasonably minimal
885 // and richly annotated call graph. By computing aliasing and mod/ref
886 // information for all local globals here, the late loop passes and notably
887 // the vectorizer will be able to use them to help recognize vectorizable
888 // memory operations.
889 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
891 FunctionPassManager OptimizePM(DebugLogging);
892 OptimizePM.addPass(Float2IntPass());
893 // FIXME: We need to run some loop optimizations to re-rotate loops after
894 // simplify-cfg and others undo their rotation.
896 // Optimize the loop execution. These passes operate on entire loop nests
897 // rather than on each loop in an inside-out manner, and so they are actually
898 // function passes.
900 for (auto &C : VectorizerStartEPCallbacks)
901 C(OptimizePM, Level);
903 // First rotate loops that may have been un-rotated by prior passes.
904 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
905 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging));
907 // Distribute loops to allow partial vectorization. I.e. isolate dependences
908 // into separate loop that would otherwise inhibit vectorization. This is
909 // currently only performed for loops marked with the metadata
910 // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
911 OptimizePM.addPass(LoopDistributePass());
913 // Now run the core loop vectorizer.
914 OptimizePM.addPass(LoopVectorizePass(
915 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
917 // Eliminate loads by forwarding stores from the previous iteration to loads
918 // of the current iteration.
919 OptimizePM.addPass(LoopLoadEliminationPass());
921 // Cleanup after the loop optimization passes.
922 OptimizePM.addPass(InstCombinePass());
924 // Now that we've formed fast to execute loop structures, we do further
925 // optimizations. These are run afterward as they might block doing complex
926 // analyses and transforms such as what are needed for loop vectorization.
928 // Cleanup after loop vectorization, etc. Simplification passes like CVP and
929 // GVN, loop transforms, and others have already run, so it's now better to
930 // convert to more optimized IR using more aggressive simplify CFG options.
931 // The extra sinking transform can create larger basic blocks, so do this
932 // before SLP vectorization.
933 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions().
934 forwardSwitchCondToPhi(true).
935 convertSwitchToLookupTable(true).
936 needCanonicalLoops(false).
937 sinkCommonInsts(true)));
939 // Optimize parallel scalar instruction chains into SIMD instructions.
940 if (PTO.SLPVectorization)
941 OptimizePM.addPass(SLPVectorizerPass());
943 OptimizePM.addPass(InstCombinePass());
945 // Unroll small loops to hide loop backedge latency and saturate any parallel
946 // execution resources of an out-of-order processor. We also then need to
947 // clean up redundancies and loop invariant code.
948 // FIXME: It would be really good to use a loop-integrated instruction
949 // combiner for cleanup here so that the unrolling and LICM can be pipelined
950 // across the loop nests.
951 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
952 if (EnableUnrollAndJam) {
953 OptimizePM.addPass(
954 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level)));
956 if (PTO.LoopUnrolling)
957 OptimizePM.addPass(LoopUnrollPass(
958 LoopUnrollOptions(Level, false, PTO.ForgetAllSCEVInLoopUnroll)));
959 OptimizePM.addPass(WarnMissedTransformationsPass());
960 OptimizePM.addPass(InstCombinePass());
961 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
962 OptimizePM.addPass(createFunctionToLoopPassAdaptor(
963 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap),
964 EnableMSSALoopDependency, DebugLogging));
966 // Now that we've vectorized and unrolled loops, we may have more refined
967 // alignment information, try to re-derive it here.
968 OptimizePM.addPass(AlignmentFromAssumptionsPass());
970 // Split out cold code. Splitting is done late to avoid hiding context from
971 // other optimizations and inadvertently regressing performance. The tradeoff
972 // is that this has a higher code size cost than splitting early.
973 if (EnableHotColdSplit && !LTOPreLink)
974 MPM.addPass(HotColdSplittingPass());
976 // LoopSink pass sinks instructions hoisted by LICM, which serves as a
977 // canonicalization pass that enables other optimizations. As a result,
978 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
979 // result too early.
980 OptimizePM.addPass(LoopSinkPass());
982 // And finally clean up LCSSA form before generating code.
983 OptimizePM.addPass(InstSimplifyPass());
985 // This hoists/decomposes div/rem ops. It should run after other sink/hoist
986 // passes to avoid re-sinking, but before SimplifyCFG because it can allow
987 // flattening of blocks.
988 OptimizePM.addPass(DivRemPairsPass());
990 // LoopSink (and other loop passes since the last simplifyCFG) might have
991 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
992 OptimizePM.addPass(SimplifyCFGPass());
994 // Optimize PHIs by speculating around them when profitable. Note that this
995 // pass needs to be run after any PRE or similar pass as it is essentially
996 // inserting redundancies into the program. This even includes SimplifyCFG.
997 OptimizePM.addPass(SpeculateAroundPHIsPass());
999 for (auto &C : OptimizerLastEPCallbacks)
1000 C(OptimizePM, Level);
1002 // Add the core optimizing pipeline.
1003 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
1005 MPM.addPass(CGProfilePass());
1007 // Now we need to do some global optimization transforms.
1008 // FIXME: It would seem like these should come first in the optimization
1009 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1010 // ordering here.
1011 MPM.addPass(GlobalDCEPass());
1012 MPM.addPass(ConstantMergePass());
1014 return MPM;
1017 ModulePassManager
1018 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1019 bool DebugLogging, bool LTOPreLink) {
1020 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1022 ModulePassManager MPM(DebugLogging);
1024 // Force any function attributes we want the rest of the pipeline to observe.
1025 MPM.addPass(ForceFunctionAttrsPass());
1027 // Apply module pipeline start EP callback.
1028 for (auto &C : PipelineStartEPCallbacks)
1029 C(MPM);
1031 if (PGOOpt && PGOOpt->SamplePGOSupport)
1032 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1034 // Add the core simplification pipeline.
1035 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None,
1036 DebugLogging));
1038 // Now add the optimization pipeline.
1039 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink));
1041 return MPM;
1044 ModulePassManager
1045 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1046 bool DebugLogging) {
1047 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1049 ModulePassManager MPM(DebugLogging);
1051 // Force any function attributes we want the rest of the pipeline to observe.
1052 MPM.addPass(ForceFunctionAttrsPass());
1054 if (PGOOpt && PGOOpt->SamplePGOSupport)
1055 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1057 // Apply module pipeline start EP callback.
1058 for (auto &C : PipelineStartEPCallbacks)
1059 C(MPM);
1061 // If we are planning to perform ThinLTO later, we don't bloat the code with
1062 // unrolling/vectorization/... now. Just simplify the module as much as we
1063 // can.
1064 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink,
1065 DebugLogging));
1067 // Run partial inlining pass to partially inline functions that have
1068 // large bodies.
1069 // FIXME: It isn't clear whether this is really the right place to run this
1070 // in ThinLTO. Because there is another canonicalization and simplification
1071 // phase that will run after the thin link, running this here ends up with
1072 // less information than will be available later and it may grow functions in
1073 // ways that aren't beneficial.
1074 if (RunPartialInlining)
1075 MPM.addPass(PartialInlinerPass());
1077 // Reduce the size of the IR as much as possible.
1078 MPM.addPass(GlobalOptPass());
1080 return MPM;
1083 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1084 OptimizationLevel Level, bool DebugLogging,
1085 const ModuleSummaryIndex *ImportSummary) {
1086 ModulePassManager MPM(DebugLogging);
1088 if (ImportSummary) {
1089 // These passes import type identifier resolutions for whole-program
1090 // devirtualization and CFI. They must run early because other passes may
1091 // disturb the specific instruction patterns that these passes look for,
1092 // creating dependencies on resolutions that may not appear in the summary.
1094 // For example, GVN may transform the pattern assume(type.test) appearing in
1095 // two basic blocks into assume(phi(type.test, type.test)), which would
1096 // transform a dependency on a WPD resolution into a dependency on a type
1097 // identifier resolution for CFI.
1099 // Also, WPD has access to more precise information than ICP and can
1100 // devirtualize more effectively, so it should operate on the IR first.
1102 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1103 // metadata and intrinsics.
1104 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1105 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1108 if (Level == O0)
1109 return MPM;
1111 // Force any function attributes we want the rest of the pipeline to observe.
1112 MPM.addPass(ForceFunctionAttrsPass());
1114 // Add the core simplification pipeline.
1115 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink,
1116 DebugLogging));
1118 // Now add the optimization pipeline.
1119 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
1121 return MPM;
1124 ModulePassManager
1125 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
1126 bool DebugLogging) {
1127 assert(Level != O0 && "Must request optimizations for the default pipeline!");
1128 // FIXME: We should use a customized pre-link pipeline!
1129 return buildPerModuleDefaultPipeline(Level, DebugLogging,
1130 /* LTOPreLink */true);
1133 ModulePassManager
1134 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging,
1135 ModuleSummaryIndex *ExportSummary) {
1136 ModulePassManager MPM(DebugLogging);
1138 if (Level == O0) {
1139 // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1140 // metadata and intrinsics.
1141 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1142 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1143 return MPM;
1146 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1147 // Load sample profile before running the LTO optimization pipeline.
1148 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1149 PGOOpt->ProfileRemappingFile,
1150 false /* ThinLTOPhase::PreLink */));
1151 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1152 // RequireAnalysisPass for PSI before subsequent non-module passes.
1153 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1156 // Remove unused virtual tables to improve the quality of code generated by
1157 // whole-program devirtualization and bitset lowering.
1158 MPM.addPass(GlobalDCEPass());
1160 // Force any function attributes we want the rest of the pipeline to observe.
1161 MPM.addPass(ForceFunctionAttrsPass());
1163 // Do basic inference of function attributes from known properties of system
1164 // libraries and other oracles.
1165 MPM.addPass(InferFunctionAttrsPass());
1167 if (Level > 1) {
1168 FunctionPassManager EarlyFPM(DebugLogging);
1169 EarlyFPM.addPass(CallSiteSplittingPass());
1170 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
1172 // Indirect call promotion. This should promote all the targets that are
1173 // left by the earlier promotion pass that promotes intra-module targets.
1174 // This two-step promotion is to save the compile time. For LTO, it should
1175 // produce the same result as if we only do promotion here.
1176 MPM.addPass(PGOIndirectCallPromotion(
1177 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1178 // Propagate constants at call sites into the functions they call. This
1179 // opens opportunities for globalopt (and inlining) by substituting function
1180 // pointers passed as arguments to direct uses of functions.
1181 MPM.addPass(IPSCCPPass());
1183 // Attach metadata to indirect call sites indicating the set of functions
1184 // they may target at run-time. This should follow IPSCCP.
1185 MPM.addPass(CalledValuePropagationPass());
1188 // Now deduce any function attributes based in the current code.
1189 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1190 PostOrderFunctionAttrsPass()));
1192 // Do RPO function attribute inference across the module to forward-propagate
1193 // attributes where applicable.
1194 // FIXME: Is this really an optimization rather than a canonicalization?
1195 MPM.addPass(ReversePostOrderFunctionAttrsPass());
1197 // Use in-range annotations on GEP indices to split globals where beneficial.
1198 MPM.addPass(GlobalSplitPass());
1200 // Run whole program optimization of virtual call when the list of callees
1201 // is fixed.
1202 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1204 // Stop here at -O1.
1205 if (Level == 1) {
1206 // The LowerTypeTestsPass needs to run to lower type metadata and the
1207 // type.test intrinsics. The pass does nothing if CFI is disabled.
1208 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1209 return MPM;
1212 // Optimize globals to try and fold them into constants.
1213 MPM.addPass(GlobalOptPass());
1215 // Promote any localized globals to SSA registers.
1216 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1218 // Linking modules together can lead to duplicate global constant, only
1219 // keep one copy of each constant.
1220 MPM.addPass(ConstantMergePass());
1222 // Remove unused arguments from functions.
1223 MPM.addPass(DeadArgumentEliminationPass());
1225 // Reduce the code after globalopt and ipsccp. Both can open up significant
1226 // simplification opportunities, and both can propagate functions through
1227 // function pointers. When this happens, we often have to resolve varargs
1228 // calls, etc, so let instcombine do this.
1229 FunctionPassManager PeepholeFPM(DebugLogging);
1230 if (Level == O3)
1231 PeepholeFPM.addPass(AggressiveInstCombinePass());
1232 PeepholeFPM.addPass(InstCombinePass());
1233 invokePeepholeEPCallbacks(PeepholeFPM, Level);
1235 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM)));
1237 // Note: historically, the PruneEH pass was run first to deduce nounwind and
1238 // generally clean up exception handling overhead. It isn't clear this is
1239 // valuable as the inliner doesn't currently care whether it is inlining an
1240 // invoke or a call.
1241 // Run the inliner now.
1242 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1243 InlinerPass(getInlineParamsFromOptLevel(Level))));
1245 // Optimize globals again after we ran the inliner.
1246 MPM.addPass(GlobalOptPass());
1248 // Garbage collect dead functions.
1249 // FIXME: Add ArgumentPromotion pass after once it's ported.
1250 MPM.addPass(GlobalDCEPass());
1252 FunctionPassManager FPM(DebugLogging);
1253 // The IPO Passes may leave cruft around. Clean up after them.
1254 FPM.addPass(InstCombinePass());
1255 invokePeepholeEPCallbacks(FPM, Level);
1257 FPM.addPass(JumpThreadingPass());
1259 // Do a post inline PGO instrumentation and use pass. This is a context
1260 // sensitive PGO pass.
1261 if (PGOOpt) {
1262 if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1263 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true,
1264 /* IsCS */ true, PGOOpt->CSProfileGenFile,
1265 PGOOpt->ProfileRemappingFile);
1266 else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1267 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false,
1268 /* IsCS */ true, PGOOpt->ProfileFile,
1269 PGOOpt->ProfileRemappingFile);
1272 // Break up allocas
1273 FPM.addPass(SROA());
1275 // LTO provides additional opportunities for tailcall elimination due to
1276 // link-time inlining, and visibility of nocapture attribute.
1277 FPM.addPass(TailCallElimPass());
1279 // Run a few AA driver optimizations here and now to cleanup the code.
1280 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1282 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
1283 PostOrderFunctionAttrsPass()));
1284 // FIXME: here we run IP alias analysis in the legacy PM.
1286 FunctionPassManager MainFPM;
1288 // FIXME: once we fix LoopPass Manager, add LICM here.
1289 // FIXME: once we provide support for enabling MLSM, add it here.
1290 if (RunNewGVN)
1291 MainFPM.addPass(NewGVNPass());
1292 else
1293 MainFPM.addPass(GVN());
1295 // Remove dead memcpy()'s.
1296 MainFPM.addPass(MemCpyOptPass());
1298 // Nuke dead stores.
1299 MainFPM.addPass(DSEPass());
1301 // FIXME: at this point, we run a bunch of loop passes:
1302 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll,
1303 // loopVectorize. Enable them once the remaining issue with LPM
1304 // are sorted out.
1306 MainFPM.addPass(InstCombinePass());
1307 MainFPM.addPass(SimplifyCFGPass());
1308 MainFPM.addPass(SCCPPass());
1309 MainFPM.addPass(InstCombinePass());
1310 MainFPM.addPass(BDCEPass());
1312 // FIXME: We may want to run SLPVectorizer here.
1313 // After vectorization, assume intrinsics may tell us more
1314 // about pointer alignments.
1315 #if 0
1316 MainFPM.add(AlignmentFromAssumptionsPass());
1317 #endif
1319 // FIXME: Conditionally run LoadCombine here, after it's ported
1320 // (in case we still have this pass, given its questionable usefulness).
1322 MainFPM.addPass(InstCombinePass());
1323 invokePeepholeEPCallbacks(MainFPM, Level);
1324 MainFPM.addPass(JumpThreadingPass());
1325 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
1327 // Create a function that performs CFI checks for cross-DSO calls with
1328 // targets in the current module.
1329 MPM.addPass(CrossDSOCFIPass());
1331 // Lower type metadata and the type.test intrinsic. This pass supports
1332 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1333 // to be run at link time if CFI is enabled. This pass does nothing if
1334 // CFI is disabled.
1335 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1337 // Enable splitting late in the FullLTO post-link pipeline. This is done in
1338 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1339 if (EnableHotColdSplit)
1340 MPM.addPass(HotColdSplittingPass());
1342 // Add late LTO optimization passes.
1343 // Delete basic blocks, which optimization passes may have killed.
1344 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
1346 // Drop bodies of available eternally objects to improve GlobalDCE.
1347 MPM.addPass(EliminateAvailableExternallyPass());
1349 // Now that we have optimized the program, discard unreachable functions.
1350 MPM.addPass(GlobalDCEPass());
1352 // FIXME: Maybe enable MergeFuncs conditionally after it's ported.
1353 return MPM;
1356 AAManager PassBuilder::buildDefaultAAPipeline() {
1357 AAManager AA;
1359 // The order in which these are registered determines their priority when
1360 // being queried.
1362 // First we register the basic alias analysis that provides the majority of
1363 // per-function local AA logic. This is a stateless, on-demand local set of
1364 // AA techniques.
1365 AA.registerFunctionAnalysis<BasicAA>();
1367 // Next we query fast, specialized alias analyses that wrap IR-embedded
1368 // information about aliasing.
1369 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1370 AA.registerFunctionAnalysis<TypeBasedAA>();
1372 // Add support for querying global aliasing information when available.
1373 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1374 // analysis, all that the `AAManager` can do is query for any *cached*
1375 // results from `GlobalsAA` through a readonly proxy.
1376 AA.registerModuleAnalysis<GlobalsAA>();
1378 return AA;
1381 static Optional<int> parseRepeatPassName(StringRef Name) {
1382 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
1383 return None;
1384 int Count;
1385 if (Name.getAsInteger(0, Count) || Count <= 0)
1386 return None;
1387 return Count;
1390 static Optional<int> parseDevirtPassName(StringRef Name) {
1391 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
1392 return None;
1393 int Count;
1394 if (Name.getAsInteger(0, Count) || Count <= 0)
1395 return None;
1396 return Count;
1399 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
1400 if (!Name.consume_front(PassName))
1401 return false;
1402 // normal pass name w/o parameters == default parameters
1403 if (Name.empty())
1404 return true;
1405 return Name.startswith("<") && Name.endswith(">");
1408 namespace {
1410 /// This performs customized parsing of pass name with parameters.
1412 /// We do not need parametrization of passes in textual pipeline very often,
1413 /// yet on a rare occasion ability to specify parameters right there can be
1414 /// useful.
1416 /// \p Name - parameterized specification of a pass from a textual pipeline
1417 /// is a string in a form of :
1418 /// PassName '<' parameter-list '>'
1420 /// Parameter list is being parsed by the parser callable argument, \p Parser,
1421 /// It takes a string-ref of parameters and returns either StringError or a
1422 /// parameter list in a form of a custom parameters type, all wrapped into
1423 /// Expected<> template class.
1425 template <typename ParametersParseCallableT>
1426 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
1427 StringRef PassName) -> decltype(Parser(StringRef{})) {
1428 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
1430 StringRef Params = Name;
1431 if (!Params.consume_front(PassName)) {
1432 assert(false &&
1433 "unable to strip pass name from parametrized pass specification");
1435 if (Params.empty())
1436 return ParametersT{};
1437 if (!Params.consume_front("<") || !Params.consume_back(">")) {
1438 assert(false && "invalid format for parametrized pass name");
1441 Expected<ParametersT> Result = Parser(Params);
1442 assert((Result || Result.template errorIsA<StringError>()) &&
1443 "Pass parameter parser can only return StringErrors.");
1444 return std::move(Result);
1447 /// Parser of parameters for LoopUnroll pass.
1448 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
1449 LoopUnrollOptions UnrollOpts;
1450 while (!Params.empty()) {
1451 StringRef ParamName;
1452 std::tie(ParamName, Params) = Params.split(';');
1453 int OptLevel = StringSwitch<int>(ParamName)
1454 .Case("O0", 0)
1455 .Case("O1", 1)
1456 .Case("O2", 2)
1457 .Case("O3", 3)
1458 .Default(-1);
1459 if (OptLevel >= 0) {
1460 UnrollOpts.setOptLevel(OptLevel);
1461 continue;
1463 if (ParamName.consume_front("full-unroll-max=")) {
1464 int Count;
1465 if (ParamName.getAsInteger(0, Count))
1466 return make_error<StringError>(
1467 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1468 inconvertibleErrorCode());
1469 UnrollOpts.setFullUnrollMaxCount(Count);
1470 continue;
1473 bool Enable = !ParamName.consume_front("no-");
1474 if (ParamName == "partial") {
1475 UnrollOpts.setPartial(Enable);
1476 } else if (ParamName == "peeling") {
1477 UnrollOpts.setPeeling(Enable);
1478 } else if (ParamName == "profile-peeling") {
1479 UnrollOpts.setProfileBasedPeeling(Enable);
1480 } else if (ParamName == "runtime") {
1481 UnrollOpts.setRuntime(Enable);
1482 } else if (ParamName == "upperbound") {
1483 UnrollOpts.setUpperBound(Enable);
1484 } else {
1485 return make_error<StringError>(
1486 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
1487 inconvertibleErrorCode());
1490 return UnrollOpts;
1493 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
1494 MemorySanitizerOptions Result;
1495 while (!Params.empty()) {
1496 StringRef ParamName;
1497 std::tie(ParamName, Params) = Params.split(';');
1499 if (ParamName == "recover") {
1500 Result.Recover = true;
1501 } else if (ParamName == "kernel") {
1502 Result.Kernel = true;
1503 } else if (ParamName.consume_front("track-origins=")) {
1504 if (ParamName.getAsInteger(0, Result.TrackOrigins))
1505 return make_error<StringError>(
1506 formatv("invalid argument to MemorySanitizer pass track-origins "
1507 "parameter: '{0}' ",
1508 ParamName)
1509 .str(),
1510 inconvertibleErrorCode());
1511 } else {
1512 return make_error<StringError>(
1513 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
1514 .str(),
1515 inconvertibleErrorCode());
1518 return Result;
1521 /// Parser of parameters for SimplifyCFG pass.
1522 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
1523 SimplifyCFGOptions Result;
1524 while (!Params.empty()) {
1525 StringRef ParamName;
1526 std::tie(ParamName, Params) = Params.split(';');
1528 bool Enable = !ParamName.consume_front("no-");
1529 if (ParamName == "forward-switch-cond") {
1530 Result.forwardSwitchCondToPhi(Enable);
1531 } else if (ParamName == "switch-to-lookup") {
1532 Result.convertSwitchToLookupTable(Enable);
1533 } else if (ParamName == "keep-loops") {
1534 Result.needCanonicalLoops(Enable);
1535 } else if (ParamName == "sink-common-insts") {
1536 Result.sinkCommonInsts(Enable);
1537 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
1538 APInt BonusInstThreshold;
1539 if (ParamName.getAsInteger(0, BonusInstThreshold))
1540 return make_error<StringError>(
1541 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
1542 "parameter: '{0}' ",
1543 ParamName).str(),
1544 inconvertibleErrorCode());
1545 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
1546 } else {
1547 return make_error<StringError>(
1548 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
1549 inconvertibleErrorCode());
1552 return Result;
1555 /// Parser of parameters for LoopVectorize pass.
1556 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
1557 LoopVectorizeOptions Opts;
1558 while (!Params.empty()) {
1559 StringRef ParamName;
1560 std::tie(ParamName, Params) = Params.split(';');
1562 bool Enable = !ParamName.consume_front("no-");
1563 if (ParamName == "interleave-forced-only") {
1564 Opts.setInterleaveOnlyWhenForced(Enable);
1565 } else if (ParamName == "vectorize-forced-only") {
1566 Opts.setVectorizeOnlyWhenForced(Enable);
1567 } else {
1568 return make_error<StringError>(
1569 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
1570 inconvertibleErrorCode());
1573 return Opts;
1576 Expected<bool> parseLoopUnswitchOptions(StringRef Params) {
1577 bool Result = false;
1578 while (!Params.empty()) {
1579 StringRef ParamName;
1580 std::tie(ParamName, Params) = Params.split(';');
1582 bool Enable = !ParamName.consume_front("no-");
1583 if (ParamName == "nontrivial") {
1584 Result = Enable;
1585 } else {
1586 return make_error<StringError>(
1587 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
1588 .str(),
1589 inconvertibleErrorCode());
1592 return Result;
1595 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
1596 bool Result = false;
1597 while (!Params.empty()) {
1598 StringRef ParamName;
1599 std::tie(ParamName, Params) = Params.split(';');
1601 bool Enable = !ParamName.consume_front("no-");
1602 if (ParamName == "split-footer-bb") {
1603 Result = Enable;
1604 } else {
1605 return make_error<StringError>(
1606 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
1607 ParamName)
1608 .str(),
1609 inconvertibleErrorCode());
1612 return Result;
1614 } // namespace
1616 /// Tests whether a pass name starts with a valid prefix for a default pipeline
1617 /// alias.
1618 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
1619 return Name.startswith("default") || Name.startswith("thinlto") ||
1620 Name.startswith("lto");
1623 /// Tests whether registered callbacks will accept a given pass name.
1625 /// When parsing a pipeline text, the type of the outermost pipeline may be
1626 /// omitted, in which case the type is automatically determined from the first
1627 /// pass name in the text. This may be a name that is handled through one of the
1628 /// callbacks. We check this through the oridinary parsing callbacks by setting
1629 /// up a dummy PassManager in order to not force the client to also handle this
1630 /// type of query.
1631 template <typename PassManagerT, typename CallbacksT>
1632 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
1633 if (!Callbacks.empty()) {
1634 PassManagerT DummyPM;
1635 for (auto &CB : Callbacks)
1636 if (CB(Name, DummyPM, {}))
1637 return true;
1639 return false;
1642 template <typename CallbacksT>
1643 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
1644 // Manually handle aliases for pre-configured pipeline fragments.
1645 if (startsWithDefaultPipelineAliasPrefix(Name))
1646 return DefaultAliasRegex.match(Name);
1648 // Explicitly handle pass manager names.
1649 if (Name == "module")
1650 return true;
1651 if (Name == "cgscc")
1652 return true;
1653 if (Name == "function")
1654 return true;
1656 // Explicitly handle custom-parsed pass names.
1657 if (parseRepeatPassName(Name))
1658 return true;
1660 #define MODULE_PASS(NAME, CREATE_PASS) \
1661 if (Name == NAME) \
1662 return true;
1663 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1664 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1665 return true;
1666 #include "PassRegistry.def"
1668 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
1671 template <typename CallbacksT>
1672 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
1673 // Explicitly handle pass manager names.
1674 if (Name == "cgscc")
1675 return true;
1676 if (Name == "function")
1677 return true;
1679 // Explicitly handle custom-parsed pass names.
1680 if (parseRepeatPassName(Name))
1681 return true;
1682 if (parseDevirtPassName(Name))
1683 return true;
1685 #define CGSCC_PASS(NAME, CREATE_PASS) \
1686 if (Name == NAME) \
1687 return true;
1688 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1689 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1690 return true;
1691 #include "PassRegistry.def"
1693 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
1696 template <typename CallbacksT>
1697 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
1698 // Explicitly handle pass manager names.
1699 if (Name == "function")
1700 return true;
1701 if (Name == "loop" || Name == "loop-mssa")
1702 return true;
1704 // Explicitly handle custom-parsed pass names.
1705 if (parseRepeatPassName(Name))
1706 return true;
1708 #define FUNCTION_PASS(NAME, CREATE_PASS) \
1709 if (Name == NAME) \
1710 return true;
1711 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1712 if (checkParametrizedPassName(Name, NAME)) \
1713 return true;
1714 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1715 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1716 return true;
1717 #include "PassRegistry.def"
1719 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
1722 template <typename CallbacksT>
1723 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) {
1724 // Explicitly handle pass manager names.
1725 if (Name == "loop" || Name == "loop-mssa")
1726 return true;
1728 // Explicitly handle custom-parsed pass names.
1729 if (parseRepeatPassName(Name))
1730 return true;
1732 #define LOOP_PASS(NAME, CREATE_PASS) \
1733 if (Name == NAME) \
1734 return true;
1735 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
1736 if (checkParametrizedPassName(Name, NAME)) \
1737 return true;
1738 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1739 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1740 return true;
1741 #include "PassRegistry.def"
1743 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1746 Optional<std::vector<PassBuilder::PipelineElement>>
1747 PassBuilder::parsePipelineText(StringRef Text) {
1748 std::vector<PipelineElement> ResultPipeline;
1750 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1751 &ResultPipeline};
1752 for (;;) {
1753 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1754 size_t Pos = Text.find_first_of(",()");
1755 Pipeline.push_back({Text.substr(0, Pos), {}});
1757 // If we have a single terminating name, we're done.
1758 if (Pos == Text.npos)
1759 break;
1761 char Sep = Text[Pos];
1762 Text = Text.substr(Pos + 1);
1763 if (Sep == ',')
1764 // Just a name ending in a comma, continue.
1765 continue;
1767 if (Sep == '(') {
1768 // Push the inner pipeline onto the stack to continue processing.
1769 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1770 continue;
1773 assert(Sep == ')' && "Bogus separator!");
1774 // When handling the close parenthesis, we greedily consume them to avoid
1775 // empty strings in the pipeline.
1776 do {
1777 // If we try to pop the outer pipeline we have unbalanced parentheses.
1778 if (PipelineStack.size() == 1)
1779 return None;
1781 PipelineStack.pop_back();
1782 } while (Text.consume_front(")"));
1784 // Check if we've finished parsing.
1785 if (Text.empty())
1786 break;
1788 // Otherwise, the end of an inner pipeline always has to be followed by
1789 // a comma, and then we can continue.
1790 if (!Text.consume_front(","))
1791 return None;
1794 if (PipelineStack.size() > 1)
1795 // Unbalanced paretheses.
1796 return None;
1798 assert(PipelineStack.back() == &ResultPipeline &&
1799 "Wrong pipeline at the bottom of the stack!");
1800 return {std::move(ResultPipeline)};
1803 Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1804 const PipelineElement &E,
1805 bool VerifyEachPass, bool DebugLogging) {
1806 auto &Name = E.Name;
1807 auto &InnerPipeline = E.InnerPipeline;
1809 // First handle complex passes like the pass managers which carry pipelines.
1810 if (!InnerPipeline.empty()) {
1811 if (Name == "module") {
1812 ModulePassManager NestedMPM(DebugLogging);
1813 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1814 VerifyEachPass, DebugLogging))
1815 return Err;
1816 MPM.addPass(std::move(NestedMPM));
1817 return Error::success();
1819 if (Name == "cgscc") {
1820 CGSCCPassManager CGPM(DebugLogging);
1821 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1822 DebugLogging))
1823 return Err;
1824 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1825 return Error::success();
1827 if (Name == "function") {
1828 FunctionPassManager FPM(DebugLogging);
1829 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1830 VerifyEachPass, DebugLogging))
1831 return Err;
1832 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1833 return Error::success();
1835 if (auto Count = parseRepeatPassName(Name)) {
1836 ModulePassManager NestedMPM(DebugLogging);
1837 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline,
1838 VerifyEachPass, DebugLogging))
1839 return Err;
1840 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1841 return Error::success();
1844 for (auto &C : ModulePipelineParsingCallbacks)
1845 if (C(Name, MPM, InnerPipeline))
1846 return Error::success();
1848 // Normal passes can't have pipelines.
1849 return make_error<StringError>(
1850 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1851 inconvertibleErrorCode());
1855 // Manually handle aliases for pre-configured pipeline fragments.
1856 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1857 SmallVector<StringRef, 3> Matches;
1858 if (!DefaultAliasRegex.match(Name, &Matches))
1859 return make_error<StringError>(
1860 formatv("unknown default pipeline alias '{0}'", Name).str(),
1861 inconvertibleErrorCode());
1863 assert(Matches.size() == 3 && "Must capture two matched strings!");
1865 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1866 .Case("O0", O0)
1867 .Case("O1", O1)
1868 .Case("O2", O2)
1869 .Case("O3", O3)
1870 .Case("Os", Os)
1871 .Case("Oz", Oz);
1872 if (L == O0) {
1873 // Add instrumentation PGO passes -- at O0 we can still do PGO.
1874 if (PGOOpt && Matches[1] != "thinlto" &&
1875 (PGOOpt->Action == PGOOptions::IRInstr ||
1876 PGOOpt->Action == PGOOptions::IRUse))
1877 addPGOInstrPassesForO0(
1878 MPM, DebugLogging,
1879 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1880 /* IsCS */ false, PGOOpt->ProfileFile,
1881 PGOOpt->ProfileRemappingFile);
1882 // Do nothing else at all!
1883 return Error::success();
1886 if (Matches[1] == "default") {
1887 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1888 } else if (Matches[1] == "thinlto-pre-link") {
1889 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1890 } else if (Matches[1] == "thinlto") {
1891 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr));
1892 } else if (Matches[1] == "lto-pre-link") {
1893 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1894 } else {
1895 assert(Matches[1] == "lto" && "Not one of the matched options!");
1896 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr));
1898 return Error::success();
1901 // Finally expand the basic registered passes from the .inc file.
1902 #define MODULE_PASS(NAME, CREATE_PASS) \
1903 if (Name == NAME) { \
1904 MPM.addPass(CREATE_PASS); \
1905 return Error::success(); \
1907 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1908 if (Name == "require<" NAME ">") { \
1909 MPM.addPass( \
1910 RequireAnalysisPass< \
1911 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1912 return Error::success(); \
1914 if (Name == "invalidate<" NAME ">") { \
1915 MPM.addPass(InvalidateAnalysisPass< \
1916 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1917 return Error::success(); \
1919 #include "PassRegistry.def"
1921 for (auto &C : ModulePipelineParsingCallbacks)
1922 if (C(Name, MPM, InnerPipeline))
1923 return Error::success();
1924 return make_error<StringError>(
1925 formatv("unknown module pass '{0}'", Name).str(),
1926 inconvertibleErrorCode());
1929 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1930 const PipelineElement &E, bool VerifyEachPass,
1931 bool DebugLogging) {
1932 auto &Name = E.Name;
1933 auto &InnerPipeline = E.InnerPipeline;
1935 // First handle complex passes like the pass managers which carry pipelines.
1936 if (!InnerPipeline.empty()) {
1937 if (Name == "cgscc") {
1938 CGSCCPassManager NestedCGPM(DebugLogging);
1939 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1940 VerifyEachPass, DebugLogging))
1941 return Err;
1942 // Add the nested pass manager with the appropriate adaptor.
1943 CGPM.addPass(std::move(NestedCGPM));
1944 return Error::success();
1946 if (Name == "function") {
1947 FunctionPassManager FPM(DebugLogging);
1948 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline,
1949 VerifyEachPass, DebugLogging))
1950 return Err;
1951 // Add the nested pass manager with the appropriate adaptor.
1952 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
1953 return Error::success();
1955 if (auto Count = parseRepeatPassName(Name)) {
1956 CGSCCPassManager NestedCGPM(DebugLogging);
1957 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1958 VerifyEachPass, DebugLogging))
1959 return Err;
1960 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1961 return Error::success();
1963 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1964 CGSCCPassManager NestedCGPM(DebugLogging);
1965 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline,
1966 VerifyEachPass, DebugLogging))
1967 return Err;
1968 CGPM.addPass(
1969 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1970 return Error::success();
1973 for (auto &C : CGSCCPipelineParsingCallbacks)
1974 if (C(Name, CGPM, InnerPipeline))
1975 return Error::success();
1977 // Normal passes can't have pipelines.
1978 return make_error<StringError>(
1979 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1980 inconvertibleErrorCode());
1983 // Now expand the basic registered passes from the .inc file.
1984 #define CGSCC_PASS(NAME, CREATE_PASS) \
1985 if (Name == NAME) { \
1986 CGPM.addPass(CREATE_PASS); \
1987 return Error::success(); \
1989 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1990 if (Name == "require<" NAME ">") { \
1991 CGPM.addPass(RequireAnalysisPass< \
1992 std::remove_reference<decltype(CREATE_PASS)>::type, \
1993 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1994 CGSCCUpdateResult &>()); \
1995 return Error::success(); \
1997 if (Name == "invalidate<" NAME ">") { \
1998 CGPM.addPass(InvalidateAnalysisPass< \
1999 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2000 return Error::success(); \
2002 #include "PassRegistry.def"
2004 for (auto &C : CGSCCPipelineParsingCallbacks)
2005 if (C(Name, CGPM, InnerPipeline))
2006 return Error::success();
2007 return make_error<StringError>(
2008 formatv("unknown cgscc pass '{0}'", Name).str(),
2009 inconvertibleErrorCode());
2012 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
2013 const PipelineElement &E,
2014 bool VerifyEachPass, bool DebugLogging) {
2015 auto &Name = E.Name;
2016 auto &InnerPipeline = E.InnerPipeline;
2018 // First handle complex passes like the pass managers which carry pipelines.
2019 if (!InnerPipeline.empty()) {
2020 if (Name == "function") {
2021 FunctionPassManager NestedFPM(DebugLogging);
2022 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2023 VerifyEachPass, DebugLogging))
2024 return Err;
2025 // Add the nested pass manager with the appropriate adaptor.
2026 FPM.addPass(std::move(NestedFPM));
2027 return Error::success();
2029 if (Name == "loop" || Name == "loop-mssa") {
2030 LoopPassManager LPM(DebugLogging);
2031 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
2032 DebugLogging))
2033 return Err;
2034 // Add the nested pass manager with the appropriate adaptor.
2035 bool UseMemorySSA = (Name == "loop-mssa");
2036 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
2037 DebugLogging));
2038 return Error::success();
2040 if (auto Count = parseRepeatPassName(Name)) {
2041 FunctionPassManager NestedFPM(DebugLogging);
2042 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline,
2043 VerifyEachPass, DebugLogging))
2044 return Err;
2045 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
2046 return Error::success();
2049 for (auto &C : FunctionPipelineParsingCallbacks)
2050 if (C(Name, FPM, InnerPipeline))
2051 return Error::success();
2053 // Normal passes can't have pipelines.
2054 return make_error<StringError>(
2055 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
2056 inconvertibleErrorCode());
2059 // Now expand the basic registered passes from the .inc file.
2060 #define FUNCTION_PASS(NAME, CREATE_PASS) \
2061 if (Name == NAME) { \
2062 FPM.addPass(CREATE_PASS); \
2063 return Error::success(); \
2065 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2066 if (checkParametrizedPassName(Name, NAME)) { \
2067 auto Params = parsePassParameters(PARSER, Name, NAME); \
2068 if (!Params) \
2069 return Params.takeError(); \
2070 FPM.addPass(CREATE_PASS(Params.get())); \
2071 return Error::success(); \
2073 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
2074 if (Name == "require<" NAME ">") { \
2075 FPM.addPass( \
2076 RequireAnalysisPass< \
2077 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
2078 return Error::success(); \
2080 if (Name == "invalidate<" NAME ">") { \
2081 FPM.addPass(InvalidateAnalysisPass< \
2082 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2083 return Error::success(); \
2085 #include "PassRegistry.def"
2087 for (auto &C : FunctionPipelineParsingCallbacks)
2088 if (C(Name, FPM, InnerPipeline))
2089 return Error::success();
2090 return make_error<StringError>(
2091 formatv("unknown function pass '{0}'", Name).str(),
2092 inconvertibleErrorCode());
2095 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
2096 bool VerifyEachPass, bool DebugLogging) {
2097 StringRef Name = E.Name;
2098 auto &InnerPipeline = E.InnerPipeline;
2100 // First handle complex passes like the pass managers which carry pipelines.
2101 if (!InnerPipeline.empty()) {
2102 if (Name == "loop") {
2103 LoopPassManager NestedLPM(DebugLogging);
2104 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2105 VerifyEachPass, DebugLogging))
2106 return Err;
2107 // Add the nested pass manager with the appropriate adaptor.
2108 LPM.addPass(std::move(NestedLPM));
2109 return Error::success();
2111 if (auto Count = parseRepeatPassName(Name)) {
2112 LoopPassManager NestedLPM(DebugLogging);
2113 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline,
2114 VerifyEachPass, DebugLogging))
2115 return Err;
2116 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
2117 return Error::success();
2120 for (auto &C : LoopPipelineParsingCallbacks)
2121 if (C(Name, LPM, InnerPipeline))
2122 return Error::success();
2124 // Normal passes can't have pipelines.
2125 return make_error<StringError>(
2126 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
2127 inconvertibleErrorCode());
2130 // Now expand the basic registered passes from the .inc file.
2131 #define LOOP_PASS(NAME, CREATE_PASS) \
2132 if (Name == NAME) { \
2133 LPM.addPass(CREATE_PASS); \
2134 return Error::success(); \
2136 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \
2137 if (checkParametrizedPassName(Name, NAME)) { \
2138 auto Params = parsePassParameters(PARSER, Name, NAME); \
2139 if (!Params) \
2140 return Params.takeError(); \
2141 LPM.addPass(CREATE_PASS(Params.get())); \
2142 return Error::success(); \
2144 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \
2145 if (Name == "require<" NAME ">") { \
2146 LPM.addPass(RequireAnalysisPass< \
2147 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
2148 LoopAnalysisManager, LoopStandardAnalysisResults &, \
2149 LPMUpdater &>()); \
2150 return Error::success(); \
2152 if (Name == "invalidate<" NAME ">") { \
2153 LPM.addPass(InvalidateAnalysisPass< \
2154 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
2155 return Error::success(); \
2157 #include "PassRegistry.def"
2159 for (auto &C : LoopPipelineParsingCallbacks)
2160 if (C(Name, LPM, InnerPipeline))
2161 return Error::success();
2162 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
2163 inconvertibleErrorCode());
2166 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
2167 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2168 if (Name == NAME) { \
2169 AA.registerModuleAnalysis< \
2170 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2171 return true; \
2173 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
2174 if (Name == NAME) { \
2175 AA.registerFunctionAnalysis< \
2176 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
2177 return true; \
2179 #include "PassRegistry.def"
2181 for (auto &C : AAParsingCallbacks)
2182 if (C(Name, AA))
2183 return true;
2184 return false;
2187 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
2188 ArrayRef<PipelineElement> Pipeline,
2189 bool VerifyEachPass,
2190 bool DebugLogging) {
2191 for (const auto &Element : Pipeline) {
2192 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
2193 return Err;
2194 // FIXME: No verifier support for Loop passes!
2196 return Error::success();
2199 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
2200 ArrayRef<PipelineElement> Pipeline,
2201 bool VerifyEachPass,
2202 bool DebugLogging) {
2203 for (const auto &Element : Pipeline) {
2204 if (auto Err =
2205 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
2206 return Err;
2207 if (VerifyEachPass)
2208 FPM.addPass(VerifierPass());
2210 return Error::success();
2213 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
2214 ArrayRef<PipelineElement> Pipeline,
2215 bool VerifyEachPass,
2216 bool DebugLogging) {
2217 for (const auto &Element : Pipeline) {
2218 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
2219 return Err;
2220 // FIXME: No verifier support for CGSCC passes!
2222 return Error::success();
2225 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
2226 FunctionAnalysisManager &FAM,
2227 CGSCCAnalysisManager &CGAM,
2228 ModuleAnalysisManager &MAM) {
2229 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
2230 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
2231 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
2232 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
2233 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
2234 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
2235 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
2238 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
2239 ArrayRef<PipelineElement> Pipeline,
2240 bool VerifyEachPass,
2241 bool DebugLogging) {
2242 for (const auto &Element : Pipeline) {
2243 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
2244 return Err;
2245 if (VerifyEachPass)
2246 MPM.addPass(VerifierPass());
2248 return Error::success();
2251 // Primary pass pipeline description parsing routine for a \c ModulePassManager
2252 // FIXME: Should this routine accept a TargetMachine or require the caller to
2253 // pre-populate the analysis managers with target-specific stuff?
2254 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
2255 StringRef PipelineText,
2256 bool VerifyEachPass, bool DebugLogging) {
2257 auto Pipeline = parsePipelineText(PipelineText);
2258 if (!Pipeline || Pipeline->empty())
2259 return make_error<StringError>(
2260 formatv("invalid pipeline '{0}'", PipelineText).str(),
2261 inconvertibleErrorCode());
2263 // If the first name isn't at the module layer, wrap the pipeline up
2264 // automatically.
2265 StringRef FirstName = Pipeline->front().Name;
2267 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
2268 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
2269 Pipeline = {{"cgscc", std::move(*Pipeline)}};
2270 } else if (isFunctionPassName(FirstName,
2271 FunctionPipelineParsingCallbacks)) {
2272 Pipeline = {{"function", std::move(*Pipeline)}};
2273 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) {
2274 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
2275 } else {
2276 for (auto &C : TopLevelPipelineParsingCallbacks)
2277 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2278 return Error::success();
2280 // Unknown pass or pipeline name!
2281 auto &InnerPipeline = Pipeline->front().InnerPipeline;
2282 return make_error<StringError>(
2283 formatv("unknown {0} name '{1}'",
2284 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
2285 .str(),
2286 inconvertibleErrorCode());
2290 if (auto Err =
2291 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging))
2292 return Err;
2293 return Error::success();
2296 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager
2297 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
2298 StringRef PipelineText,
2299 bool VerifyEachPass, bool DebugLogging) {
2300 auto Pipeline = parsePipelineText(PipelineText);
2301 if (!Pipeline || Pipeline->empty())
2302 return make_error<StringError>(
2303 formatv("invalid pipeline '{0}'", PipelineText).str(),
2304 inconvertibleErrorCode());
2306 StringRef FirstName = Pipeline->front().Name;
2307 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
2308 return make_error<StringError>(
2309 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
2310 PipelineText)
2311 .str(),
2312 inconvertibleErrorCode());
2314 if (auto Err =
2315 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2316 return Err;
2317 return Error::success();
2320 // Primary pass pipeline description parsing routine for a \c
2321 // FunctionPassManager
2322 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
2323 StringRef PipelineText,
2324 bool VerifyEachPass, bool DebugLogging) {
2325 auto Pipeline = parsePipelineText(PipelineText);
2326 if (!Pipeline || Pipeline->empty())
2327 return make_error<StringError>(
2328 formatv("invalid pipeline '{0}'", PipelineText).str(),
2329 inconvertibleErrorCode());
2331 StringRef FirstName = Pipeline->front().Name;
2332 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
2333 return make_error<StringError>(
2334 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
2335 PipelineText)
2336 .str(),
2337 inconvertibleErrorCode());
2339 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass,
2340 DebugLogging))
2341 return Err;
2342 return Error::success();
2345 // Primary pass pipeline description parsing routine for a \c LoopPassManager
2346 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
2347 StringRef PipelineText,
2348 bool VerifyEachPass, bool DebugLogging) {
2349 auto Pipeline = parsePipelineText(PipelineText);
2350 if (!Pipeline || Pipeline->empty())
2351 return make_error<StringError>(
2352 formatv("invalid pipeline '{0}'", PipelineText).str(),
2353 inconvertibleErrorCode());
2355 if (auto Err =
2356 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging))
2357 return Err;
2359 return Error::success();
2362 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
2363 // If the pipeline just consists of the word 'default' just replace the AA
2364 // manager with our default one.
2365 if (PipelineText == "default") {
2366 AA = buildDefaultAAPipeline();
2367 return Error::success();
2370 while (!PipelineText.empty()) {
2371 StringRef Name;
2372 std::tie(Name, PipelineText) = PipelineText.split(',');
2373 if (!parseAAPassName(AA, Name))
2374 return make_error<StringError>(
2375 formatv("unknown alias analysis name '{0}'", Name).str(),
2376 inconvertibleErrorCode());
2379 return Error::success();