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