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