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