1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===// 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 // 9 // This file defines the PassManagerBuilder class, which is used to set up a 10 // "standard" optimization sequence suitable for languages like C and C++. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 15 #include "llvm-c/Transforms/PassManagerBuilder.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/InlineCost.h" 22 #include "llvm/Analysis/ScopedNoAliasAA.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 25 #include "llvm/IR/LegacyPassManager.h" 26 #include "llvm/IR/Verifier.h" 27 #include "llvm/Support/CommandLine.h" 28 #include "llvm/Support/ManagedStatic.h" 29 #include "llvm/Target/CGPassBuilderOption.h" 30 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 31 #include "llvm/Transforms/IPO.h" 32 #include "llvm/Transforms/IPO/Attributor.h" 33 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 34 #include "llvm/Transforms/IPO/FunctionAttrs.h" 35 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 36 #include "llvm/Transforms/InstCombine/InstCombine.h" 37 #include "llvm/Transforms/Instrumentation.h" 38 #include "llvm/Transforms/Scalar.h" 39 #include "llvm/Transforms/Scalar/GVN.h" 40 #include "llvm/Transforms/Scalar/LICM.h" 41 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 42 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 43 #include "llvm/Transforms/Utils.h" 44 #include "llvm/Transforms/Vectorize.h" 45 46 using namespace llvm; 47 48 namespace llvm { 49 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::init(false), 50 cl::Hidden, cl::ZeroOrMore, 51 cl::desc("Run Partial inlinining pass")); 52 53 static cl::opt<bool> 54 UseGVNAfterVectorization("use-gvn-after-vectorization", 55 cl::init(false), cl::Hidden, 56 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 57 58 cl::opt<bool> ExtraVectorizerPasses( 59 "extra-vectorizer-passes", cl::init(false), cl::Hidden, 60 cl::desc("Run cleanup optimization passes after vectorization.")); 61 62 static cl::opt<bool> 63 RunLoopRerolling("reroll-loops", cl::Hidden, 64 cl::desc("Run the loop rerolling pass")); 65 66 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, 67 cl::desc("Run the NewGVN pass")); 68 69 // Experimental option to use CFL-AA 70 static cl::opt<::CFLAAType> 71 UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden, 72 cl::desc("Enable the new, experimental CFL alias analysis"), 73 cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"), 74 clEnumValN(::CFLAAType::Steensgaard, "steens", 75 "Enable unification-based CFL-AA"), 76 clEnumValN(::CFLAAType::Andersen, "anders", 77 "Enable inclusion-based CFL-AA"), 78 clEnumValN(::CFLAAType::Both, "both", 79 "Enable both variants of CFL-AA"))); 80 81 cl::opt<bool> EnableLoopInterchange( 82 "enable-loopinterchange", cl::init(false), cl::Hidden, 83 cl::desc("Enable the experimental LoopInterchange Pass")); 84 85 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), 86 cl::Hidden, 87 cl::desc("Enable Unroll And Jam Pass")); 88 89 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false), 90 cl::Hidden, 91 cl::desc("Enable the LoopFlatten Pass")); 92 93 cl::opt<bool> EnableDFAJumpThreading("enable-dfa-jump-thread", 94 cl::desc("Enable DFA jump threading."), 95 cl::init(false), cl::Hidden); 96 97 static cl::opt<bool> 98 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden, 99 cl::desc("Enable preparation for ThinLTO.")); 100 101 static cl::opt<bool> 102 EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden, 103 cl::desc("Enable performing ThinLTO.")); 104 105 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false), 106 cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass")); 107 108 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, 109 cl::desc("Enable ir outliner pass")); 110 111 static cl::opt<bool> UseLoopVersioningLICM( 112 "enable-loop-versioning-licm", cl::init(false), cl::Hidden, 113 cl::desc("Enable the experimental Loop Versioning LICM pass")); 114 115 cl::opt<bool> 116 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, 117 cl::desc("Disable pre-instrumentation inliner")); 118 119 cl::opt<int> PreInlineThreshold( 120 "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore, 121 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 122 "(default = 75)")); 123 124 cl::opt<bool> 125 EnableGVNHoist("enable-gvn-hoist", cl::init(false), cl::ZeroOrMore, 126 cl::desc("Enable the GVN hoisting pass (default = off)")); 127 128 static cl::opt<bool> 129 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false), 130 cl::Hidden, 131 cl::desc("Disable shrink-wrap library calls")); 132 133 static cl::opt<bool> EnableSimpleLoopUnswitch( 134 "enable-simple-loop-unswitch", cl::init(false), cl::Hidden, 135 cl::desc("Enable the simple loop unswitch pass. Also enables independent " 136 "cleanup passes integrated into the loop pass manager pipeline.")); 137 138 cl::opt<bool> 139 EnableGVNSink("enable-gvn-sink", cl::init(false), cl::ZeroOrMore, 140 cl::desc("Enable the GVN sinking pass (default = off)")); 141 142 // This option is used in simplifying testing SampleFDO optimizations for 143 // profile loading. 144 cl::opt<bool> 145 EnableCHR("enable-chr", cl::init(true), cl::Hidden, 146 cl::desc("Enable control height reduction optimization (CHR)")); 147 148 cl::opt<bool> FlattenedProfileUsed( 149 "flattened-profile-used", cl::init(false), cl::Hidden, 150 cl::desc("Indicate the sample profile being used is flattened, i.e., " 151 "no inline hierachy exists in the profile. ")); 152 153 cl::opt<bool> EnableOrderFileInstrumentation( 154 "enable-order-file-instrumentation", cl::init(false), cl::Hidden, 155 cl::desc("Enable order file instrumentation (default = off)")); 156 157 cl::opt<bool> EnableMatrix( 158 "enable-matrix", cl::init(false), cl::Hidden, 159 cl::desc("Enable lowering of the matrix intrinsics")); 160 161 cl::opt<bool> EnableConstraintElimination( 162 "enable-constraint-elimination", cl::init(false), cl::Hidden, 163 cl::desc( 164 "Enable pass to eliminate conditions based on linear constraints.")); 165 166 cl::opt<bool> EnableFunctionSpecialization( 167 "enable-function-specialization", cl::init(false), cl::Hidden, 168 cl::desc("Enable Function Specialization pass")); 169 170 cl::opt<AttributorRunOption> AttributorRun( 171 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), 172 cl::desc("Enable the attributor inter-procedural deduction pass."), 173 cl::values(clEnumValN(AttributorRunOption::ALL, "all", 174 "enable all attributor runs"), 175 clEnumValN(AttributorRunOption::MODULE, "module", 176 "enable module-wide attributor runs"), 177 clEnumValN(AttributorRunOption::CGSCC, "cgscc", 178 "enable call graph SCC attributor runs"), 179 clEnumValN(AttributorRunOption::NONE, "none", 180 "disable attributor runs"))); 181 182 extern cl::opt<bool> EnableKnowledgeRetention; 183 } // namespace llvm 184 185 PassManagerBuilder::PassManagerBuilder() { 186 OptLevel = 2; 187 SizeLevel = 0; 188 LibraryInfo = nullptr; 189 Inliner = nullptr; 190 DisableUnrollLoops = false; 191 SLPVectorize = false; 192 LoopVectorize = true; 193 LoopsInterleaved = true; 194 RerollLoops = RunLoopRerolling; 195 NewGVN = RunNewGVN; 196 LicmMssaOptCap = SetLicmMssaOptCap; 197 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 198 DisableGVNLoadPRE = false; 199 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 200 VerifyInput = false; 201 VerifyOutput = false; 202 MergeFunctions = false; 203 PrepareForLTO = false; 204 EnablePGOInstrGen = false; 205 EnablePGOCSInstrGen = false; 206 EnablePGOCSInstrUse = false; 207 PGOInstrGen = ""; 208 PGOInstrUse = ""; 209 PGOSampleUse = ""; 210 PrepareForThinLTO = EnablePrepareForThinLTO; 211 PerformThinLTO = EnablePerformThinLTO; 212 DivergentTarget = false; 213 CallGraphProfile = true; 214 } 215 216 PassManagerBuilder::~PassManagerBuilder() { 217 delete LibraryInfo; 218 delete Inliner; 219 } 220 221 /// Set of global extensions, automatically added as part of the standard set. 222 static ManagedStatic< 223 SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy, 224 PassManagerBuilder::ExtensionFn, 225 PassManagerBuilder::GlobalExtensionID>, 226 8>> 227 GlobalExtensions; 228 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter; 229 230 /// Check if GlobalExtensions is constructed and not empty. 231 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger 232 /// the construction of the object. 233 static bool GlobalExtensionsNotEmpty() { 234 return GlobalExtensions.isConstructed() && !GlobalExtensions->empty(); 235 } 236 237 PassManagerBuilder::GlobalExtensionID 238 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty, 239 PassManagerBuilder::ExtensionFn Fn) { 240 auto ExtensionID = GlobalExtensionsCounter++; 241 GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID)); 242 return ExtensionID; 243 } 244 245 void PassManagerBuilder::removeGlobalExtension( 246 PassManagerBuilder::GlobalExtensionID ExtensionID) { 247 // RegisterStandardPasses may try to call this function after GlobalExtensions 248 // has already been destroyed; doing so should not generate an error. 249 if (!GlobalExtensions.isConstructed()) 250 return; 251 252 auto GlobalExtension = 253 llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) { 254 return std::get<2>(elem) == ExtensionID; 255 }); 256 assert(GlobalExtension != GlobalExtensions->end() && 257 "The extension ID to be removed should always be valid."); 258 259 GlobalExtensions->erase(GlobalExtension); 260 } 261 262 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 263 Extensions.push_back(std::make_pair(Ty, std::move(Fn))); 264 } 265 266 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 267 legacy::PassManagerBase &PM) const { 268 if (GlobalExtensionsNotEmpty()) { 269 for (auto &Ext : *GlobalExtensions) { 270 if (std::get<0>(Ext) == ETy) 271 std::get<1>(Ext)(*this, PM); 272 } 273 } 274 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 275 if (Extensions[i].first == ETy) 276 Extensions[i].second(*this, PM); 277 } 278 279 void PassManagerBuilder::addInitialAliasAnalysisPasses( 280 legacy::PassManagerBase &PM) const { 281 switch (UseCFLAA) { 282 case ::CFLAAType::Steensgaard: 283 PM.add(createCFLSteensAAWrapperPass()); 284 break; 285 case ::CFLAAType::Andersen: 286 PM.add(createCFLAndersAAWrapperPass()); 287 break; 288 case ::CFLAAType::Both: 289 PM.add(createCFLSteensAAWrapperPass()); 290 PM.add(createCFLAndersAAWrapperPass()); 291 break; 292 default: 293 break; 294 } 295 296 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 297 // BasicAliasAnalysis wins if they disagree. This is intended to help 298 // support "obvious" type-punning idioms. 299 PM.add(createTypeBasedAAWrapperPass()); 300 PM.add(createScopedNoAliasAAWrapperPass()); 301 } 302 303 void PassManagerBuilder::populateFunctionPassManager( 304 legacy::FunctionPassManager &FPM) { 305 addExtensionsToPM(EP_EarlyAsPossible, FPM); 306 307 // Add LibraryInfo if we have some. 308 if (LibraryInfo) 309 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 310 311 // The backends do not handle matrix intrinsics currently. 312 // Make sure they are also lowered in O0. 313 // FIXME: A lightweight version of the pass should run in the backend 314 // pipeline on demand. 315 if (EnableMatrix && OptLevel == 0) 316 FPM.add(createLowerMatrixIntrinsicsMinimalPass()); 317 318 if (OptLevel == 0) return; 319 320 addInitialAliasAnalysisPasses(FPM); 321 322 // Lower llvm.expect to metadata before attempting transforms. 323 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 324 FPM.add(createLowerExpectIntrinsicPass()); 325 FPM.add(createCFGSimplificationPass()); 326 FPM.add(createSROAPass()); 327 FPM.add(createEarlyCSEPass()); 328 } 329 330 // Do PGO instrumentation generation or use pass as the option specified. 331 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM, 332 bool IsCS = false) { 333 if (IsCS) { 334 if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse) 335 return; 336 } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty()) 337 return; 338 339 // Perform the preinline and cleanup passes for O1 and above. 340 // We will not do this inline for context sensitive PGO (when IsCS is true). 341 if (OptLevel > 0 && !DisablePreInliner && PGOSampleUse.empty() && !IsCS) { 342 // Create preinline pass. We construct an InlineParams object and specify 343 // the threshold here to avoid the command line options of the regular 344 // inliner to influence pre-inlining. The only fields of InlineParams we 345 // care about are DefaultThreshold and HintThreshold. 346 InlineParams IP; 347 IP.DefaultThreshold = PreInlineThreshold; 348 // FIXME: The hint threshold has the same value used by the regular inliner 349 // when not optimzing for size. This should probably be lowered after 350 // performance testing. 351 // Use PreInlineThreshold for both -Os and -Oz. Not running preinliner makes 352 // the instrumented binary unusably large. Even if PreInlineThreshold is not 353 // correct thresold for -Oz, it is better than not running preinliner. 354 IP.HintThreshold = SizeLevel > 0 ? PreInlineThreshold : 325; 355 356 MPM.add(createFunctionInliningPass(IP)); 357 MPM.add(createSROAPass()); 358 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 359 MPM.add(createCFGSimplificationPass( 360 SimplifyCFGOptions().convertSwitchRangeToICmp( 361 true))); // Merge & remove BBs 362 MPM.add(createInstructionCombiningPass()); // Combine silly seq's 363 addExtensionsToPM(EP_Peephole, MPM); 364 } 365 if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) { 366 MPM.add(createPGOInstrumentationGenLegacyPass(IsCS)); 367 // Add the profile lowering pass. 368 InstrProfOptions Options; 369 if (!PGOInstrGen.empty()) 370 Options.InstrProfileOutput = PGOInstrGen; 371 Options.DoCounterPromotion = true; 372 Options.UseBFIInPromotion = IsCS; 373 MPM.add(createLoopRotatePass()); 374 MPM.add(createInstrProfilingLegacyPass(Options, IsCS)); 375 } 376 if (!PGOInstrUse.empty()) 377 MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS)); 378 // Indirect call promotion that promotes intra-module targets only. 379 // For ThinLTO this is done earlier due to interactions with globalopt 380 // for imported functions. We don't run this at -O0. 381 if (OptLevel > 0 && !IsCS) 382 MPM.add( 383 createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty())); 384 } 385 void PassManagerBuilder::addFunctionSimplificationPasses( 386 legacy::PassManagerBase &MPM) { 387 // Start of function pass. 388 // Break up aggregate allocas, using SSAUpdater. 389 assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!"); 390 MPM.add(createSROAPass()); 391 MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies 392 if (EnableKnowledgeRetention) 393 MPM.add(createAssumeSimplifyPass()); 394 395 if (OptLevel > 1) { 396 if (EnableGVNHoist) 397 MPM.add(createGVNHoistPass()); 398 if (EnableGVNSink) { 399 MPM.add(createGVNSinkPass()); 400 MPM.add(createCFGSimplificationPass( 401 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 402 } 403 } 404 405 if (EnableConstraintElimination) 406 MPM.add(createConstraintEliminationPass()); 407 408 if (OptLevel > 1) { 409 // Speculative execution if the target has divergent branches; otherwise nop. 410 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 411 412 MPM.add(createJumpThreadingPass()); // Thread jumps. 413 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 414 } 415 MPM.add( 416 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 417 true))); // Merge & remove BBs 418 // Combine silly seq's 419 if (OptLevel > 2) 420 MPM.add(createAggressiveInstCombinerPass()); 421 MPM.add(createInstructionCombiningPass()); 422 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 423 MPM.add(createLibCallsShrinkWrapPass()); 424 addExtensionsToPM(EP_Peephole, MPM); 425 426 // Optimize memory intrinsic calls based on the profiled size information. 427 if (SizeLevel == 0) 428 MPM.add(createPGOMemOPSizeOptLegacyPass()); 429 430 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 431 if (OptLevel > 1) 432 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 433 MPM.add( 434 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 435 true))); // Merge & remove BBs 436 MPM.add(createReassociatePass()); // Reassociate expressions 437 438 // The matrix extension can introduce large vector operations early, which can 439 // benefit from running vector-combine early on. 440 if (EnableMatrix) 441 MPM.add(createVectorCombinePass()); 442 443 // Begin the loop pass pipeline. 444 if (EnableSimpleLoopUnswitch) { 445 // The simple loop unswitch pass relies on separate cleanup passes. Schedule 446 // them first so when we re-process a loop they run before other loop 447 // passes. 448 MPM.add(createLoopInstSimplifyPass()); 449 MPM.add(createLoopSimplifyCFGPass()); 450 } 451 // Try to remove as much code from the loop header as possible, 452 // to reduce amount of IR that will have to be duplicated. However, 453 // do not perform speculative hoisting the first time as LICM 454 // will destroy metadata that may not need to be destroyed if run 455 // after loop rotation. 456 // TODO: Investigate promotion cap for O1. 457 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 458 /*AllowSpeculation=*/false)); 459 // Rotate Loop - disable header duplication at -Oz 460 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 461 // TODO: Investigate promotion cap for O1. 462 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 463 /*AllowSpeculation=*/true)); 464 if (EnableSimpleLoopUnswitch) 465 MPM.add(createSimpleLoopUnswitchLegacyPass()); 466 else 467 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 468 // FIXME: We break the loop pass pipeline here in order to do full 469 // simplifycfg. Eventually loop-simplifycfg should be enhanced to replace the 470 // need for this. 471 MPM.add(createCFGSimplificationPass( 472 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 473 MPM.add(createInstructionCombiningPass()); 474 // We resume loop passes creating a second loop pipeline here. 475 if (EnableLoopFlatten) { 476 MPM.add(createLoopFlattenPass()); // Flatten loops 477 MPM.add(createLoopSimplifyCFGPass()); 478 } 479 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 480 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 481 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 482 MPM.add(createLoopDeletionPass()); // Delete dead loops 483 484 if (EnableLoopInterchange) 485 MPM.add(createLoopInterchangePass()); // Interchange loops 486 487 // Unroll small loops and perform peeling. 488 MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 489 ForgetAllSCEVInLoopUnroll)); 490 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 491 // This ends the loop pass pipelines. 492 493 // Break up allocas that may now be splittable after loop unrolling. 494 MPM.add(createSROAPass()); 495 496 if (OptLevel > 1) { 497 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 498 MPM.add(NewGVN ? createNewGVNPass() 499 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 500 } 501 MPM.add(createSCCPPass()); // Constant prop with SCCP 502 503 if (EnableConstraintElimination) 504 MPM.add(createConstraintEliminationPass()); 505 506 // Delete dead bit computations (instcombine runs after to fold away the dead 507 // computations, and then ADCE will run later to exploit any new DCE 508 // opportunities that creates). 509 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 510 511 // Run instcombine after redundancy elimination to exploit opportunities 512 // opened up by them. 513 MPM.add(createInstructionCombiningPass()); 514 addExtensionsToPM(EP_Peephole, MPM); 515 if (OptLevel > 1) { 516 if (EnableDFAJumpThreading && SizeLevel == 0) 517 MPM.add(createDFAJumpThreadingPass()); 518 519 MPM.add(createJumpThreadingPass()); // Thread jumps 520 MPM.add(createCorrelatedValuePropagationPass()); 521 } 522 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 523 524 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 525 // TODO: Investigate if this is too expensive at O1. 526 if (OptLevel > 1) { 527 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 528 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 529 /*AllowSpeculation=*/true)); 530 } 531 532 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 533 534 if (RerollLoops) 535 MPM.add(createLoopRerollPass()); 536 537 // Merge & remove BBs and sink & hoist common instructions. 538 MPM.add(createCFGSimplificationPass( 539 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 540 // Clean up after everything. 541 MPM.add(createInstructionCombiningPass()); 542 addExtensionsToPM(EP_Peephole, MPM); 543 544 if (EnableCHR && OptLevel >= 3 && 545 (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen)) 546 MPM.add(createControlHeightReductionLegacyPass()); 547 } 548 549 /// FIXME: Should LTO cause any differences to this set of passes? 550 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM, 551 bool IsFullLTO) { 552 PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize)); 553 554 if (IsFullLTO) { 555 // The vectorizer may have significantly shortened a loop body; unroll 556 // again. Unroll small loops to hide loop backedge latency and saturate any 557 // parallel execution resources of an out-of-order processor. We also then 558 // need to clean up redundancies and loop invariant code. 559 // FIXME: It would be really good to use a loop-integrated instruction 560 // combiner for cleanup here so that the unrolling and LICM can be pipelined 561 // across the loop nests. 562 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 563 if (EnableUnrollAndJam && !DisableUnrollLoops) 564 PM.add(createLoopUnrollAndJamPass(OptLevel)); 565 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 566 ForgetAllSCEVInLoopUnroll)); 567 PM.add(createWarnMissedTransformationsPass()); 568 } 569 570 if (!IsFullLTO) { 571 // Eliminate loads by forwarding stores from the previous iteration to loads 572 // of the current iteration. 573 PM.add(createLoopLoadEliminationPass()); 574 } 575 // Cleanup after the loop optimization passes. 576 PM.add(createInstructionCombiningPass()); 577 578 if (OptLevel > 1 && ExtraVectorizerPasses) { 579 // At higher optimization levels, try to clean up any runtime overlap and 580 // alignment checks inserted by the vectorizer. We want to track correlated 581 // runtime checks for two inner loops in the same outer loop, fold any 582 // common computations, hoist loop-invariant aspects out of any outer loop, 583 // and unswitch the runtime checks if possible. Once hoisted, we may have 584 // dead (or speculatable) control flows or more combining opportunities. 585 PM.add(createEarlyCSEPass()); 586 PM.add(createCorrelatedValuePropagationPass()); 587 PM.add(createInstructionCombiningPass()); 588 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 589 /*AllowSpeculation=*/true)); 590 PM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 591 PM.add(createCFGSimplificationPass( 592 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 593 PM.add(createInstructionCombiningPass()); 594 } 595 596 // Now that we've formed fast to execute loop structures, we do further 597 // optimizations. These are run afterward as they might block doing complex 598 // analyses and transforms such as what are needed for loop vectorization. 599 600 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 601 // GVN, loop transforms, and others have already run, so it's now better to 602 // convert to more optimized IR using more aggressive simplify CFG options. 603 // The extra sinking transform can create larger basic blocks, so do this 604 // before SLP vectorization. 605 PM.add(createCFGSimplificationPass(SimplifyCFGOptions() 606 .forwardSwitchCondToPhi(true) 607 .convertSwitchRangeToICmp(true) 608 .convertSwitchToLookupTable(true) 609 .needCanonicalLoops(false) 610 .hoistCommonInsts(true) 611 .sinkCommonInsts(true))); 612 613 if (IsFullLTO) { 614 PM.add(createSCCPPass()); // Propagate exposed constants 615 PM.add(createInstructionCombiningPass()); // Clean up again 616 PM.add(createBitTrackingDCEPass()); 617 } 618 619 // Optimize parallel scalar instruction chains into SIMD instructions. 620 if (SLPVectorize) { 621 PM.add(createSLPVectorizerPass()); 622 if (OptLevel > 1 && ExtraVectorizerPasses) 623 PM.add(createEarlyCSEPass()); 624 } 625 626 // Enhance/cleanup vector code. 627 PM.add(createVectorCombinePass()); 628 629 if (!IsFullLTO) { 630 addExtensionsToPM(EP_Peephole, PM); 631 PM.add(createInstructionCombiningPass()); 632 633 if (EnableUnrollAndJam && !DisableUnrollLoops) { 634 // Unroll and Jam. We do this before unroll but need to be in a separate 635 // loop pass manager in order for the outer loop to be processed by 636 // unroll and jam before the inner loop is unrolled. 637 PM.add(createLoopUnrollAndJamPass(OptLevel)); 638 } 639 640 // Unroll small loops 641 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 642 ForgetAllSCEVInLoopUnroll)); 643 644 if (!DisableUnrollLoops) { 645 // LoopUnroll may generate some redundency to cleanup. 646 PM.add(createInstructionCombiningPass()); 647 648 // Runtime unrolling will introduce runtime check in loop prologue. If the 649 // unrolled loop is a inner loop, then the prologue will be inside the 650 // outer loop. LICM pass can help to promote the runtime check out if the 651 // checked value is loop invariant. 652 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 653 /*AllowSpeculation=*/true)); 654 } 655 656 PM.add(createWarnMissedTransformationsPass()); 657 } 658 659 // After vectorization and unrolling, assume intrinsics may tell us more 660 // about pointer alignments. 661 PM.add(createAlignmentFromAssumptionsPass()); 662 663 if (IsFullLTO) 664 PM.add(createInstructionCombiningPass()); 665 } 666 667 void PassManagerBuilder::populateModulePassManager( 668 legacy::PassManagerBase &MPM) { 669 // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link 670 // is handled separately, so just check this is not the ThinLTO post-link. 671 bool DefaultOrPreLinkPipeline = !PerformThinLTO; 672 673 MPM.add(createAnnotation2MetadataLegacyPass()); 674 675 if (!PGOSampleUse.empty()) { 676 MPM.add(createPruneEHPass()); 677 // In ThinLTO mode, when flattened profile is used, all the available 678 // profile information will be annotated in PreLink phase so there is 679 // no need to load the profile again in PostLink. 680 if (!(FlattenedProfileUsed && PerformThinLTO)) 681 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 682 } 683 684 // Allow forcing function attributes as a debugging and tuning aid. 685 MPM.add(createForceFunctionAttrsLegacyPass()); 686 687 // If all optimizations are disabled, just run the always-inline pass and, 688 // if enabled, the function merging pass. 689 if (OptLevel == 0) { 690 addPGOInstrPasses(MPM); 691 if (Inliner) { 692 MPM.add(Inliner); 693 Inliner = nullptr; 694 } 695 696 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 697 // creates a CGSCC pass manager, but we don't want to add extensions into 698 // that pass manager. To prevent this we insert a no-op module pass to reset 699 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 700 // builds. The function merging pass is 701 if (MergeFunctions) 702 MPM.add(createMergeFunctionsPass()); 703 else if (GlobalExtensionsNotEmpty() || !Extensions.empty()) 704 MPM.add(createBarrierNoopPass()); 705 706 if (PerformThinLTO) { 707 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 708 // Drop available_externally and unreferenced globals. This is necessary 709 // with ThinLTO in order to avoid leaving undefined references to dead 710 // globals in the object file. 711 MPM.add(createEliminateAvailableExternallyPass()); 712 MPM.add(createGlobalDCEPass()); 713 } 714 715 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 716 717 if (PrepareForLTO || PrepareForThinLTO) { 718 MPM.add(createCanonicalizeAliasesPass()); 719 // Rename anon globals to be able to export them in the summary. 720 // This has to be done after we add the extensions to the pass manager 721 // as there could be passes (e.g. Adddress sanitizer) which introduce 722 // new unnamed globals. 723 MPM.add(createNameAnonGlobalPass()); 724 } 725 726 MPM.add(createAnnotationRemarksLegacyPass()); 727 return; 728 } 729 730 // Add LibraryInfo if we have some. 731 if (LibraryInfo) 732 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 733 734 addInitialAliasAnalysisPasses(MPM); 735 736 // For ThinLTO there are two passes of indirect call promotion. The 737 // first is during the compile phase when PerformThinLTO=false and 738 // intra-module indirect call targets are promoted. The second is during 739 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 740 // inter-module indirect calls. For that we perform indirect call promotion 741 // earlier in the pass pipeline, here before globalopt. Otherwise imported 742 // available_externally functions look unreferenced and are removed. 743 if (PerformThinLTO) { 744 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true, 745 !PGOSampleUse.empty())); 746 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 747 } 748 749 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 750 // as it will change the CFG too much to make the 2nd profile annotation 751 // in backend more difficult. 752 bool PrepareForThinLTOUsingPGOSampleProfile = 753 PrepareForThinLTO && !PGOSampleUse.empty(); 754 if (PrepareForThinLTOUsingPGOSampleProfile) 755 DisableUnrollLoops = true; 756 757 // Infer attributes about declarations if possible. 758 MPM.add(createInferFunctionAttrsLegacyPass()); 759 760 // Infer attributes on declarations, call sites, arguments, etc. 761 if (AttributorRun & AttributorRunOption::MODULE) 762 MPM.add(createAttributorLegacyPass()); 763 764 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 765 766 if (OptLevel > 2) 767 MPM.add(createCallSiteSplittingPass()); 768 769 // Propage constant function arguments by specializing the functions. 770 if (OptLevel > 2 && EnableFunctionSpecialization) 771 MPM.add(createFunctionSpecializationPass()); 772 773 MPM.add(createIPSCCPPass()); // IP SCCP 774 MPM.add(createCalledValuePropagationPass()); 775 776 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 777 // Promote any localized global vars. 778 MPM.add(createPromoteMemoryToRegisterPass()); 779 780 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 781 782 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE 783 addExtensionsToPM(EP_Peephole, MPM); 784 MPM.add( 785 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 786 true))); // Clean up after IPCP & DAE 787 788 // For SamplePGO in ThinLTO compile phase, we do not want to do indirect 789 // call promotion as it will change the CFG too much to make the 2nd 790 // profile annotation in backend more difficult. 791 // PGO instrumentation is added during the compile phase for ThinLTO, do 792 // not run it a second time 793 if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile) 794 addPGOInstrPasses(MPM); 795 796 // Create profile COMDAT variables. Lld linker wants to see all variables 797 // before the LTO/ThinLTO link since it needs to resolve symbols/comdats. 798 if (!PerformThinLTO && EnablePGOCSInstrGen) 799 MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen)); 800 801 // We add a module alias analysis pass here. In part due to bugs in the 802 // analysis infrastructure this "works" in that the analysis stays alive 803 // for the entire SCC pass run below. 804 MPM.add(createGlobalsAAWrapperPass()); 805 806 // Start of CallGraph SCC passes. 807 MPM.add(createPruneEHPass()); // Remove dead EH info 808 bool RunInliner = false; 809 if (Inliner) { 810 MPM.add(Inliner); 811 Inliner = nullptr; 812 RunInliner = true; 813 } 814 815 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 816 if (AttributorRun & AttributorRunOption::CGSCC) 817 MPM.add(createAttributorCGSCCLegacyPass()); 818 819 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 820 // there are no OpenMP runtime calls present in the module. 821 if (OptLevel > 1) 822 MPM.add(createOpenMPOptCGSCCLegacyPass()); 823 824 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 825 if (OptLevel > 2) 826 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 827 828 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 829 addFunctionSimplificationPasses(MPM); 830 831 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 832 // pass manager that we are specifically trying to avoid. To prevent this 833 // we must insert a no-op module pass to reset the pass manager. 834 MPM.add(createBarrierNoopPass()); 835 836 if (RunPartialInlining) 837 MPM.add(createPartialInliningPass()); 838 839 if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO) 840 // Remove avail extern fns and globals definitions if we aren't 841 // compiling an object file for later LTO. For LTO we want to preserve 842 // these so they are eligible for inlining at link-time. Note if they 843 // are unreferenced they will be removed by GlobalDCE later, so 844 // this only impacts referenced available externally globals. 845 // Eventually they will be suppressed during codegen, but eliminating 846 // here enables more opportunity for GlobalDCE as it may make 847 // globals referenced by available external functions dead 848 // and saves running remaining passes on the eliminated functions. 849 MPM.add(createEliminateAvailableExternallyPass()); 850 851 // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass 852 // for LTO and ThinLTO -- The actual pass will be called after all inlines 853 // are performed. 854 // Need to do this after COMDAT variables have been eliminated, 855 // (i.e. after EliminateAvailableExternallyPass). 856 if (!(PrepareForLTO || PrepareForThinLTO)) 857 addPGOInstrPasses(MPM, /* IsCS */ true); 858 859 if (EnableOrderFileInstrumentation) 860 MPM.add(createInstrOrderFilePass()); 861 862 MPM.add(createReversePostOrderFunctionAttrsPass()); 863 864 // The inliner performs some kind of dead code elimination as it goes, 865 // but there are cases that are not really caught by it. We might 866 // at some point consider teaching the inliner about them, but it 867 // is OK for now to run GlobalOpt + GlobalDCE in tandem as their 868 // benefits generally outweight the cost, making the whole pipeline 869 // faster. 870 if (RunInliner) { 871 MPM.add(createGlobalOptimizerPass()); 872 MPM.add(createGlobalDCEPass()); 873 } 874 875 // If we are planning to perform ThinLTO later, let's not bloat the code with 876 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 877 // during ThinLTO and perform the rest of the optimizations afterward. 878 if (PrepareForThinLTO) { 879 // Ensure we perform any last passes, but do so before renaming anonymous 880 // globals in case the passes add any. 881 addExtensionsToPM(EP_OptimizerLast, MPM); 882 MPM.add(createCanonicalizeAliasesPass()); 883 // Rename anon globals to be able to export them in the summary. 884 MPM.add(createNameAnonGlobalPass()); 885 return; 886 } 887 888 if (PerformThinLTO) 889 // Optimize globals now when performing ThinLTO, this enables more 890 // optimizations later. 891 MPM.add(createGlobalOptimizerPass()); 892 893 // Scheduling LoopVersioningLICM when inlining is over, because after that 894 // we may see more accurate aliasing. Reason to run this late is that too 895 // early versioning may prevent further inlining due to increase of code 896 // size. By placing it just after inlining other optimizations which runs 897 // later might get benefit of no-alias assumption in clone loop. 898 if (UseLoopVersioningLICM) { 899 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 900 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 901 /*AllowSpeculation=*/true)); 902 } 903 904 // We add a fresh GlobalsModRef run at this point. This is particularly 905 // useful as the above will have inlined, DCE'ed, and function-attr 906 // propagated everything. We should at this point have a reasonably minimal 907 // and richly annotated call graph. By computing aliasing and mod/ref 908 // information for all local globals here, the late loop passes and notably 909 // the vectorizer will be able to use them to help recognize vectorizable 910 // memory operations. 911 // 912 // Note that this relies on a bug in the pass manager which preserves 913 // a module analysis into a function pass pipeline (and throughout it) so 914 // long as the first function pass doesn't invalidate the module analysis. 915 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 916 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 917 // (doing nothing preserves it as it is required to be conservatively 918 // correct in the face of IR changes). 919 MPM.add(createGlobalsAAWrapperPass()); 920 921 MPM.add(createFloat2IntPass()); 922 MPM.add(createLowerConstantIntrinsicsPass()); 923 924 if (EnableMatrix) { 925 MPM.add(createLowerMatrixIntrinsicsPass()); 926 // CSE the pointer arithmetic of the column vectors. This allows alias 927 // analysis to establish no-aliasing between loads and stores of different 928 // columns of the same matrix. 929 MPM.add(createEarlyCSEPass(false)); 930 } 931 932 addExtensionsToPM(EP_VectorizerStart, MPM); 933 934 // Re-rotate loops in all our loop nests. These may have fallout out of 935 // rotated form due to GVN or other transformations, and the vectorizer relies 936 // on the rotated form. Disable header duplication at -Oz. 937 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 938 939 // Distribute loops to allow partial vectorization. I.e. isolate dependences 940 // into separate loop that would otherwise inhibit vectorization. This is 941 // currently only performed for loops marked with the metadata 942 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 943 MPM.add(createLoopDistributePass()); 944 945 addVectorPasses(MPM, /* IsFullLTO */ false); 946 947 // FIXME: We shouldn't bother with this anymore. 948 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 949 950 // GlobalOpt already deletes dead functions and globals, at -O2 try a 951 // late pass of GlobalDCE. It is capable of deleting dead cycles. 952 if (OptLevel > 1) { 953 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 954 MPM.add(createConstantMergePass()); // Merge dup global constants 955 } 956 957 // See comment in the new PM for justification of scheduling splitting at 958 // this stage (\ref buildModuleSimplificationPipeline). 959 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 960 MPM.add(createHotColdSplittingPass()); 961 962 if (EnableIROutliner) 963 MPM.add(createIROutlinerPass()); 964 965 if (MergeFunctions) 966 MPM.add(createMergeFunctionsPass()); 967 968 // Add Module flag "CG Profile" based on Branch Frequency Information. 969 if (CallGraphProfile) 970 MPM.add(createCGProfileLegacyPass()); 971 972 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 973 // canonicalization pass that enables other optimizations. As a result, 974 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 975 // result too early. 976 MPM.add(createLoopSinkPass()); 977 // Get rid of LCSSA nodes. 978 MPM.add(createInstSimplifyLegacyPass()); 979 980 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 981 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 982 // flattening of blocks. 983 MPM.add(createDivRemPairsPass()); 984 985 // LoopSink (and other loop passes since the last simplifyCFG) might have 986 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 987 MPM.add(createCFGSimplificationPass( 988 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 989 990 addExtensionsToPM(EP_OptimizerLast, MPM); 991 992 if (PrepareForLTO) { 993 MPM.add(createCanonicalizeAliasesPass()); 994 // Rename anon globals to be able to handle them in the summary 995 MPM.add(createNameAnonGlobalPass()); 996 } 997 998 MPM.add(createAnnotationRemarksLegacyPass()); 999 } 1000 1001 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 1002 // Load sample profile before running the LTO optimization pipeline. 1003 if (!PGOSampleUse.empty()) { 1004 PM.add(createPruneEHPass()); 1005 PM.add(createSampleProfileLoaderPass(PGOSampleUse)); 1006 } 1007 1008 // Remove unused virtual tables to improve the quality of code generated by 1009 // whole-program devirtualization and bitset lowering. 1010 PM.add(createGlobalDCEPass()); 1011 1012 // Provide AliasAnalysis services for optimizations. 1013 addInitialAliasAnalysisPasses(PM); 1014 1015 // Allow forcing function attributes as a debugging and tuning aid. 1016 PM.add(createForceFunctionAttrsLegacyPass()); 1017 1018 // Infer attributes about declarations if possible. 1019 PM.add(createInferFunctionAttrsLegacyPass()); 1020 1021 if (OptLevel > 1) { 1022 // Split call-site with more constrained arguments. 1023 PM.add(createCallSiteSplittingPass()); 1024 1025 // Indirect call promotion. This should promote all the targets that are 1026 // left by the earlier promotion pass that promotes intra-module targets. 1027 // This two-step promotion is to save the compile time. For LTO, it should 1028 // produce the same result as if we only do promotion here. 1029 PM.add( 1030 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty())); 1031 1032 // Propage constant function arguments by specializing the functions. 1033 if (EnableFunctionSpecialization && OptLevel > 2) 1034 PM.add(createFunctionSpecializationPass()); 1035 1036 // Propagate constants at call sites into the functions they call. This 1037 // opens opportunities for globalopt (and inlining) by substituting function 1038 // pointers passed as arguments to direct uses of functions. 1039 PM.add(createIPSCCPPass()); 1040 1041 // Attach metadata to indirect call sites indicating the set of functions 1042 // they may target at run-time. This should follow IPSCCP. 1043 PM.add(createCalledValuePropagationPass()); 1044 1045 // Infer attributes on declarations, call sites, arguments, etc. 1046 if (AttributorRun & AttributorRunOption::MODULE) 1047 PM.add(createAttributorLegacyPass()); 1048 } 1049 1050 // Infer attributes about definitions. The readnone attribute in particular is 1051 // required for virtual constant propagation. 1052 PM.add(createPostOrderFunctionAttrsLegacyPass()); 1053 PM.add(createReversePostOrderFunctionAttrsPass()); 1054 1055 // Split globals using inrange annotations on GEP indices. This can help 1056 // improve the quality of generated code when virtual constant propagation or 1057 // control flow integrity are enabled. 1058 PM.add(createGlobalSplitPass()); 1059 1060 // Apply whole-program devirtualization and virtual constant propagation. 1061 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1062 1063 // That's all we need at opt level 1. 1064 if (OptLevel == 1) 1065 return; 1066 1067 // Now that we internalized some globals, see if we can hack on them! 1068 PM.add(createGlobalOptimizerPass()); 1069 // Promote any localized global vars. 1070 PM.add(createPromoteMemoryToRegisterPass()); 1071 1072 // Linking modules together can lead to duplicated global constants, only 1073 // keep one copy of each constant. 1074 PM.add(createConstantMergePass()); 1075 1076 // Remove unused arguments from functions. 1077 PM.add(createDeadArgEliminationPass()); 1078 1079 // Reduce the code after globalopt and ipsccp. Both can open up significant 1080 // simplification opportunities, and both can propagate functions through 1081 // function pointers. When this happens, we often have to resolve varargs 1082 // calls, etc, so let instcombine do this. 1083 if (OptLevel > 2) 1084 PM.add(createAggressiveInstCombinerPass()); 1085 PM.add(createInstructionCombiningPass()); 1086 addExtensionsToPM(EP_Peephole, PM); 1087 1088 // Inline small functions 1089 bool RunInliner = Inliner; 1090 if (RunInliner) { 1091 PM.add(Inliner); 1092 Inliner = nullptr; 1093 } 1094 1095 PM.add(createPruneEHPass()); // Remove dead EH info. 1096 1097 // CSFDO instrumentation and use pass. 1098 addPGOInstrPasses(PM, /* IsCS */ true); 1099 1100 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 1101 if (AttributorRun & AttributorRunOption::CGSCC) 1102 PM.add(createAttributorCGSCCLegacyPass()); 1103 1104 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 1105 // there are no OpenMP runtime calls present in the module. 1106 if (OptLevel > 1) 1107 PM.add(createOpenMPOptCGSCCLegacyPass()); 1108 1109 // Optimize globals again if we ran the inliner. 1110 if (RunInliner) 1111 PM.add(createGlobalOptimizerPass()); 1112 PM.add(createGlobalDCEPass()); // Remove dead functions. 1113 1114 // If we didn't decide to inline a function, check to see if we can 1115 // transform it to pass arguments by value instead of by reference. 1116 PM.add(createArgumentPromotionPass()); 1117 1118 // The IPO passes may leave cruft around. Clean up after them. 1119 PM.add(createInstructionCombiningPass()); 1120 addExtensionsToPM(EP_Peephole, PM); 1121 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1122 1123 // Break up allocas 1124 PM.add(createSROAPass()); 1125 1126 // LTO provides additional opportunities for tailcall elimination due to 1127 // link-time inlining, and visibility of nocapture attribute. 1128 if (OptLevel > 1) 1129 PM.add(createTailCallEliminationPass()); 1130 1131 // Infer attributes on declarations, call sites, arguments, etc. 1132 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 1133 // Run a few AA driven optimizations here and now, to cleanup the code. 1134 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 1135 1136 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 1137 /*AllowSpeculation=*/true)); 1138 PM.add(NewGVN ? createNewGVNPass() 1139 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 1140 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 1141 1142 // Nuke dead stores. 1143 PM.add(createDeadStoreEliminationPass()); 1144 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 1145 1146 // More loops are countable; try to optimize them. 1147 if (EnableLoopFlatten) 1148 PM.add(createLoopFlattenPass()); 1149 PM.add(createIndVarSimplifyPass()); 1150 PM.add(createLoopDeletionPass()); 1151 if (EnableLoopInterchange) 1152 PM.add(createLoopInterchangePass()); 1153 1154 if (EnableConstraintElimination) 1155 PM.add(createConstraintEliminationPass()); 1156 1157 // Unroll small loops and perform peeling. 1158 PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 1159 ForgetAllSCEVInLoopUnroll)); 1160 PM.add(createLoopDistributePass()); 1161 1162 addVectorPasses(PM, /* IsFullLTO */ true); 1163 1164 addExtensionsToPM(EP_Peephole, PM); 1165 1166 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1167 } 1168 1169 void PassManagerBuilder::addLateLTOOptimizationPasses( 1170 legacy::PassManagerBase &PM) { 1171 // See comment in the new PM for justification of scheduling splitting at 1172 // this stage (\ref buildLTODefaultPipeline). 1173 if (EnableHotColdSplit) 1174 PM.add(createHotColdSplittingPass()); 1175 1176 // Delete basic blocks, which optimization passes may have killed. 1177 PM.add( 1178 createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true))); 1179 1180 // Drop bodies of available externally objects to improve GlobalDCE. 1181 PM.add(createEliminateAvailableExternallyPass()); 1182 1183 // Now that we have optimized the program, discard unreachable functions. 1184 PM.add(createGlobalDCEPass()); 1185 1186 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 1187 // currently it damages debug info. 1188 if (MergeFunctions) 1189 PM.add(createMergeFunctionsPass()); 1190 } 1191 1192 void PassManagerBuilder::populateThinLTOPassManager( 1193 legacy::PassManagerBase &PM) { 1194 PerformThinLTO = true; 1195 if (LibraryInfo) 1196 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1197 1198 if (VerifyInput) 1199 PM.add(createVerifierPass()); 1200 1201 if (ImportSummary) { 1202 // This pass imports type identifier resolutions for whole-program 1203 // devirtualization and CFI. It must run early because other passes may 1204 // disturb the specific instruction patterns that these passes look for, 1205 // creating dependencies on resolutions that may not appear in the summary. 1206 // 1207 // For example, GVN may transform the pattern assume(type.test) appearing in 1208 // two basic blocks into assume(phi(type.test, type.test)), which would 1209 // transform a dependency on a WPD resolution into a dependency on a type 1210 // identifier resolution for CFI. 1211 // 1212 // Also, WPD has access to more precise information than ICP and can 1213 // devirtualize more effectively, so it should operate on the IR first. 1214 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary)); 1215 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary)); 1216 } 1217 1218 populateModulePassManager(PM); 1219 1220 if (VerifyOutput) 1221 PM.add(createVerifierPass()); 1222 PerformThinLTO = false; 1223 } 1224 1225 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 1226 if (LibraryInfo) 1227 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1228 1229 if (VerifyInput) 1230 PM.add(createVerifierPass()); 1231 1232 addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM); 1233 1234 if (OptLevel != 0) 1235 addLTOOptimizationPasses(PM); 1236 else { 1237 // The whole-program-devirt pass needs to run at -O0 because only it knows 1238 // about the llvm.type.checked.load intrinsic: it needs to both lower the 1239 // intrinsic itself and handle it in the summary. 1240 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1241 } 1242 1243 // Create a function that performs CFI checks for cross-DSO calls with targets 1244 // in the current module. 1245 PM.add(createCrossDSOCFIPass()); 1246 1247 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 1248 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 1249 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 1250 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr)); 1251 // Run a second time to clean up any type tests left behind by WPD for use 1252 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1253 PM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 1254 1255 if (OptLevel != 0) 1256 addLateLTOOptimizationPasses(PM); 1257 1258 addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM); 1259 1260 PM.add(createAnnotationRemarksLegacyPass()); 1261 1262 if (VerifyOutput) 1263 PM.add(createVerifierPass()); 1264 } 1265 1266 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 1267 PassManagerBuilder *PMB = new PassManagerBuilder(); 1268 return wrap(PMB); 1269 } 1270 1271 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 1272 PassManagerBuilder *Builder = unwrap(PMB); 1273 delete Builder; 1274 } 1275 1276 void 1277 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 1278 unsigned OptLevel) { 1279 PassManagerBuilder *Builder = unwrap(PMB); 1280 Builder->OptLevel = OptLevel; 1281 } 1282 1283 void 1284 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 1285 unsigned SizeLevel) { 1286 PassManagerBuilder *Builder = unwrap(PMB); 1287 Builder->SizeLevel = SizeLevel; 1288 } 1289 1290 void 1291 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 1292 LLVMBool Value) { 1293 // NOTE: The DisableUnitAtATime switch has been removed. 1294 } 1295 1296 void 1297 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 1298 LLVMBool Value) { 1299 PassManagerBuilder *Builder = unwrap(PMB); 1300 Builder->DisableUnrollLoops = Value; 1301 } 1302 1303 void 1304 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 1305 LLVMBool Value) { 1306 // NOTE: The simplify-libcalls pass has been removed. 1307 } 1308 1309 void 1310 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 1311 unsigned Threshold) { 1312 PassManagerBuilder *Builder = unwrap(PMB); 1313 Builder->Inliner = createFunctionInliningPass(Threshold); 1314 } 1315 1316 void 1317 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 1318 LLVMPassManagerRef PM) { 1319 PassManagerBuilder *Builder = unwrap(PMB); 1320 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 1321 Builder->populateFunctionPassManager(*FPM); 1322 } 1323 1324 void 1325 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 1326 LLVMPassManagerRef PM) { 1327 PassManagerBuilder *Builder = unwrap(PMB); 1328 legacy::PassManagerBase *MPM = unwrap(PM); 1329 Builder->populateModulePassManager(*MPM); 1330 } 1331 1332 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 1333 LLVMPassManagerRef PM, 1334 LLVMBool Internalize, 1335 LLVMBool RunInliner) { 1336 PassManagerBuilder *Builder = unwrap(PMB); 1337 legacy::PassManagerBase *LPM = unwrap(PM); 1338 1339 // A small backwards compatibility hack. populateLTOPassManager used to take 1340 // an RunInliner option. 1341 if (RunInliner && !Builder->Inliner) 1342 Builder->Inliner = createFunctionInliningPass(); 1343 1344 Builder->populateLTOPassManager(*LPM); 1345 } 1346