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