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 /// Tests whether a pass name starts with a valid prefix for a default pipeline 1247 /// alias. 1248 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) { 1249 return Name.startswith("default") || Name.startswith("thinlto") || 1250 Name.startswith("lto"); 1251 } 1252 1253 /// Tests whether registered callbacks will accept a given pass name. 1254 /// 1255 /// When parsing a pipeline text, the type of the outermost pipeline may be 1256 /// omitted, in which case the type is automatically determined from the first 1257 /// pass name in the text. This may be a name that is handled through one of the 1258 /// callbacks. We check this through the oridinary parsing callbacks by setting 1259 /// up a dummy PassManager in order to not force the client to also handle this 1260 /// type of query. 1261 template <typename PassManagerT, typename CallbacksT> 1262 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) { 1263 if (!Callbacks.empty()) { 1264 PassManagerT DummyPM; 1265 for (auto &CB : Callbacks) 1266 if (CB(Name, DummyPM, {})) 1267 return true; 1268 } 1269 return false; 1270 } 1271 1272 template <typename CallbacksT> 1273 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) { 1274 // Manually handle aliases for pre-configured pipeline fragments. 1275 if (startsWithDefaultPipelineAliasPrefix(Name)) 1276 return DefaultAliasRegex.match(Name); 1277 1278 // Explicitly handle pass manager names. 1279 if (Name == "module") 1280 return true; 1281 if (Name == "cgscc") 1282 return true; 1283 if (Name == "function") 1284 return true; 1285 1286 // Explicitly handle custom-parsed pass names. 1287 if (parseRepeatPassName(Name)) 1288 return true; 1289 1290 #define MODULE_PASS(NAME, CREATE_PASS) \ 1291 if (Name == NAME) \ 1292 return true; 1293 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1294 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1295 return true; 1296 #include "PassRegistry.def" 1297 1298 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks); 1299 } 1300 1301 template <typename CallbacksT> 1302 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) { 1303 // Explicitly handle pass manager names. 1304 if (Name == "cgscc") 1305 return true; 1306 if (Name == "function") 1307 return true; 1308 1309 // Explicitly handle custom-parsed pass names. 1310 if (parseRepeatPassName(Name)) 1311 return true; 1312 if (parseDevirtPassName(Name)) 1313 return true; 1314 1315 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1316 if (Name == NAME) \ 1317 return true; 1318 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1319 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1320 return true; 1321 #include "PassRegistry.def" 1322 1323 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks); 1324 } 1325 1326 template <typename CallbacksT> 1327 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) { 1328 // Explicitly handle pass manager names. 1329 if (Name == "function") 1330 return true; 1331 if (Name == "loop") 1332 return true; 1333 1334 // Explicitly handle custom-parsed pass names. 1335 if (parseRepeatPassName(Name)) 1336 return true; 1337 1338 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1339 if (Name == NAME) \ 1340 return true; 1341 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1342 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1343 return true; 1344 #include "PassRegistry.def" 1345 1346 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks); 1347 } 1348 1349 template <typename CallbacksT> 1350 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) { 1351 // Explicitly handle pass manager names. 1352 if (Name == "loop") 1353 return true; 1354 1355 // Explicitly handle custom-parsed pass names. 1356 if (parseRepeatPassName(Name)) 1357 return true; 1358 1359 #define LOOP_PASS(NAME, CREATE_PASS) \ 1360 if (Name == NAME) \ 1361 return true; 1362 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1363 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1364 return true; 1365 #include "PassRegistry.def" 1366 1367 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks); 1368 } 1369 1370 Optional<std::vector<PassBuilder::PipelineElement>> 1371 PassBuilder::parsePipelineText(StringRef Text) { 1372 std::vector<PipelineElement> ResultPipeline; 1373 1374 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = { 1375 &ResultPipeline}; 1376 for (;;) { 1377 std::vector<PipelineElement> &Pipeline = *PipelineStack.back(); 1378 size_t Pos = Text.find_first_of(",()"); 1379 Pipeline.push_back({Text.substr(0, Pos), {}}); 1380 1381 // If we have a single terminating name, we're done. 1382 if (Pos == Text.npos) 1383 break; 1384 1385 char Sep = Text[Pos]; 1386 Text = Text.substr(Pos + 1); 1387 if (Sep == ',') 1388 // Just a name ending in a comma, continue. 1389 continue; 1390 1391 if (Sep == '(') { 1392 // Push the inner pipeline onto the stack to continue processing. 1393 PipelineStack.push_back(&Pipeline.back().InnerPipeline); 1394 continue; 1395 } 1396 1397 assert(Sep == ')' && "Bogus separator!"); 1398 // When handling the close parenthesis, we greedily consume them to avoid 1399 // empty strings in the pipeline. 1400 do { 1401 // If we try to pop the outer pipeline we have unbalanced parentheses. 1402 if (PipelineStack.size() == 1) 1403 return None; 1404 1405 PipelineStack.pop_back(); 1406 } while (Text.consume_front(")")); 1407 1408 // Check if we've finished parsing. 1409 if (Text.empty()) 1410 break; 1411 1412 // Otherwise, the end of an inner pipeline always has to be followed by 1413 // a comma, and then we can continue. 1414 if (!Text.consume_front(",")) 1415 return None; 1416 } 1417 1418 if (PipelineStack.size() > 1) 1419 // Unbalanced paretheses. 1420 return None; 1421 1422 assert(PipelineStack.back() == &ResultPipeline && 1423 "Wrong pipeline at the bottom of the stack!"); 1424 return {std::move(ResultPipeline)}; 1425 } 1426 1427 Error PassBuilder::parseModulePass(ModulePassManager &MPM, 1428 const PipelineElement &E, 1429 bool VerifyEachPass, bool DebugLogging) { 1430 auto &Name = E.Name; 1431 auto &InnerPipeline = E.InnerPipeline; 1432 1433 // First handle complex passes like the pass managers which carry pipelines. 1434 if (!InnerPipeline.empty()) { 1435 if (Name == "module") { 1436 ModulePassManager NestedMPM(DebugLogging); 1437 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1438 VerifyEachPass, DebugLogging)) 1439 return Err; 1440 MPM.addPass(std::move(NestedMPM)); 1441 return Error::success(); 1442 } 1443 if (Name == "cgscc") { 1444 CGSCCPassManager CGPM(DebugLogging); 1445 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass, 1446 DebugLogging)) 1447 return Err; 1448 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1449 return Error::success(); 1450 } 1451 if (Name == "function") { 1452 FunctionPassManager FPM(DebugLogging); 1453 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 1454 VerifyEachPass, DebugLogging)) 1455 return Err; 1456 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1457 return Error::success(); 1458 } 1459 if (auto Count = parseRepeatPassName(Name)) { 1460 ModulePassManager NestedMPM(DebugLogging); 1461 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1462 VerifyEachPass, DebugLogging)) 1463 return Err; 1464 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM))); 1465 return Error::success(); 1466 } 1467 1468 for (auto &C : ModulePipelineParsingCallbacks) 1469 if (C(Name, MPM, InnerPipeline)) 1470 return Error::success(); 1471 1472 // Normal passes can't have pipelines. 1473 return make_error<StringError>( 1474 formatv("invalid use of '{0}' pass as module pipeline", Name).str(), 1475 inconvertibleErrorCode()); 1476 ; 1477 } 1478 1479 // Manually handle aliases for pre-configured pipeline fragments. 1480 if (startsWithDefaultPipelineAliasPrefix(Name)) { 1481 SmallVector<StringRef, 3> Matches; 1482 if (!DefaultAliasRegex.match(Name, &Matches)) 1483 return make_error<StringError>( 1484 formatv("unknown default pipeline alias '{0}'", Name).str(), 1485 inconvertibleErrorCode()); 1486 1487 assert(Matches.size() == 3 && "Must capture two matched strings!"); 1488 1489 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2]) 1490 .Case("O0", O0) 1491 .Case("O1", O1) 1492 .Case("O2", O2) 1493 .Case("O3", O3) 1494 .Case("Os", Os) 1495 .Case("Oz", Oz); 1496 if (L == O0) 1497 // At O0 we do nothing at all! 1498 return Error::success(); 1499 1500 if (Matches[1] == "default") { 1501 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging)); 1502 } else if (Matches[1] == "thinlto-pre-link") { 1503 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging)); 1504 } else if (Matches[1] == "thinlto") { 1505 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr)); 1506 } else if (Matches[1] == "lto-pre-link") { 1507 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging)); 1508 } else { 1509 assert(Matches[1] == "lto" && "Not one of the matched options!"); 1510 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr)); 1511 } 1512 return Error::success(); 1513 } 1514 1515 // Finally expand the basic registered passes from the .inc file. 1516 #define MODULE_PASS(NAME, CREATE_PASS) \ 1517 if (Name == NAME) { \ 1518 MPM.addPass(CREATE_PASS); \ 1519 return Error::success(); \ 1520 } 1521 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1522 if (Name == "require<" NAME ">") { \ 1523 MPM.addPass( \ 1524 RequireAnalysisPass< \ 1525 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \ 1526 return Error::success(); \ 1527 } \ 1528 if (Name == "invalidate<" NAME ">") { \ 1529 MPM.addPass(InvalidateAnalysisPass< \ 1530 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1531 return Error::success(); \ 1532 } 1533 #include "PassRegistry.def" 1534 1535 for (auto &C : ModulePipelineParsingCallbacks) 1536 if (C(Name, MPM, InnerPipeline)) 1537 return Error::success(); 1538 return make_error<StringError>( 1539 formatv("unknown module pass '{0}'", Name).str(), 1540 inconvertibleErrorCode()); 1541 } 1542 1543 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM, 1544 const PipelineElement &E, bool VerifyEachPass, 1545 bool DebugLogging) { 1546 auto &Name = E.Name; 1547 auto &InnerPipeline = E.InnerPipeline; 1548 1549 // First handle complex passes like the pass managers which carry pipelines. 1550 if (!InnerPipeline.empty()) { 1551 if (Name == "cgscc") { 1552 CGSCCPassManager NestedCGPM(DebugLogging); 1553 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1554 VerifyEachPass, DebugLogging)) 1555 return Err; 1556 // Add the nested pass manager with the appropriate adaptor. 1557 CGPM.addPass(std::move(NestedCGPM)); 1558 return Error::success(); 1559 } 1560 if (Name == "function") { 1561 FunctionPassManager FPM(DebugLogging); 1562 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 1563 VerifyEachPass, DebugLogging)) 1564 return Err; 1565 // Add the nested pass manager with the appropriate adaptor. 1566 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 1567 return Error::success(); 1568 } 1569 if (auto Count = parseRepeatPassName(Name)) { 1570 CGSCCPassManager NestedCGPM(DebugLogging); 1571 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1572 VerifyEachPass, DebugLogging)) 1573 return Err; 1574 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM))); 1575 return Error::success(); 1576 } 1577 if (auto MaxRepetitions = parseDevirtPassName(Name)) { 1578 CGSCCPassManager NestedCGPM(DebugLogging); 1579 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1580 VerifyEachPass, DebugLogging)) 1581 return Err; 1582 CGPM.addPass( 1583 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions)); 1584 return Error::success(); 1585 } 1586 1587 for (auto &C : CGSCCPipelineParsingCallbacks) 1588 if (C(Name, CGPM, InnerPipeline)) 1589 return Error::success(); 1590 1591 // Normal passes can't have pipelines. 1592 return make_error<StringError>( 1593 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(), 1594 inconvertibleErrorCode()); 1595 } 1596 1597 // Now expand the basic registered passes from the .inc file. 1598 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1599 if (Name == NAME) { \ 1600 CGPM.addPass(CREATE_PASS); \ 1601 return Error::success(); \ 1602 } 1603 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1604 if (Name == "require<" NAME ">") { \ 1605 CGPM.addPass(RequireAnalysisPass< \ 1606 std::remove_reference<decltype(CREATE_PASS)>::type, \ 1607 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \ 1608 CGSCCUpdateResult &>()); \ 1609 return Error::success(); \ 1610 } \ 1611 if (Name == "invalidate<" NAME ">") { \ 1612 CGPM.addPass(InvalidateAnalysisPass< \ 1613 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1614 return Error::success(); \ 1615 } 1616 #include "PassRegistry.def" 1617 1618 for (auto &C : CGSCCPipelineParsingCallbacks) 1619 if (C(Name, CGPM, InnerPipeline)) 1620 return Error::success(); 1621 return make_error<StringError>( 1622 formatv("unknown cgscc pass '{0}'", Name).str(), 1623 inconvertibleErrorCode()); 1624 } 1625 1626 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM, 1627 const PipelineElement &E, 1628 bool VerifyEachPass, bool DebugLogging) { 1629 auto &Name = E.Name; 1630 auto &InnerPipeline = E.InnerPipeline; 1631 1632 // First handle complex passes like the pass managers which carry pipelines. 1633 if (!InnerPipeline.empty()) { 1634 if (Name == "function") { 1635 FunctionPassManager NestedFPM(DebugLogging); 1636 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 1637 VerifyEachPass, DebugLogging)) 1638 return Err; 1639 // Add the nested pass manager with the appropriate adaptor. 1640 FPM.addPass(std::move(NestedFPM)); 1641 return Error::success(); 1642 } 1643 if (Name == "loop") { 1644 LoopPassManager LPM(DebugLogging); 1645 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass, 1646 DebugLogging)) 1647 return Err; 1648 // Add the nested pass manager with the appropriate adaptor. 1649 FPM.addPass( 1650 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging)); 1651 return Error::success(); 1652 } 1653 if (auto Count = parseRepeatPassName(Name)) { 1654 FunctionPassManager NestedFPM(DebugLogging); 1655 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 1656 VerifyEachPass, DebugLogging)) 1657 return Err; 1658 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM))); 1659 return Error::success(); 1660 } 1661 1662 for (auto &C : FunctionPipelineParsingCallbacks) 1663 if (C(Name, FPM, InnerPipeline)) 1664 return Error::success(); 1665 1666 // Normal passes can't have pipelines. 1667 return make_error<StringError>( 1668 formatv("invalid use of '{0}' pass as function pipeline", Name).str(), 1669 inconvertibleErrorCode()); 1670 } 1671 1672 // Now expand the basic registered passes from the .inc file. 1673 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1674 if (Name == NAME) { \ 1675 FPM.addPass(CREATE_PASS); \ 1676 return Error::success(); \ 1677 } 1678 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1679 if (Name == "require<" NAME ">") { \ 1680 FPM.addPass( \ 1681 RequireAnalysisPass< \ 1682 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \ 1683 return Error::success(); \ 1684 } \ 1685 if (Name == "invalidate<" NAME ">") { \ 1686 FPM.addPass(InvalidateAnalysisPass< \ 1687 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1688 return Error::success(); \ 1689 } 1690 #include "PassRegistry.def" 1691 1692 for (auto &C : FunctionPipelineParsingCallbacks) 1693 if (C(Name, FPM, InnerPipeline)) 1694 return Error::success(); 1695 return make_error<StringError>( 1696 formatv("unknown function pass '{0}'", Name).str(), 1697 inconvertibleErrorCode()); 1698 } 1699 1700 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E, 1701 bool VerifyEachPass, bool DebugLogging) { 1702 StringRef Name = E.Name; 1703 auto &InnerPipeline = E.InnerPipeline; 1704 1705 // First handle complex passes like the pass managers which carry pipelines. 1706 if (!InnerPipeline.empty()) { 1707 if (Name == "loop") { 1708 LoopPassManager NestedLPM(DebugLogging); 1709 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 1710 VerifyEachPass, DebugLogging)) 1711 return Err; 1712 // Add the nested pass manager with the appropriate adaptor. 1713 LPM.addPass(std::move(NestedLPM)); 1714 return Error::success(); 1715 } 1716 if (auto Count = parseRepeatPassName(Name)) { 1717 LoopPassManager NestedLPM(DebugLogging); 1718 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 1719 VerifyEachPass, DebugLogging)) 1720 return Err; 1721 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM))); 1722 return Error::success(); 1723 } 1724 1725 for (auto &C : LoopPipelineParsingCallbacks) 1726 if (C(Name, LPM, InnerPipeline)) 1727 return Error::success(); 1728 1729 // Normal passes can't have pipelines. 1730 return make_error<StringError>( 1731 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(), 1732 inconvertibleErrorCode()); 1733 } 1734 1735 // Now expand the basic registered passes from the .inc file. 1736 #define LOOP_PASS(NAME, CREATE_PASS) \ 1737 if (Name == NAME) { \ 1738 LPM.addPass(CREATE_PASS); \ 1739 return Error::success(); \ 1740 } 1741 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1742 if (Name == "require<" NAME ">") { \ 1743 LPM.addPass(RequireAnalysisPass< \ 1744 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \ 1745 LoopAnalysisManager, LoopStandardAnalysisResults &, \ 1746 LPMUpdater &>()); \ 1747 return Error::success(); \ 1748 } \ 1749 if (Name == "invalidate<" NAME ">") { \ 1750 LPM.addPass(InvalidateAnalysisPass< \ 1751 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1752 return Error::success(); \ 1753 } 1754 #include "PassRegistry.def" 1755 1756 for (auto &C : LoopPipelineParsingCallbacks) 1757 if (C(Name, LPM, InnerPipeline)) 1758 return Error::success(); 1759 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(), 1760 inconvertibleErrorCode()); 1761 } 1762 1763 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) { 1764 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1765 if (Name == NAME) { \ 1766 AA.registerModuleAnalysis< \ 1767 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1768 return true; \ 1769 } 1770 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1771 if (Name == NAME) { \ 1772 AA.registerFunctionAnalysis< \ 1773 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1774 return true; \ 1775 } 1776 #include "PassRegistry.def" 1777 1778 for (auto &C : AAParsingCallbacks) 1779 if (C(Name, AA)) 1780 return true; 1781 return false; 1782 } 1783 1784 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM, 1785 ArrayRef<PipelineElement> Pipeline, 1786 bool VerifyEachPass, 1787 bool DebugLogging) { 1788 for (const auto &Element : Pipeline) { 1789 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging)) 1790 return Err; 1791 // FIXME: No verifier support for Loop passes! 1792 } 1793 return Error::success(); 1794 } 1795 1796 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM, 1797 ArrayRef<PipelineElement> Pipeline, 1798 bool VerifyEachPass, 1799 bool DebugLogging) { 1800 for (const auto &Element : Pipeline) { 1801 if (auto Err = 1802 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging)) 1803 return Err; 1804 if (VerifyEachPass) 1805 FPM.addPass(VerifierPass()); 1806 } 1807 return Error::success(); 1808 } 1809 1810 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM, 1811 ArrayRef<PipelineElement> Pipeline, 1812 bool VerifyEachPass, 1813 bool DebugLogging) { 1814 for (const auto &Element : Pipeline) { 1815 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging)) 1816 return Err; 1817 // FIXME: No verifier support for CGSCC passes! 1818 } 1819 return Error::success(); 1820 } 1821 1822 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM, 1823 FunctionAnalysisManager &FAM, 1824 CGSCCAnalysisManager &CGAM, 1825 ModuleAnalysisManager &MAM) { 1826 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); }); 1827 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); }); 1828 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); }); 1829 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); }); 1830 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); }); 1831 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); }); 1832 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); }); 1833 } 1834 1835 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM, 1836 ArrayRef<PipelineElement> Pipeline, 1837 bool VerifyEachPass, 1838 bool DebugLogging) { 1839 for (const auto &Element : Pipeline) { 1840 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging)) 1841 return Err; 1842 if (VerifyEachPass) 1843 MPM.addPass(VerifierPass()); 1844 } 1845 return Error::success(); 1846 } 1847 1848 // Primary pass pipeline description parsing routine for a \c ModulePassManager 1849 // FIXME: Should this routine accept a TargetMachine or require the caller to 1850 // pre-populate the analysis managers with target-specific stuff? 1851 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM, 1852 StringRef PipelineText, 1853 bool VerifyEachPass, bool DebugLogging) { 1854 auto Pipeline = parsePipelineText(PipelineText); 1855 if (!Pipeline || Pipeline->empty()) 1856 return make_error<StringError>( 1857 formatv("invalid pipeline '{0}'", PipelineText).str(), 1858 inconvertibleErrorCode()); 1859 1860 // If the first name isn't at the module layer, wrap the pipeline up 1861 // automatically. 1862 StringRef FirstName = Pipeline->front().Name; 1863 1864 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) { 1865 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) { 1866 Pipeline = {{"cgscc", std::move(*Pipeline)}}; 1867 } else if (isFunctionPassName(FirstName, 1868 FunctionPipelineParsingCallbacks)) { 1869 Pipeline = {{"function", std::move(*Pipeline)}}; 1870 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) { 1871 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}}; 1872 } else { 1873 for (auto &C : TopLevelPipelineParsingCallbacks) 1874 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 1875 return Error::success(); 1876 1877 // Unknown pass or pipeline name! 1878 auto &InnerPipeline = Pipeline->front().InnerPipeline; 1879 return make_error<StringError>( 1880 formatv("unknown {0} name '{1}'", 1881 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName) 1882 .str(), 1883 inconvertibleErrorCode()); 1884 } 1885 } 1886 1887 if (auto Err = 1888 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 1889 return Err; 1890 return Error::success(); 1891 } 1892 1893 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager 1894 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM, 1895 StringRef PipelineText, 1896 bool VerifyEachPass, bool DebugLogging) { 1897 auto Pipeline = parsePipelineText(PipelineText); 1898 if (!Pipeline || Pipeline->empty()) 1899 return make_error<StringError>( 1900 formatv("invalid pipeline '{0}'", PipelineText).str(), 1901 inconvertibleErrorCode()); 1902 1903 StringRef FirstName = Pipeline->front().Name; 1904 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) 1905 return make_error<StringError>( 1906 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName, 1907 PipelineText) 1908 .str(), 1909 inconvertibleErrorCode()); 1910 1911 if (auto Err = 1912 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 1913 return Err; 1914 return Error::success(); 1915 } 1916 1917 // Primary pass pipeline description parsing routine for a \c 1918 // FunctionPassManager 1919 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM, 1920 StringRef PipelineText, 1921 bool VerifyEachPass, bool DebugLogging) { 1922 auto Pipeline = parsePipelineText(PipelineText); 1923 if (!Pipeline || Pipeline->empty()) 1924 return make_error<StringError>( 1925 formatv("invalid pipeline '{0}'", PipelineText).str(), 1926 inconvertibleErrorCode()); 1927 1928 StringRef FirstName = Pipeline->front().Name; 1929 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks)) 1930 return make_error<StringError>( 1931 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName, 1932 PipelineText) 1933 .str(), 1934 inconvertibleErrorCode()); 1935 1936 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass, 1937 DebugLogging)) 1938 return Err; 1939 return Error::success(); 1940 } 1941 1942 // Primary pass pipeline description parsing routine for a \c LoopPassManager 1943 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM, 1944 StringRef PipelineText, 1945 bool VerifyEachPass, bool DebugLogging) { 1946 auto Pipeline = parsePipelineText(PipelineText); 1947 if (!Pipeline || Pipeline->empty()) 1948 return make_error<StringError>( 1949 formatv("invalid pipeline '{0}'", PipelineText).str(), 1950 inconvertibleErrorCode()); 1951 1952 if (auto Err = 1953 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 1954 return Err; 1955 1956 return Error::success(); 1957 } 1958 1959 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) { 1960 // If the pipeline just consists of the word 'default' just replace the AA 1961 // manager with our default one. 1962 if (PipelineText == "default") { 1963 AA = buildDefaultAAPipeline(); 1964 return Error::success(); 1965 } 1966 1967 while (!PipelineText.empty()) { 1968 StringRef Name; 1969 std::tie(Name, PipelineText) = PipelineText.split(','); 1970 if (!parseAAPassName(AA, Name)) 1971 return make_error<StringError>( 1972 formatv("unknown alias analysis name '{0}'", Name).str(), 1973 inconvertibleErrorCode()); 1974 } 1975 1976 return Error::success(); 1977 } 1978