1 //===- Construction of pass pipelines -------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// 10 /// This file provides the implementation of the PassBuilder based on our 11 /// static pass registry as well as related functionality. It also provides 12 /// helpers to aid in analyzing, debugging, and testing passes and pass 13 /// pipelines. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/BasicAliasAnalysis.h" 19 #include "llvm/Analysis/CGSCCPassManager.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/InlineAdvisor.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/Analysis/ProfileSummaryInfo.h" 24 #include "llvm/Analysis/ScopedNoAliasAA.h" 25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 26 #include "llvm/IR/PassManager.h" 27 #include "llvm/Passes/OptimizationLevel.h" 28 #include "llvm/Passes/PassBuilder.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/PGOOptions.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 34 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 35 #include "llvm/Transforms/Coroutines/CoroConditionalWrapper.h" 36 #include "llvm/Transforms/Coroutines/CoroEarly.h" 37 #include "llvm/Transforms/Coroutines/CoroElide.h" 38 #include "llvm/Transforms/Coroutines/CoroSplit.h" 39 #include "llvm/Transforms/IPO/AlwaysInliner.h" 40 #include "llvm/Transforms/IPO/Annotation2Metadata.h" 41 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 42 #include "llvm/Transforms/IPO/Attributor.h" 43 #include "llvm/Transforms/IPO/CalledValuePropagation.h" 44 #include "llvm/Transforms/IPO/ConstantMerge.h" 45 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 46 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 47 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 48 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 49 #include "llvm/Transforms/IPO/FunctionAttrs.h" 50 #include "llvm/Transforms/IPO/GlobalDCE.h" 51 #include "llvm/Transforms/IPO/GlobalOpt.h" 52 #include "llvm/Transforms/IPO/GlobalSplit.h" 53 #include "llvm/Transforms/IPO/HotColdSplitting.h" 54 #include "llvm/Transforms/IPO/IROutliner.h" 55 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 56 #include "llvm/Transforms/IPO/Inliner.h" 57 #include "llvm/Transforms/IPO/LowerTypeTests.h" 58 #include "llvm/Transforms/IPO/MergeFunctions.h" 59 #include "llvm/Transforms/IPO/ModuleInliner.h" 60 #include "llvm/Transforms/IPO/OpenMPOpt.h" 61 #include "llvm/Transforms/IPO/PartialInlining.h" 62 #include "llvm/Transforms/IPO/SCCP.h" 63 #include "llvm/Transforms/IPO/SampleProfile.h" 64 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 65 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" 66 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 67 #include "llvm/Transforms/InstCombine/InstCombine.h" 68 #include "llvm/Transforms/Instrumentation/CGProfile.h" 69 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 70 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h" 71 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 72 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 73 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 74 #include "llvm/Transforms/Scalar/ADCE.h" 75 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 76 #include "llvm/Transforms/Scalar/AnnotationRemarks.h" 77 #include "llvm/Transforms/Scalar/BDCE.h" 78 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 79 #include "llvm/Transforms/Scalar/ConstraintElimination.h" 80 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 81 #include "llvm/Transforms/Scalar/DFAJumpThreading.h" 82 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 83 #include "llvm/Transforms/Scalar/DivRemPairs.h" 84 #include "llvm/Transforms/Scalar/EarlyCSE.h" 85 #include "llvm/Transforms/Scalar/Float2Int.h" 86 #include "llvm/Transforms/Scalar/GVN.h" 87 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 88 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 89 #include "llvm/Transforms/Scalar/JumpThreading.h" 90 #include "llvm/Transforms/Scalar/LICM.h" 91 #include "llvm/Transforms/Scalar/LoopDeletion.h" 92 #include "llvm/Transforms/Scalar/LoopDistribute.h" 93 #include "llvm/Transforms/Scalar/LoopFlatten.h" 94 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 95 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 96 #include "llvm/Transforms/Scalar/LoopInterchange.h" 97 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 98 #include "llvm/Transforms/Scalar/LoopPassManager.h" 99 #include "llvm/Transforms/Scalar/LoopRotation.h" 100 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 101 #include "llvm/Transforms/Scalar/LoopSink.h" 102 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" 103 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 104 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h" 105 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 106 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 107 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 108 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 109 #include "llvm/Transforms/Scalar/NewGVN.h" 110 #include "llvm/Transforms/Scalar/Reassociate.h" 111 #include "llvm/Transforms/Scalar/SCCP.h" 112 #include "llvm/Transforms/Scalar/SROA.h" 113 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 114 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 115 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 116 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 117 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h" 118 #include "llvm/Transforms/Utils/AddDiscriminators.h" 119 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 120 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 121 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 122 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 123 #include "llvm/Transforms/Utils/Mem2Reg.h" 124 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 125 #include "llvm/Transforms/Utils/RelLookupTableConverter.h" 126 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h" 127 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 128 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 129 #include "llvm/Transforms/Vectorize/VectorCombine.h" 130 131 using namespace llvm; 132 133 static cl::opt<InliningAdvisorMode> UseInlineAdvisor( 134 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, 135 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), 136 cl::values(clEnumValN(InliningAdvisorMode::Default, "default", 137 "Heuristics-based inliner version."), 138 clEnumValN(InliningAdvisorMode::Development, "development", 139 "Use development mode (runtime-loadable model)."), 140 clEnumValN(InliningAdvisorMode::Release, "release", 141 "Use release mode (AOT-compiled model)."))); 142 143 static cl::opt<bool> EnableSyntheticCounts( 144 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, 145 cl::desc("Run synthetic function entry count generation " 146 "pass")); 147 148 /// Flag to enable inline deferral during PGO. 149 static cl::opt<bool> 150 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), 151 cl::Hidden, 152 cl::desc("Enable inline deferral during PGO")); 153 154 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false), 155 cl::Hidden, cl::ZeroOrMore, 156 cl::desc("Enable memory profiler")); 157 158 static cl::opt<bool> EnableModuleInliner("enable-module-inliner", 159 cl::init(false), cl::Hidden, 160 cl::desc("Enable module inliner")); 161 162 static cl::opt<bool> PerformMandatoryInliningsFirst( 163 "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore, 164 cl::desc("Perform mandatory inlinings module-wide, before performing " 165 "inlining.")); 166 167 static cl::opt<bool> EnableO3NonTrivialUnswitching( 168 "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden, 169 cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3")); 170 171 static cl::opt<bool> EnableEagerlyInvalidateAnalyses( 172 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden, 173 cl::desc("Eagerly invalidate more analyses in default pipelines")); 174 175 static cl::opt<bool> EnableNoRerunSimplificationPipeline( 176 "enable-no-rerun-simplification-pipeline", cl::init(false), cl::Hidden, 177 cl::desc( 178 "Prevent running the simplification pipeline on a function more " 179 "than once in the case that SCC mutations cause a function to be " 180 "visited multiple times as long as the function has not been changed")); 181 182 static cl::opt<bool> EnableMergeFunctions( 183 "enable-merge-functions", cl::init(false), cl::Hidden, 184 cl::desc("Enable function merging as part of the optimization pipeline")); 185 186 PipelineTuningOptions::PipelineTuningOptions() { 187 LoopInterleaving = true; 188 LoopVectorization = true; 189 SLPVectorization = false; 190 LoopUnrolling = true; 191 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 192 LicmMssaOptCap = SetLicmMssaOptCap; 193 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 194 CallGraphProfile = true; 195 MergeFunctions = EnableMergeFunctions; 196 EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses; 197 } 198 199 namespace llvm { 200 201 extern cl::opt<unsigned> MaxDevirtIterations; 202 extern cl::opt<bool> EnableConstraintElimination; 203 extern cl::opt<bool> EnableFunctionSpecialization; 204 extern cl::opt<bool> EnableGVNHoist; 205 extern cl::opt<bool> EnableGVNSink; 206 extern cl::opt<bool> EnableHotColdSplit; 207 extern cl::opt<bool> EnableIROutliner; 208 extern cl::opt<bool> EnableOrderFileInstrumentation; 209 extern cl::opt<bool> EnableCHR; 210 extern cl::opt<bool> EnableLoopInterchange; 211 extern cl::opt<bool> EnableUnrollAndJam; 212 extern cl::opt<bool> EnableLoopFlatten; 213 extern cl::opt<bool> EnableDFAJumpThreading; 214 extern cl::opt<bool> RunNewGVN; 215 extern cl::opt<bool> RunPartialInlining; 216 extern cl::opt<bool> ExtraVectorizerPasses; 217 218 extern cl::opt<bool> FlattenedProfileUsed; 219 220 extern cl::opt<AttributorRunOption> AttributorRun; 221 extern cl::opt<bool> EnableKnowledgeRetention; 222 223 extern cl::opt<bool> EnableMatrix; 224 225 extern cl::opt<bool> DisablePreInliner; 226 extern cl::opt<int> PreInlineThreshold; 227 } // namespace llvm 228 229 void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM, 230 OptimizationLevel Level) { 231 for (auto &C : PeepholeEPCallbacks) 232 C(FPM, Level); 233 } 234 235 // Helper to add AnnotationRemarksPass. 236 static void addAnnotationRemarksPass(ModulePassManager &MPM) { 237 MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass())); 238 } 239 240 // Helper to check if the current compilation phase is preparing for LTO 241 static bool isLTOPreLink(ThinOrFullLTOPhase Phase) { 242 return Phase == ThinOrFullLTOPhase::ThinLTOPreLink || 243 Phase == ThinOrFullLTOPhase::FullLTOPreLink; 244 } 245 246 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 247 FunctionPassManager 248 PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level, 249 ThinOrFullLTOPhase Phase) { 250 251 FunctionPassManager FPM; 252 253 // Form SSA out of local memory accesses after breaking apart aggregates into 254 // scalars. 255 FPM.addPass(SROAPass()); 256 257 // Catch trivial redundancies 258 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 259 260 // Hoisting of scalars and load expressions. 261 FPM.addPass( 262 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 263 FPM.addPass(InstCombinePass()); 264 265 FPM.addPass(LibCallsShrinkWrapPass()); 266 267 invokePeepholeEPCallbacks(FPM, Level); 268 269 FPM.addPass( 270 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 271 272 // Form canonically associated expression trees, and simplify the trees using 273 // basic mathematical properties. For example, this will form (nearly) 274 // minimal multiplication trees. 275 FPM.addPass(ReassociatePass()); 276 277 // Add the primary loop simplification pipeline. 278 // FIXME: Currently this is split into two loop pass pipelines because we run 279 // some function passes in between them. These can and should be removed 280 // and/or replaced by scheduling the loop pass equivalents in the correct 281 // positions. But those equivalent passes aren't powerful enough yet. 282 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 283 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 284 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 285 // `LoopInstSimplify`. 286 LoopPassManager LPM1, LPM2; 287 288 // Simplify the loop body. We do this initially to clean up after other loop 289 // passes run, either when iterating on a loop or on inner loops with 290 // implications on the outer loop. 291 LPM1.addPass(LoopInstSimplifyPass()); 292 LPM1.addPass(LoopSimplifyCFGPass()); 293 294 // Try to remove as much code from the loop header as possible, 295 // to reduce amount of IR that will have to be duplicated. However, 296 // do not perform speculative hoisting the first time as LICM 297 // will destroy metadata that may not need to be destroyed if run 298 // after loop rotation. 299 // TODO: Investigate promotion cap for O1. 300 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 301 /*AllowSpeculation=*/false)); 302 303 LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true, 304 isLTOPreLink(Phase))); 305 // TODO: Investigate promotion cap for O1. 306 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 307 /*AllowSpeculation=*/true)); 308 LPM1.addPass(SimpleLoopUnswitchPass()); 309 if (EnableLoopFlatten) 310 LPM1.addPass(LoopFlattenPass()); 311 312 LPM2.addPass(LoopIdiomRecognizePass()); 313 LPM2.addPass(IndVarSimplifyPass()); 314 315 for (auto &C : LateLoopOptimizationsEPCallbacks) 316 C(LPM2, Level); 317 318 LPM2.addPass(LoopDeletionPass()); 319 320 if (EnableLoopInterchange) 321 LPM2.addPass(LoopInterchangePass()); 322 323 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 324 // because it changes IR to makes profile annotation in back compile 325 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 326 // attributes so we need to make sure and allow the full unroll pass to pay 327 // attention to it. 328 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 329 PGOOpt->Action != PGOOptions::SampleUse) 330 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 331 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 332 PTO.ForgetAllSCEVInLoopUnroll)); 333 334 for (auto &C : LoopOptimizerEndEPCallbacks) 335 C(LPM2, Level); 336 337 // We provide the opt remark emitter pass for LICM to use. We only need to do 338 // this once as it is immutable. 339 FPM.addPass( 340 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 341 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 342 /*UseMemorySSA=*/true, 343 /*UseBlockFrequencyInfo=*/true)); 344 FPM.addPass( 345 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 346 FPM.addPass(InstCombinePass()); 347 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA. 348 // *All* loop passes must preserve it, in order to be able to use it. 349 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 350 /*UseMemorySSA=*/false, 351 /*UseBlockFrequencyInfo=*/false)); 352 353 // Delete small array after loop unroll. 354 FPM.addPass(SROAPass()); 355 356 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 357 FPM.addPass(MemCpyOptPass()); 358 359 // Sparse conditional constant propagation. 360 // FIXME: It isn't clear why we do this *after* loop passes rather than 361 // before... 362 FPM.addPass(SCCPPass()); 363 364 // Delete dead bit computations (instcombine runs after to fold away the dead 365 // computations, and then ADCE will run later to exploit any new DCE 366 // opportunities that creates). 367 FPM.addPass(BDCEPass()); 368 369 // Run instcombine after redundancy and dead bit elimination to exploit 370 // opportunities opened up by them. 371 FPM.addPass(InstCombinePass()); 372 invokePeepholeEPCallbacks(FPM, Level); 373 374 FPM.addPass(CoroElidePass()); 375 376 for (auto &C : ScalarOptimizerLateEPCallbacks) 377 C(FPM, Level); 378 379 // Finally, do an expensive DCE pass to catch all the dead code exposed by 380 // the simplifications and basic cleanup after all the simplifications. 381 // TODO: Investigate if this is too expensive. 382 FPM.addPass(ADCEPass()); 383 FPM.addPass( 384 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 385 FPM.addPass(InstCombinePass()); 386 invokePeepholeEPCallbacks(FPM, Level); 387 388 return FPM; 389 } 390 391 FunctionPassManager 392 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 393 ThinOrFullLTOPhase Phase) { 394 assert(Level != OptimizationLevel::O0 && "Must request optimizations!"); 395 396 // The O1 pipeline has a separate pipeline creation function to simplify 397 // construction readability. 398 if (Level.getSpeedupLevel() == 1) 399 return buildO1FunctionSimplificationPipeline(Level, Phase); 400 401 FunctionPassManager FPM; 402 403 // Form SSA out of local memory accesses after breaking apart aggregates into 404 // scalars. 405 FPM.addPass(SROAPass()); 406 407 // Catch trivial redundancies 408 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 409 if (EnableKnowledgeRetention) 410 FPM.addPass(AssumeSimplifyPass()); 411 412 // Hoisting of scalars and load expressions. 413 if (EnableGVNHoist) 414 FPM.addPass(GVNHoistPass()); 415 416 // Global value numbering based sinking. 417 if (EnableGVNSink) { 418 FPM.addPass(GVNSinkPass()); 419 FPM.addPass( 420 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 421 } 422 423 if (EnableConstraintElimination) 424 FPM.addPass(ConstraintEliminationPass()); 425 426 // Speculative execution if the target has divergent branches; otherwise nop. 427 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true)); 428 429 // Optimize based on known information about branches, and cleanup afterward. 430 FPM.addPass(JumpThreadingPass()); 431 FPM.addPass(CorrelatedValuePropagationPass()); 432 433 FPM.addPass( 434 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 435 FPM.addPass(InstCombinePass()); 436 if (Level == OptimizationLevel::O3) 437 FPM.addPass(AggressiveInstCombinePass()); 438 439 if (!Level.isOptimizingForSize()) 440 FPM.addPass(LibCallsShrinkWrapPass()); 441 442 invokePeepholeEPCallbacks(FPM, Level); 443 444 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy 445 // using the size value profile. Don't perform this when optimizing for size. 446 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse && 447 !Level.isOptimizingForSize()) 448 FPM.addPass(PGOMemOPSizeOpt()); 449 450 FPM.addPass(TailCallElimPass()); 451 FPM.addPass( 452 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 453 454 // Form canonically associated expression trees, and simplify the trees using 455 // basic mathematical properties. For example, this will form (nearly) 456 // minimal multiplication trees. 457 FPM.addPass(ReassociatePass()); 458 459 // Add the primary loop simplification pipeline. 460 // FIXME: Currently this is split into two loop pass pipelines because we run 461 // some function passes in between them. These can and should be removed 462 // and/or replaced by scheduling the loop pass equivalents in the correct 463 // positions. But those equivalent passes aren't powerful enough yet. 464 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 465 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 466 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 467 // `LoopInstSimplify`. 468 LoopPassManager LPM1, LPM2; 469 470 // Simplify the loop body. We do this initially to clean up after other loop 471 // passes run, either when iterating on a loop or on inner loops with 472 // implications on the outer loop. 473 LPM1.addPass(LoopInstSimplifyPass()); 474 LPM1.addPass(LoopSimplifyCFGPass()); 475 476 // Try to remove as much code from the loop header as possible, 477 // to reduce amount of IR that will have to be duplicated. However, 478 // do not perform speculative hoisting the first time as LICM 479 // will destroy metadata that may not need to be destroyed if run 480 // after loop rotation. 481 // TODO: Investigate promotion cap for O1. 482 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 483 /*AllowSpeculation=*/false)); 484 485 // Disable header duplication in loop rotation at -Oz. 486 LPM1.addPass( 487 LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase))); 488 // TODO: Investigate promotion cap for O1. 489 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 490 /*AllowSpeculation=*/true)); 491 LPM1.addPass( 492 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 && 493 EnableO3NonTrivialUnswitching)); 494 if (EnableLoopFlatten) 495 LPM1.addPass(LoopFlattenPass()); 496 497 LPM2.addPass(LoopIdiomRecognizePass()); 498 LPM2.addPass(IndVarSimplifyPass()); 499 500 for (auto &C : LateLoopOptimizationsEPCallbacks) 501 C(LPM2, Level); 502 503 LPM2.addPass(LoopDeletionPass()); 504 505 if (EnableLoopInterchange) 506 LPM2.addPass(LoopInterchangePass()); 507 508 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 509 // because it changes IR to makes profile annotation in back compile 510 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 511 // attributes so we need to make sure and allow the full unroll pass to pay 512 // attention to it. 513 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 514 PGOOpt->Action != PGOOptions::SampleUse) 515 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 516 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 517 PTO.ForgetAllSCEVInLoopUnroll)); 518 519 for (auto &C : LoopOptimizerEndEPCallbacks) 520 C(LPM2, Level); 521 522 // We provide the opt remark emitter pass for LICM to use. We only need to do 523 // this once as it is immutable. 524 FPM.addPass( 525 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 526 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 527 /*UseMemorySSA=*/true, 528 /*UseBlockFrequencyInfo=*/true)); 529 FPM.addPass( 530 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 531 FPM.addPass(InstCombinePass()); 532 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass, 533 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA. 534 // *All* loop passes must preserve it, in order to be able to use it. 535 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 536 /*UseMemorySSA=*/false, 537 /*UseBlockFrequencyInfo=*/false)); 538 539 // Delete small array after loop unroll. 540 FPM.addPass(SROAPass()); 541 542 // The matrix extension can introduce large vector operations early, which can 543 // benefit from running vector-combine early on. 544 if (EnableMatrix) 545 FPM.addPass(VectorCombinePass(/*ScalarizationOnly=*/true)); 546 547 // Eliminate redundancies. 548 FPM.addPass(MergedLoadStoreMotionPass()); 549 if (RunNewGVN) 550 FPM.addPass(NewGVNPass()); 551 else 552 FPM.addPass(GVNPass()); 553 554 // Sparse conditional constant propagation. 555 // FIXME: It isn't clear why we do this *after* loop passes rather than 556 // before... 557 FPM.addPass(SCCPPass()); 558 559 // Delete dead bit computations (instcombine runs after to fold away the dead 560 // computations, and then ADCE will run later to exploit any new DCE 561 // opportunities that creates). 562 FPM.addPass(BDCEPass()); 563 564 // Run instcombine after redundancy and dead bit elimination to exploit 565 // opportunities opened up by them. 566 FPM.addPass(InstCombinePass()); 567 invokePeepholeEPCallbacks(FPM, Level); 568 569 // Re-consider control flow based optimizations after redundancy elimination, 570 // redo DCE, etc. 571 if (EnableDFAJumpThreading && Level.getSizeLevel() == 0) 572 FPM.addPass(DFAJumpThreadingPass()); 573 574 FPM.addPass(JumpThreadingPass()); 575 FPM.addPass(CorrelatedValuePropagationPass()); 576 577 // Finally, do an expensive DCE pass to catch all the dead code exposed by 578 // the simplifications and basic cleanup after all the simplifications. 579 // TODO: Investigate if this is too expensive. 580 FPM.addPass(ADCEPass()); 581 582 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 583 FPM.addPass(MemCpyOptPass()); 584 585 FPM.addPass(DSEPass()); 586 FPM.addPass(createFunctionToLoopPassAdaptor( 587 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 588 /*AllowSpeculation=*/true), 589 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 590 591 FPM.addPass(CoroElidePass()); 592 593 for (auto &C : ScalarOptimizerLateEPCallbacks) 594 C(FPM, Level); 595 596 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions() 597 .convertSwitchRangeToICmp(true) 598 .hoistCommonInsts(true) 599 .sinkCommonInsts(true))); 600 FPM.addPass(InstCombinePass()); 601 invokePeepholeEPCallbacks(FPM, Level); 602 603 if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt && 604 (PGOOpt->Action == PGOOptions::IRUse || 605 PGOOpt->Action == PGOOptions::SampleUse)) 606 FPM.addPass(ControlHeightReductionPass()); 607 608 return FPM; 609 } 610 611 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) { 612 MPM.addPass(CanonicalizeAliasesPass()); 613 MPM.addPass(NameAnonGlobalPass()); 614 } 615 616 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, 617 OptimizationLevel Level, bool RunProfileGen, 618 bool IsCS, std::string ProfileFile, 619 std::string ProfileRemappingFile) { 620 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!"); 621 if (!IsCS && !DisablePreInliner) { 622 InlineParams IP; 623 624 IP.DefaultThreshold = PreInlineThreshold; 625 626 // FIXME: The hint threshold has the same value used by the regular inliner 627 // when not optimzing for size. This should probably be lowered after 628 // performance testing. 629 // FIXME: this comment is cargo culted from the old pass manager, revisit). 630 IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325; 631 ModuleInlinerWrapperPass MIWP(IP); 632 CGSCCPassManager &CGPipeline = MIWP.getPM(); 633 634 FunctionPassManager FPM; 635 FPM.addPass(SROAPass()); 636 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 637 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 638 true))); // Merge & remove basic blocks. 639 FPM.addPass(InstCombinePass()); // Combine silly sequences. 640 invokePeepholeEPCallbacks(FPM, Level); 641 642 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 643 std::move(FPM), PTO.EagerlyInvalidateAnalyses)); 644 645 MPM.addPass(std::move(MIWP)); 646 647 // Delete anything that is now dead to make sure that we don't instrument 648 // dead code. Instrumentation can end up keeping dead code around and 649 // dramatically increase code size. 650 MPM.addPass(GlobalDCEPass()); 651 } 652 653 if (!RunProfileGen) { 654 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 655 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 656 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 657 // RequireAnalysisPass for PSI before subsequent non-module passes. 658 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 659 return; 660 } 661 662 // Perform PGO instrumentation. 663 MPM.addPass(PGOInstrumentationGen(IsCS)); 664 665 // Disable header duplication in loop rotation at -Oz. 666 MPM.addPass(createModuleToFunctionPassAdaptor( 667 createFunctionToLoopPassAdaptor( 668 LoopRotatePass(Level != OptimizationLevel::Oz), 669 /*UseMemorySSA=*/false, 670 /*UseBlockFrequencyInfo=*/false), 671 PTO.EagerlyInvalidateAnalyses)); 672 673 // Add the profile lowering pass. 674 InstrProfOptions Options; 675 if (!ProfileFile.empty()) 676 Options.InstrProfileOutput = ProfileFile; 677 // Do counter promotion at Level greater than O0. 678 Options.DoCounterPromotion = true; 679 Options.UseBFIInPromotion = IsCS; 680 MPM.addPass(InstrProfiling(Options, IsCS)); 681 } 682 683 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM, 684 bool RunProfileGen, bool IsCS, 685 std::string ProfileFile, 686 std::string ProfileRemappingFile) { 687 if (!RunProfileGen) { 688 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 689 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 690 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 691 // RequireAnalysisPass for PSI before subsequent non-module passes. 692 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 693 return; 694 } 695 696 // Perform PGO instrumentation. 697 MPM.addPass(PGOInstrumentationGen(IsCS)); 698 // Add the profile lowering pass. 699 InstrProfOptions Options; 700 if (!ProfileFile.empty()) 701 Options.InstrProfileOutput = ProfileFile; 702 // Do not do counter promotion at O0. 703 Options.DoCounterPromotion = false; 704 Options.UseBFIInPromotion = IsCS; 705 MPM.addPass(InstrProfiling(Options, IsCS)); 706 } 707 708 static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) { 709 return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel()); 710 } 711 712 ModuleInlinerWrapperPass 713 PassBuilder::buildInlinerPipeline(OptimizationLevel Level, 714 ThinOrFullLTOPhase Phase) { 715 InlineParams IP = getInlineParamsFromOptLevel(Level); 716 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt && 717 PGOOpt->Action == PGOOptions::SampleUse) 718 IP.HotCallSiteThreshold = 0; 719 720 if (PGOOpt) 721 IP.EnableDeferral = EnablePGOInlineDeferral; 722 723 ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst, 724 UseInlineAdvisor, MaxDevirtIterations); 725 726 // Require the GlobalsAA analysis for the module so we can query it within 727 // the CGSCC pipeline. 728 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>()); 729 // Invalidate AAManager so it can be recreated and pick up the newly available 730 // GlobalsAA. 731 MIWP.addModulePass( 732 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 733 734 // Require the ProfileSummaryAnalysis for the module so we can query it within 735 // the inliner pass. 736 MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 737 738 // Now begin the main postorder CGSCC pipeline. 739 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 740 // manager and trying to emulate its precise behavior. Much of this doesn't 741 // make a lot of sense and we should revisit the core CGSCC structure. 742 CGSCCPassManager &MainCGPipeline = MIWP.getPM(); 743 744 // Note: historically, the PruneEH pass was run first to deduce nounwind and 745 // generally clean up exception handling overhead. It isn't clear this is 746 // valuable as the inliner doesn't currently care whether it is inlining an 747 // invoke or a call. 748 749 if (AttributorRun & AttributorRunOption::CGSCC) 750 MainCGPipeline.addPass(AttributorCGSCCPass()); 751 752 // Now deduce any function attributes based in the current code. 753 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 754 755 // When at O3 add argument promotion to the pass pipeline. 756 // FIXME: It isn't at all clear why this should be limited to O3. 757 if (Level == OptimizationLevel::O3) 758 MainCGPipeline.addPass(ArgumentPromotionPass()); 759 760 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 761 // there are no OpenMP runtime calls present in the module. 762 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3) 763 MainCGPipeline.addPass(OpenMPOptCGSCCPass()); 764 765 for (auto &C : CGSCCOptimizerLateEPCallbacks) 766 C(MainCGPipeline, Level); 767 768 // Lastly, add the core function simplification pipeline nested inside the 769 // CGSCC walk. 770 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 771 buildFunctionSimplificationPipeline(Level, Phase), 772 PTO.EagerlyInvalidateAnalyses, EnableNoRerunSimplificationPipeline)); 773 774 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0)); 775 776 if (EnableNoRerunSimplificationPipeline) 777 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor( 778 InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>())); 779 780 return MIWP; 781 } 782 783 ModulePassManager 784 PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level, 785 ThinOrFullLTOPhase Phase) { 786 ModulePassManager MPM; 787 788 InlineParams IP = getInlineParamsFromOptLevel(Level); 789 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt && 790 PGOOpt->Action == PGOOptions::SampleUse) 791 IP.HotCallSiteThreshold = 0; 792 793 if (PGOOpt) 794 IP.EnableDeferral = EnablePGOInlineDeferral; 795 796 // The inline deferral logic is used to avoid losing some 797 // inlining chance in future. It is helpful in SCC inliner, in which 798 // inlining is processed in bottom-up order. 799 // While in module inliner, the inlining order is a priority-based order 800 // by default. The inline deferral is unnecessary there. So we disable the 801 // inline deferral logic in module inliner. 802 IP.EnableDeferral = false; 803 804 MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor)); 805 806 MPM.addPass(createModuleToFunctionPassAdaptor( 807 buildFunctionSimplificationPipeline(Level, Phase), 808 PTO.EagerlyInvalidateAnalyses)); 809 810 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 811 CoroSplitPass(Level != OptimizationLevel::O0))); 812 813 return MPM; 814 } 815 816 ModulePassManager 817 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, 818 ThinOrFullLTOPhase Phase) { 819 ModulePassManager MPM; 820 821 // Place pseudo probe instrumentation as the first pass of the pipeline to 822 // minimize the impact of optimization changes. 823 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 824 Phase != ThinOrFullLTOPhase::ThinLTOPostLink) 825 MPM.addPass(SampleProfileProbePass(TM)); 826 827 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse); 828 829 // In ThinLTO mode, when flattened profile is used, all the available 830 // profile information will be annotated in PreLink phase so there is 831 // no need to load the profile again in PostLink. 832 bool LoadSampleProfile = 833 HasSampleProfile && 834 !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink); 835 836 // During the ThinLTO backend phase we perform early indirect call promotion 837 // here, before globalopt. Otherwise imported available_externally functions 838 // look unreferenced and are removed. If we are going to load the sample 839 // profile then defer until later. 840 // TODO: See if we can move later and consolidate with the location where 841 // we perform ICP when we are loading a sample profile. 842 // TODO: We pass HasSampleProfile (whether there was a sample profile file 843 // passed to the compile) to the SamplePGO flag of ICP. This is used to 844 // determine whether the new direct calls are annotated with prof metadata. 845 // Ideally this should be determined from whether the IR is annotated with 846 // sample profile, and not whether the a sample profile was provided on the 847 // command line. E.g. for flattened profiles where we will not be reloading 848 // the sample profile in the ThinLTO backend, we ideally shouldn't have to 849 // provide the sample profile file. 850 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile) 851 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile)); 852 853 // Do basic inference of function attributes from known properties of system 854 // libraries and other oracles. 855 MPM.addPass(InferFunctionAttrsPass()); 856 857 // Create an early function pass manager to cleanup the output of the 858 // frontend. 859 FunctionPassManager EarlyFPM; 860 // Lower llvm.expect to metadata before attempting transforms. 861 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 862 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 863 EarlyFPM.addPass(SimplifyCFGPass()); 864 EarlyFPM.addPass(SROAPass()); 865 EarlyFPM.addPass(EarlyCSEPass()); 866 EarlyFPM.addPass(CoroEarlyPass()); 867 if (Level == OptimizationLevel::O3) 868 EarlyFPM.addPass(CallSiteSplittingPass()); 869 870 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation 871 // to convert bitcast to direct calls so that they can be inlined during the 872 // profile annotation prepration step. 873 // More details about SamplePGO design can be found in: 874 // https://research.google.com/pubs/pub45290.html 875 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured. 876 if (LoadSampleProfile) 877 EarlyFPM.addPass(InstCombinePass()); 878 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM), 879 PTO.EagerlyInvalidateAnalyses)); 880 881 if (LoadSampleProfile) { 882 // Annotate sample profile right after early FPM to ensure freshness of 883 // the debug info. 884 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 885 PGOOpt->ProfileRemappingFile, Phase)); 886 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 887 // RequireAnalysisPass for PSI before subsequent non-module passes. 888 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 889 // Do not invoke ICP in the LTOPrelink phase as it makes it hard 890 // for the profile annotation to be accurate in the LTO backend. 891 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink && 892 Phase != ThinOrFullLTOPhase::FullLTOPreLink) 893 // We perform early indirect call promotion here, before globalopt. 894 // This is important for the ThinLTO backend phase because otherwise 895 // imported available_externally functions look unreferenced and are 896 // removed. 897 MPM.addPass( 898 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */)); 899 } 900 901 // Try to perform OpenMP specific optimizations on the module. This is a 902 // (quick!) no-op if there are no OpenMP runtime calls present in the module. 903 if (Level != OptimizationLevel::O0) 904 MPM.addPass(OpenMPOptPass()); 905 906 if (AttributorRun & AttributorRunOption::MODULE) 907 MPM.addPass(AttributorPass()); 908 909 // Lower type metadata and the type.test intrinsic in the ThinLTO 910 // post link pipeline after ICP. This is to enable usage of the type 911 // tests in ICP sequences. 912 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink) 913 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 914 915 for (auto &C : PipelineEarlySimplificationEPCallbacks) 916 C(MPM, Level); 917 918 // Specialize functions with IPSCCP. 919 if (EnableFunctionSpecialization && Level == OptimizationLevel::O3) 920 MPM.addPass(FunctionSpecializationPass()); 921 922 // Interprocedural constant propagation now that basic cleanup has occurred 923 // and prior to optimizing globals. 924 // FIXME: This position in the pipeline hasn't been carefully considered in 925 // years, it should be re-analyzed. 926 MPM.addPass(IPSCCPPass()); 927 928 // Attach metadata to indirect call sites indicating the set of functions 929 // they may target at run-time. This should follow IPSCCP. 930 MPM.addPass(CalledValuePropagationPass()); 931 932 // Optimize globals to try and fold them into constants. 933 MPM.addPass(GlobalOptPass()); 934 935 // Promote any localized globals to SSA registers. 936 // FIXME: Should this instead by a run of SROA? 937 // FIXME: We should probably run instcombine and simplifycfg afterward to 938 // delete control flows that are dead once globals have been folded to 939 // constants. 940 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 941 942 // Remove any dead arguments exposed by cleanups and constant folding 943 // globals. 944 MPM.addPass(DeadArgumentEliminationPass()); 945 946 // Create a small function pass pipeline to cleanup after all the global 947 // optimizations. 948 FunctionPassManager GlobalCleanupPM; 949 GlobalCleanupPM.addPass(InstCombinePass()); 950 invokePeepholeEPCallbacks(GlobalCleanupPM, Level); 951 952 GlobalCleanupPM.addPass( 953 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 954 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM), 955 PTO.EagerlyInvalidateAnalyses)); 956 957 // Add all the requested passes for instrumentation PGO, if requested. 958 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 959 (PGOOpt->Action == PGOOptions::IRInstr || 960 PGOOpt->Action == PGOOptions::IRUse)) { 961 addPGOInstrPasses(MPM, Level, 962 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr, 963 /* IsCS */ false, PGOOpt->ProfileFile, 964 PGOOpt->ProfileRemappingFile); 965 MPM.addPass(PGOIndirectCallPromotion(false, false)); 966 } 967 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 968 PGOOpt->CSAction == PGOOptions::CSIRInstr) 969 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile)); 970 971 // Synthesize function entry counts for non-PGO compilation. 972 if (EnableSyntheticCounts && !PGOOpt) 973 MPM.addPass(SyntheticCountsPropagation()); 974 975 if (EnableModuleInliner) 976 MPM.addPass(buildModuleInlinerPipeline(Level, Phase)); 977 else 978 MPM.addPass(buildInlinerPipeline(Level, Phase)); 979 980 if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) { 981 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 982 MPM.addPass(ModuleMemProfilerPass()); 983 } 984 985 return MPM; 986 } 987 988 /// TODO: Should LTO cause any differences to this set of passes? 989 void PassBuilder::addVectorPasses(OptimizationLevel Level, 990 FunctionPassManager &FPM, bool IsFullLTO) { 991 FPM.addPass(LoopVectorizePass( 992 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization))); 993 994 if (IsFullLTO) { 995 // The vectorizer may have significantly shortened a loop body; unroll 996 // again. Unroll small loops to hide loop backedge latency and saturate any 997 // parallel execution resources of an out-of-order processor. We also then 998 // need to clean up redundancies and loop invariant code. 999 // FIXME: It would be really good to use a loop-integrated instruction 1000 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1001 // across the loop nests. 1002 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1003 if (EnableUnrollAndJam && PTO.LoopUnrolling) 1004 FPM.addPass(createFunctionToLoopPassAdaptor( 1005 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 1006 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 1007 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1008 PTO.ForgetAllSCEVInLoopUnroll))); 1009 FPM.addPass(WarnMissedTransformationsPass()); 1010 } 1011 1012 if (!IsFullLTO) { 1013 // Eliminate loads by forwarding stores from the previous iteration to loads 1014 // of the current iteration. 1015 FPM.addPass(LoopLoadEliminationPass()); 1016 } 1017 // Cleanup after the loop optimization passes. 1018 FPM.addPass(InstCombinePass()); 1019 1020 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 1021 ExtraVectorPassManager ExtraPasses; 1022 // At higher optimization levels, try to clean up any runtime overlap and 1023 // alignment checks inserted by the vectorizer. We want to track correlated 1024 // runtime checks for two inner loops in the same outer loop, fold any 1025 // common computations, hoist loop-invariant aspects out of any outer loop, 1026 // and unswitch the runtime checks if possible. Once hoisted, we may have 1027 // dead (or speculatable) control flows or more combining opportunities. 1028 ExtraPasses.addPass(EarlyCSEPass()); 1029 ExtraPasses.addPass(CorrelatedValuePropagationPass()); 1030 ExtraPasses.addPass(InstCombinePass()); 1031 LoopPassManager LPM; 1032 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 1033 /*AllowSpeculation=*/true)); 1034 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level == 1035 OptimizationLevel::O3)); 1036 ExtraPasses.addPass( 1037 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1038 ExtraPasses.addPass( 1039 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true, 1040 /*UseBlockFrequencyInfo=*/true)); 1041 ExtraPasses.addPass( 1042 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 1043 ExtraPasses.addPass(InstCombinePass()); 1044 FPM.addPass(std::move(ExtraPasses)); 1045 } 1046 1047 // Now that we've formed fast to execute loop structures, we do further 1048 // optimizations. These are run afterward as they might block doing complex 1049 // analyses and transforms such as what are needed for loop vectorization. 1050 1051 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 1052 // GVN, loop transforms, and others have already run, so it's now better to 1053 // convert to more optimized IR using more aggressive simplify CFG options. 1054 // The extra sinking transform can create larger basic blocks, so do this 1055 // before SLP vectorization. 1056 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions() 1057 .forwardSwitchCondToPhi(true) 1058 .convertSwitchRangeToICmp(true) 1059 .convertSwitchToLookupTable(true) 1060 .needCanonicalLoops(false) 1061 .hoistCommonInsts(true) 1062 .sinkCommonInsts(true))); 1063 1064 if (IsFullLTO) { 1065 FPM.addPass(SCCPPass()); 1066 FPM.addPass(InstCombinePass()); 1067 FPM.addPass(BDCEPass()); 1068 } 1069 1070 // Optimize parallel scalar instruction chains into SIMD instructions. 1071 if (PTO.SLPVectorization) { 1072 FPM.addPass(SLPVectorizerPass()); 1073 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 1074 FPM.addPass(EarlyCSEPass()); 1075 } 1076 } 1077 // Enhance/cleanup vector code. 1078 FPM.addPass(VectorCombinePass()); 1079 1080 if (!IsFullLTO) { 1081 FPM.addPass(InstCombinePass()); 1082 // Unroll small loops to hide loop backedge latency and saturate any 1083 // parallel execution resources of an out-of-order processor. We also then 1084 // need to clean up redundancies and loop invariant code. 1085 // FIXME: It would be really good to use a loop-integrated instruction 1086 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1087 // across the loop nests. 1088 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1089 if (EnableUnrollAndJam && PTO.LoopUnrolling) { 1090 FPM.addPass(createFunctionToLoopPassAdaptor( 1091 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 1092 } 1093 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 1094 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1095 PTO.ForgetAllSCEVInLoopUnroll))); 1096 FPM.addPass(WarnMissedTransformationsPass()); 1097 FPM.addPass(InstCombinePass()); 1098 FPM.addPass( 1099 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1100 FPM.addPass(createFunctionToLoopPassAdaptor( 1101 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 1102 /*AllowSpeculation=*/true), 1103 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1104 } 1105 1106 // Now that we've vectorized and unrolled loops, we may have more refined 1107 // alignment information, try to re-derive it here. 1108 FPM.addPass(AlignmentFromAssumptionsPass()); 1109 1110 if (IsFullLTO) 1111 FPM.addPass(InstCombinePass()); 1112 } 1113 1114 ModulePassManager 1115 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, 1116 bool LTOPreLink) { 1117 ModulePassManager MPM; 1118 1119 // Optimize globals now that the module is fully simplified. 1120 MPM.addPass(GlobalOptPass()); 1121 MPM.addPass(GlobalDCEPass()); 1122 1123 // Run partial inlining pass to partially inline functions that have 1124 // large bodies. 1125 if (RunPartialInlining) 1126 MPM.addPass(PartialInlinerPass()); 1127 1128 // Remove avail extern fns and globals definitions since we aren't compiling 1129 // an object file for later LTO. For LTO we want to preserve these so they 1130 // are eligible for inlining at link-time. Note if they are unreferenced they 1131 // will be removed by GlobalDCE later, so this only impacts referenced 1132 // available externally globals. Eventually they will be suppressed during 1133 // codegen, but eliminating here enables more opportunity for GlobalDCE as it 1134 // may make globals referenced by available external functions dead and saves 1135 // running remaining passes on the eliminated functions. These should be 1136 // preserved during prelinking for link-time inlining decisions. 1137 if (!LTOPreLink) 1138 MPM.addPass(EliminateAvailableExternallyPass()); 1139 1140 if (EnableOrderFileInstrumentation) 1141 MPM.addPass(InstrOrderFilePass()); 1142 1143 // Do RPO function attribute inference across the module to forward-propagate 1144 // attributes where applicable. 1145 // FIXME: Is this really an optimization rather than a canonicalization? 1146 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1147 1148 // Do a post inline PGO instrumentation and use pass. This is a context 1149 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as 1150 // cross-module inline has not been done yet. The context sensitive 1151 // instrumentation is after all the inlines are done. 1152 if (!LTOPreLink && PGOOpt) { 1153 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1154 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1155 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1156 PGOOpt->ProfileRemappingFile); 1157 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1158 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1159 /* IsCS */ true, PGOOpt->ProfileFile, 1160 PGOOpt->ProfileRemappingFile); 1161 } 1162 1163 // Re-compute GlobalsAA here prior to function passes. This is particularly 1164 // useful as the above will have inlined, DCE'ed, and function-attr 1165 // propagated everything. We should at this point have a reasonably minimal 1166 // and richly annotated call graph. By computing aliasing and mod/ref 1167 // information for all local globals here, the late loop passes and notably 1168 // the vectorizer will be able to use them to help recognize vectorizable 1169 // memory operations. 1170 MPM.addPass(RecomputeGlobalsAAPass()); 1171 1172 for (auto &C : OptimizerEarlyEPCallbacks) 1173 C(MPM, Level); 1174 1175 FunctionPassManager OptimizePM; 1176 OptimizePM.addPass(Float2IntPass()); 1177 OptimizePM.addPass(LowerConstantIntrinsicsPass()); 1178 1179 if (EnableMatrix) { 1180 OptimizePM.addPass(LowerMatrixIntrinsicsPass()); 1181 OptimizePM.addPass(EarlyCSEPass()); 1182 } 1183 1184 // FIXME: We need to run some loop optimizations to re-rotate loops after 1185 // simplifycfg and others undo their rotation. 1186 1187 // Optimize the loop execution. These passes operate on entire loop nests 1188 // rather than on each loop in an inside-out manner, and so they are actually 1189 // function passes. 1190 1191 for (auto &C : VectorizerStartEPCallbacks) 1192 C(OptimizePM, Level); 1193 1194 LoopPassManager LPM; 1195 // First rotate loops that may have been un-rotated by prior passes. 1196 // Disable header duplication at -Oz. 1197 LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink)); 1198 // Some loops may have become dead by now. Try to delete them. 1199 // FIXME: see discussion in https://reviews.llvm.org/D112851, 1200 // this may need to be revisited once we run GVN before loop deletion 1201 // in the simplification pipeline. 1202 LPM.addPass(LoopDeletionPass()); 1203 OptimizePM.addPass(createFunctionToLoopPassAdaptor( 1204 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false)); 1205 1206 // Distribute loops to allow partial vectorization. I.e. isolate dependences 1207 // into separate loop that would otherwise inhibit vectorization. This is 1208 // currently only performed for loops marked with the metadata 1209 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 1210 OptimizePM.addPass(LoopDistributePass()); 1211 1212 // Populates the VFABI attribute with the scalar-to-vector mappings 1213 // from the TargetLibraryInfo. 1214 OptimizePM.addPass(InjectTLIMappings()); 1215 1216 addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false); 1217 1218 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 1219 // canonicalization pass that enables other optimizations. As a result, 1220 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 1221 // result too early. 1222 OptimizePM.addPass(LoopSinkPass()); 1223 1224 // And finally clean up LCSSA form before generating code. 1225 OptimizePM.addPass(InstSimplifyPass()); 1226 1227 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 1228 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 1229 // flattening of blocks. 1230 OptimizePM.addPass(DivRemPairsPass()); 1231 1232 // LoopSink (and other loop passes since the last simplifyCFG) might have 1233 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 1234 OptimizePM.addPass( 1235 SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 1236 1237 OptimizePM.addPass(CoroCleanupPass()); 1238 1239 // Add the core optimizing pipeline. 1240 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM), 1241 PTO.EagerlyInvalidateAnalyses)); 1242 1243 for (auto &C : OptimizerLastEPCallbacks) 1244 C(MPM, Level); 1245 1246 // Split out cold code. Splitting is done late to avoid hiding context from 1247 // other optimizations and inadvertently regressing performance. The tradeoff 1248 // is that this has a higher code size cost than splitting early. 1249 if (EnableHotColdSplit && !LTOPreLink) 1250 MPM.addPass(HotColdSplittingPass()); 1251 1252 // Search the code for similar regions of code. If enough similar regions can 1253 // be found where extracting the regions into their own function will decrease 1254 // the size of the program, we extract the regions, a deduplicate the 1255 // structurally similar regions. 1256 if (EnableIROutliner) 1257 MPM.addPass(IROutlinerPass()); 1258 1259 // Merge functions if requested. 1260 if (PTO.MergeFunctions) 1261 MPM.addPass(MergeFunctionsPass()); 1262 1263 if (PTO.CallGraphProfile) 1264 MPM.addPass(CGProfilePass()); 1265 1266 // Now we need to do some global optimization transforms. 1267 // FIXME: It would seem like these should come first in the optimization 1268 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 1269 // ordering here. 1270 MPM.addPass(GlobalDCEPass()); 1271 MPM.addPass(ConstantMergePass()); 1272 1273 // TODO: Relative look table converter pass caused an issue when full lto is 1274 // enabled. See https://reviews.llvm.org/D94355 for more details. 1275 // Until the issue fixed, disable this pass during pre-linking phase. 1276 if (!LTOPreLink) 1277 MPM.addPass(RelLookupTableConverterPass()); 1278 1279 return MPM; 1280 } 1281 1282 ModulePassManager 1283 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 1284 bool LTOPreLink) { 1285 assert(Level != OptimizationLevel::O0 && 1286 "Must request optimizations for the default pipeline!"); 1287 1288 ModulePassManager MPM; 1289 1290 // Convert @llvm.global.annotations to !annotation metadata. 1291 MPM.addPass(Annotation2MetadataPass()); 1292 1293 // Force any function attributes we want the rest of the pipeline to observe. 1294 MPM.addPass(ForceFunctionAttrsPass()); 1295 1296 // Apply module pipeline start EP callback. 1297 for (auto &C : PipelineStartEPCallbacks) 1298 C(MPM, Level); 1299 1300 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1301 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1302 1303 // Add the core simplification pipeline. 1304 MPM.addPass(buildModuleSimplificationPipeline( 1305 Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink 1306 : ThinOrFullLTOPhase::None)); 1307 1308 // Now add the optimization pipeline. 1309 MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink)); 1310 1311 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 1312 PGOOpt->Action == PGOOptions::SampleUse) 1313 MPM.addPass(PseudoProbeUpdatePass()); 1314 1315 // Emit annotation remarks. 1316 addAnnotationRemarksPass(MPM); 1317 1318 if (LTOPreLink) 1319 addRequiredLTOPreLinkPasses(MPM); 1320 1321 return MPM; 1322 } 1323 1324 ModulePassManager 1325 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1326 assert(Level != OptimizationLevel::O0 && 1327 "Must request optimizations for the default pipeline!"); 1328 1329 ModulePassManager MPM; 1330 1331 // Convert @llvm.global.annotations to !annotation metadata. 1332 MPM.addPass(Annotation2MetadataPass()); 1333 1334 // Force any function attributes we want the rest of the pipeline to observe. 1335 MPM.addPass(ForceFunctionAttrsPass()); 1336 1337 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1338 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1339 1340 // Apply module pipeline start EP callback. 1341 for (auto &C : PipelineStartEPCallbacks) 1342 C(MPM, Level); 1343 1344 // If we are planning to perform ThinLTO later, we don't bloat the code with 1345 // unrolling/vectorization/... now. Just simplify the module as much as we 1346 // can. 1347 MPM.addPass(buildModuleSimplificationPipeline( 1348 Level, ThinOrFullLTOPhase::ThinLTOPreLink)); 1349 1350 // Run partial inlining pass to partially inline functions that have 1351 // large bodies. 1352 // FIXME: It isn't clear whether this is really the right place to run this 1353 // in ThinLTO. Because there is another canonicalization and simplification 1354 // phase that will run after the thin link, running this here ends up with 1355 // less information than will be available later and it may grow functions in 1356 // ways that aren't beneficial. 1357 if (RunPartialInlining) 1358 MPM.addPass(PartialInlinerPass()); 1359 1360 // Reduce the size of the IR as much as possible. 1361 MPM.addPass(GlobalOptPass()); 1362 1363 // Module simplification splits coroutines, but does not fully clean up 1364 // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up 1365 // on these, we schedule the cleanup here. 1366 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1367 1368 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 1369 PGOOpt->Action == PGOOptions::SampleUse) 1370 MPM.addPass(PseudoProbeUpdatePass()); 1371 1372 // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual 1373 // optimization is going to be done in PostLink stage, but clang can't 1374 // add callbacks there in case of in-process ThinLTO called by linker. 1375 for (auto &C : OptimizerLastEPCallbacks) 1376 C(MPM, Level); 1377 1378 // Emit annotation remarks. 1379 addAnnotationRemarksPass(MPM); 1380 1381 addRequiredLTOPreLinkPasses(MPM); 1382 1383 return MPM; 1384 } 1385 1386 ModulePassManager PassBuilder::buildThinLTODefaultPipeline( 1387 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) { 1388 ModulePassManager MPM; 1389 1390 // Convert @llvm.global.annotations to !annotation metadata. 1391 MPM.addPass(Annotation2MetadataPass()); 1392 1393 if (ImportSummary) { 1394 // These passes import type identifier resolutions for whole-program 1395 // devirtualization and CFI. They must run early because other passes may 1396 // disturb the specific instruction patterns that these passes look for, 1397 // creating dependencies on resolutions that may not appear in the summary. 1398 // 1399 // For example, GVN may transform the pattern assume(type.test) appearing in 1400 // two basic blocks into assume(phi(type.test, type.test)), which would 1401 // transform a dependency on a WPD resolution into a dependency on a type 1402 // identifier resolution for CFI. 1403 // 1404 // Also, WPD has access to more precise information than ICP and can 1405 // devirtualize more effectively, so it should operate on the IR first. 1406 // 1407 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1408 // metadata and intrinsics. 1409 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary)); 1410 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary)); 1411 } 1412 1413 if (Level == OptimizationLevel::O0) { 1414 // Run a second time to clean up any type tests left behind by WPD for use 1415 // in ICP. 1416 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1417 // Drop available_externally and unreferenced globals. This is necessary 1418 // with ThinLTO in order to avoid leaving undefined references to dead 1419 // globals in the object file. 1420 MPM.addPass(EliminateAvailableExternallyPass()); 1421 MPM.addPass(GlobalDCEPass()); 1422 return MPM; 1423 } 1424 1425 // Force any function attributes we want the rest of the pipeline to observe. 1426 MPM.addPass(ForceFunctionAttrsPass()); 1427 1428 // Add the core simplification pipeline. 1429 MPM.addPass(buildModuleSimplificationPipeline( 1430 Level, ThinOrFullLTOPhase::ThinLTOPostLink)); 1431 1432 // Now add the optimization pipeline. 1433 MPM.addPass(buildModuleOptimizationPipeline(Level)); 1434 1435 // Emit annotation remarks. 1436 addAnnotationRemarksPass(MPM); 1437 1438 return MPM; 1439 } 1440 1441 ModulePassManager 1442 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1443 assert(Level != OptimizationLevel::O0 && 1444 "Must request optimizations for the default pipeline!"); 1445 // FIXME: We should use a customized pre-link pipeline! 1446 return buildPerModuleDefaultPipeline(Level, 1447 /* LTOPreLink */ true); 1448 } 1449 1450 ModulePassManager 1451 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, 1452 ModuleSummaryIndex *ExportSummary) { 1453 ModulePassManager MPM; 1454 1455 // Convert @llvm.global.annotations to !annotation metadata. 1456 MPM.addPass(Annotation2MetadataPass()); 1457 1458 for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks) 1459 C(MPM, Level); 1460 1461 // Create a function that performs CFI checks for cross-DSO calls with targets 1462 // in the current module. 1463 MPM.addPass(CrossDSOCFIPass()); 1464 1465 if (Level == OptimizationLevel::O0) { 1466 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1467 // metadata and intrinsics. 1468 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1469 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1470 // Run a second time to clean up any type tests left behind by WPD for use 1471 // in ICP. 1472 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1473 1474 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks) 1475 C(MPM, Level); 1476 1477 // Emit annotation remarks. 1478 addAnnotationRemarksPass(MPM); 1479 1480 return MPM; 1481 } 1482 1483 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) { 1484 // Load sample profile before running the LTO optimization pipeline. 1485 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 1486 PGOOpt->ProfileRemappingFile, 1487 ThinOrFullLTOPhase::FullLTOPostLink)); 1488 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 1489 // RequireAnalysisPass for PSI before subsequent non-module passes. 1490 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1491 } 1492 1493 // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present. 1494 MPM.addPass(OpenMPOptPass()); 1495 1496 // Remove unused virtual tables to improve the quality of code generated by 1497 // whole-program devirtualization and bitset lowering. 1498 MPM.addPass(GlobalDCEPass()); 1499 1500 // Force any function attributes we want the rest of the pipeline to observe. 1501 MPM.addPass(ForceFunctionAttrsPass()); 1502 1503 // Do basic inference of function attributes from known properties of system 1504 // libraries and other oracles. 1505 MPM.addPass(InferFunctionAttrsPass()); 1506 1507 if (Level.getSpeedupLevel() > 1) { 1508 MPM.addPass(createModuleToFunctionPassAdaptor( 1509 CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses)); 1510 1511 // Indirect call promotion. This should promote all the targets that are 1512 // left by the earlier promotion pass that promotes intra-module targets. 1513 // This two-step promotion is to save the compile time. For LTO, it should 1514 // produce the same result as if we only do promotion here. 1515 MPM.addPass(PGOIndirectCallPromotion( 1516 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)); 1517 1518 if (EnableFunctionSpecialization && Level == OptimizationLevel::O3) 1519 MPM.addPass(FunctionSpecializationPass()); 1520 // Propagate constants at call sites into the functions they call. This 1521 // opens opportunities for globalopt (and inlining) by substituting function 1522 // pointers passed as arguments to direct uses of functions. 1523 MPM.addPass(IPSCCPPass()); 1524 1525 // Attach metadata to indirect call sites indicating the set of functions 1526 // they may target at run-time. This should follow IPSCCP. 1527 MPM.addPass(CalledValuePropagationPass()); 1528 } 1529 1530 // Now deduce any function attributes based in the current code. 1531 MPM.addPass( 1532 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass())); 1533 1534 // Do RPO function attribute inference across the module to forward-propagate 1535 // attributes where applicable. 1536 // FIXME: Is this really an optimization rather than a canonicalization? 1537 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1538 1539 // Use in-range annotations on GEP indices to split globals where beneficial. 1540 MPM.addPass(GlobalSplitPass()); 1541 1542 // Run whole program optimization of virtual call when the list of callees 1543 // is fixed. 1544 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1545 1546 // Stop here at -O1. 1547 if (Level == OptimizationLevel::O1) { 1548 // The LowerTypeTestsPass needs to run to lower type metadata and the 1549 // type.test intrinsics. The pass does nothing if CFI is disabled. 1550 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1551 // Run a second time to clean up any type tests left behind by WPD for use 1552 // in ICP (which is performed earlier than this in the regular LTO 1553 // pipeline). 1554 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1555 1556 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks) 1557 C(MPM, Level); 1558 1559 // Emit annotation remarks. 1560 addAnnotationRemarksPass(MPM); 1561 1562 return MPM; 1563 } 1564 1565 // Optimize globals to try and fold them into constants. 1566 MPM.addPass(GlobalOptPass()); 1567 1568 // Promote any localized globals to SSA registers. 1569 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1570 1571 // Linking modules together can lead to duplicate global constant, only 1572 // keep one copy of each constant. 1573 MPM.addPass(ConstantMergePass()); 1574 1575 // Remove unused arguments from functions. 1576 MPM.addPass(DeadArgumentEliminationPass()); 1577 1578 // Reduce the code after globalopt and ipsccp. Both can open up significant 1579 // simplification opportunities, and both can propagate functions through 1580 // function pointers. When this happens, we often have to resolve varargs 1581 // calls, etc, so let instcombine do this. 1582 FunctionPassManager PeepholeFPM; 1583 PeepholeFPM.addPass(InstCombinePass()); 1584 if (Level == OptimizationLevel::O3) 1585 PeepholeFPM.addPass(AggressiveInstCombinePass()); 1586 invokePeepholeEPCallbacks(PeepholeFPM, Level); 1587 1588 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM), 1589 PTO.EagerlyInvalidateAnalyses)); 1590 1591 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1592 // generally clean up exception handling overhead. It isn't clear this is 1593 // valuable as the inliner doesn't currently care whether it is inlining an 1594 // invoke or a call. 1595 // Run the inliner now. 1596 MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level))); 1597 1598 // Optimize globals again after we ran the inliner. 1599 MPM.addPass(GlobalOptPass()); 1600 1601 // Garbage collect dead functions. 1602 MPM.addPass(GlobalDCEPass()); 1603 1604 // If we didn't decide to inline a function, check to see if we can 1605 // transform it to pass arguments by value instead of by reference. 1606 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass())); 1607 1608 FunctionPassManager FPM; 1609 // The IPO Passes may leave cruft around. Clean up after them. 1610 FPM.addPass(InstCombinePass()); 1611 invokePeepholeEPCallbacks(FPM, Level); 1612 1613 FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1614 1615 // Do a post inline PGO instrumentation and use pass. This is a context 1616 // sensitive PGO pass. 1617 if (PGOOpt) { 1618 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1619 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1620 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1621 PGOOpt->ProfileRemappingFile); 1622 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1623 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1624 /* IsCS */ true, PGOOpt->ProfileFile, 1625 PGOOpt->ProfileRemappingFile); 1626 } 1627 1628 // Break up allocas 1629 FPM.addPass(SROAPass()); 1630 1631 // LTO provides additional opportunities for tailcall elimination due to 1632 // link-time inlining, and visibility of nocapture attribute. 1633 FPM.addPass(TailCallElimPass()); 1634 1635 // Run a few AA driver optimizations here and now to cleanup the code. 1636 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM), 1637 PTO.EagerlyInvalidateAnalyses)); 1638 1639 MPM.addPass( 1640 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass())); 1641 1642 // Require the GlobalsAA analysis for the module so we can query it within 1643 // MainFPM. 1644 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 1645 // Invalidate AAManager so it can be recreated and pick up the newly available 1646 // GlobalsAA. 1647 MPM.addPass( 1648 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 1649 1650 FunctionPassManager MainFPM; 1651 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1652 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap, 1653 /*AllowSpeculation=*/true), 1654 /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1655 1656 if (RunNewGVN) 1657 MainFPM.addPass(NewGVNPass()); 1658 else 1659 MainFPM.addPass(GVNPass()); 1660 1661 // Remove dead memcpy()'s. 1662 MainFPM.addPass(MemCpyOptPass()); 1663 1664 // Nuke dead stores. 1665 MainFPM.addPass(DSEPass()); 1666 MainFPM.addPass(MergedLoadStoreMotionPass()); 1667 1668 1669 if (EnableConstraintElimination) 1670 MainFPM.addPass(ConstraintEliminationPass()); 1671 1672 LoopPassManager LPM; 1673 if (EnableLoopFlatten && Level.getSpeedupLevel() > 1) 1674 LPM.addPass(LoopFlattenPass()); 1675 LPM.addPass(IndVarSimplifyPass()); 1676 LPM.addPass(LoopDeletionPass()); 1677 // FIXME: Add loop interchange. 1678 1679 // Unroll small loops and perform peeling. 1680 LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 1681 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 1682 PTO.ForgetAllSCEVInLoopUnroll)); 1683 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA. 1684 // *All* loop passes must preserve it, in order to be able to use it. 1685 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1686 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true)); 1687 1688 MainFPM.addPass(LoopDistributePass()); 1689 1690 addVectorPasses(Level, MainFPM, /* IsFullLTO */ true); 1691 1692 // Run the OpenMPOpt CGSCC pass again late. 1693 MPM.addPass( 1694 createModuleToPostOrderCGSCCPassAdaptor(OpenMPOptCGSCCPass())); 1695 1696 invokePeepholeEPCallbacks(MainFPM, Level); 1697 MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1698 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM), 1699 PTO.EagerlyInvalidateAnalyses)); 1700 1701 // Lower type metadata and the type.test intrinsic. This pass supports 1702 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 1703 // to be run at link time if CFI is enabled. This pass does nothing if 1704 // CFI is disabled. 1705 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1706 // Run a second time to clean up any type tests left behind by WPD for use 1707 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1708 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1709 1710 // Enable splitting late in the FullLTO post-link pipeline. This is done in 1711 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses). 1712 if (EnableHotColdSplit) 1713 MPM.addPass(HotColdSplittingPass()); 1714 1715 // Add late LTO optimization passes. 1716 // Delete basic blocks, which optimization passes may have killed. 1717 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass( 1718 SimplifyCFGOptions().convertSwitchRangeToICmp(true).hoistCommonInsts( 1719 true)))); 1720 1721 // Drop bodies of available eternally objects to improve GlobalDCE. 1722 MPM.addPass(EliminateAvailableExternallyPass()); 1723 1724 // Now that we have optimized the program, discard unreachable functions. 1725 MPM.addPass(GlobalDCEPass()); 1726 1727 if (PTO.MergeFunctions) 1728 MPM.addPass(MergeFunctionsPass()); 1729 1730 for (auto &C : FullLinkTimeOptimizationLastEPCallbacks) 1731 C(MPM, Level); 1732 1733 // Emit annotation remarks. 1734 addAnnotationRemarksPass(MPM); 1735 1736 return MPM; 1737 } 1738 1739 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level, 1740 bool LTOPreLink) { 1741 assert(Level == OptimizationLevel::O0 && 1742 "buildO0DefaultPipeline should only be used with O0"); 1743 1744 ModulePassManager MPM; 1745 1746 // Perform pseudo probe instrumentation in O0 mode. This is for the 1747 // consistency between different build modes. For example, a LTO build can be 1748 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in 1749 // the postlink will require pseudo probe instrumentation in the prelink. 1750 if (PGOOpt && PGOOpt->PseudoProbeForProfiling) 1751 MPM.addPass(SampleProfileProbePass(TM)); 1752 1753 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || 1754 PGOOpt->Action == PGOOptions::IRUse)) 1755 addPGOInstrPassesForO0( 1756 MPM, 1757 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1758 /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); 1759 1760 for (auto &C : PipelineStartEPCallbacks) 1761 C(MPM, Level); 1762 1763 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1764 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1765 1766 for (auto &C : PipelineEarlySimplificationEPCallbacks) 1767 C(MPM, Level); 1768 1769 // Build a minimal pipeline based on the semantics required by LLVM, 1770 // which is just that always inlining occurs. Further, disable generating 1771 // lifetime intrinsics to avoid enabling further optimizations during 1772 // code generation. 1773 MPM.addPass(AlwaysInlinerPass( 1774 /*InsertLifetimeIntrinsics=*/false)); 1775 1776 if (PTO.MergeFunctions) 1777 MPM.addPass(MergeFunctionsPass()); 1778 1779 if (EnableMatrix) 1780 MPM.addPass( 1781 createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true))); 1782 1783 if (!CGSCCOptimizerLateEPCallbacks.empty()) { 1784 CGSCCPassManager CGPM; 1785 for (auto &C : CGSCCOptimizerLateEPCallbacks) 1786 C(CGPM, Level); 1787 if (!CGPM.isEmpty()) 1788 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1789 } 1790 if (!LateLoopOptimizationsEPCallbacks.empty()) { 1791 LoopPassManager LPM; 1792 for (auto &C : LateLoopOptimizationsEPCallbacks) 1793 C(LPM, Level); 1794 if (!LPM.isEmpty()) { 1795 MPM.addPass(createModuleToFunctionPassAdaptor( 1796 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1797 } 1798 } 1799 if (!LoopOptimizerEndEPCallbacks.empty()) { 1800 LoopPassManager LPM; 1801 for (auto &C : LoopOptimizerEndEPCallbacks) 1802 C(LPM, Level); 1803 if (!LPM.isEmpty()) { 1804 MPM.addPass(createModuleToFunctionPassAdaptor( 1805 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1806 } 1807 } 1808 if (!ScalarOptimizerLateEPCallbacks.empty()) { 1809 FunctionPassManager FPM; 1810 for (auto &C : ScalarOptimizerLateEPCallbacks) 1811 C(FPM, Level); 1812 if (!FPM.isEmpty()) 1813 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1814 } 1815 1816 for (auto &C : OptimizerEarlyEPCallbacks) 1817 C(MPM, Level); 1818 1819 if (!VectorizerStartEPCallbacks.empty()) { 1820 FunctionPassManager FPM; 1821 for (auto &C : VectorizerStartEPCallbacks) 1822 C(FPM, Level); 1823 if (!FPM.isEmpty()) 1824 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1825 } 1826 1827 ModulePassManager CoroPM; 1828 CoroPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1829 CGSCCPassManager CGPM; 1830 CGPM.addPass(CoroSplitPass()); 1831 CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1832 CoroPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1833 CoroPM.addPass(GlobalDCEPass()); 1834 MPM.addPass(CoroConditionalWrapper(std::move(CoroPM))); 1835 1836 for (auto &C : OptimizerLastEPCallbacks) 1837 C(MPM, Level); 1838 1839 if (LTOPreLink) 1840 addRequiredLTOPreLinkPasses(MPM); 1841 1842 MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass())); 1843 1844 return MPM; 1845 } 1846 1847 AAManager PassBuilder::buildDefaultAAPipeline() { 1848 AAManager AA; 1849 1850 // The order in which these are registered determines their priority when 1851 // being queried. 1852 1853 // First we register the basic alias analysis that provides the majority of 1854 // per-function local AA logic. This is a stateless, on-demand local set of 1855 // AA techniques. 1856 AA.registerFunctionAnalysis<BasicAA>(); 1857 1858 // Next we query fast, specialized alias analyses that wrap IR-embedded 1859 // information about aliasing. 1860 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 1861 AA.registerFunctionAnalysis<TypeBasedAA>(); 1862 1863 // Add support for querying global aliasing information when available. 1864 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 1865 // analysis, all that the `AAManager` can do is query for any *cached* 1866 // results from `GlobalsAA` through a readonly proxy. 1867 AA.registerModuleAnalysis<GlobalsAA>(); 1868 1869 // Add target-specific alias analyses. 1870 if (TM) 1871 TM->registerDefaultAliasAnalyses(AA); 1872 1873 return AA; 1874 } 1875