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