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