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