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