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