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