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