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