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