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