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