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