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