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