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