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