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