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> 71 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true), 72 cl::desc("Run the float2int (float demotion) pass")); 73 74 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false), 75 cl::Hidden, 76 cl::desc("Run the load combining pass")); 77 78 static cl::opt<bool> 79 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization", 80 cl::init(true), cl::Hidden, 81 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop " 82 "vectorizer instead of before")); 83 84 // Experimental option to use CFL-AA 85 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 86 static cl::opt<CFLAAType> 87 UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden, 88 cl::desc("Enable the new, experimental CFL alias analysis"), 89 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 90 clEnumValN(CFLAAType::Steensgaard, "steens", 91 "Enable unification-based CFL-AA"), 92 clEnumValN(CFLAAType::Andersen, "anders", 93 "Enable inclusion-based CFL-AA"), 94 clEnumValN(CFLAAType::Both, "both", 95 "Enable both variants of CFL-AA"))); 96 97 static cl::opt<bool> 98 EnableMLSM("mlsm", cl::init(true), cl::Hidden, 99 cl::desc("Enable motion of merged load and store")); 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(true), cl::Hidden, 146 cl::desc("Enable the GVN hoisting pass (default = on)")); 147 148 PassManagerBuilder::PassManagerBuilder() { 149 OptLevel = 2; 150 SizeLevel = 0; 151 LibraryInfo = nullptr; 152 Inliner = nullptr; 153 ModuleSummary = nullptr; 154 DisableUnitAtATime = false; 155 DisableUnrollLoops = false; 156 BBVectorize = RunBBVectorization; 157 SLPVectorize = RunSLPVectorization; 158 LoopVectorize = RunLoopVectorization; 159 RerollLoops = RunLoopRerolling; 160 LoadCombine = RunLoadCombine; 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 addExtensionsToPM(EP_Peephole, MPM); 301 302 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 303 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 304 MPM.add(createReassociatePass()); // Reassociate expressions 305 // Rotate Loop - disable header duplication at -Oz 306 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1)); 307 MPM.add(createLICMPass()); // Hoist loop invariants 308 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); 309 MPM.add(createCFGSimplificationPass()); 310 addInstructionCombiningPass(MPM); 311 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 312 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 313 MPM.add(createLoopDeletionPass()); // Delete dead loops 314 if (EnableLoopInterchange) { 315 MPM.add(createLoopInterchangePass()); // Interchange loops 316 MPM.add(createCFGSimplificationPass()); 317 } 318 if (!DisableUnrollLoops) 319 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops 320 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 321 322 if (OptLevel > 1) { 323 if (EnableMLSM) 324 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 325 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 326 } 327 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 328 MPM.add(createSCCPPass()); // Constant prop with SCCP 329 330 // Delete dead bit computations (instcombine runs after to fold away the dead 331 // computations, and then ADCE will run later to exploit any new DCE 332 // opportunities that creates). 333 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 334 335 // Run instcombine after redundancy elimination to exploit opportunities 336 // opened up by them. 337 addInstructionCombiningPass(MPM); 338 addExtensionsToPM(EP_Peephole, MPM); 339 MPM.add(createJumpThreadingPass()); // Thread jumps 340 MPM.add(createCorrelatedValuePropagationPass()); 341 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 342 MPM.add(createLICMPass()); 343 344 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 345 346 if (RerollLoops) 347 MPM.add(createLoopRerollPass()); 348 if (!RunSLPAfterLoopVectorization) { 349 if (SLPVectorize) 350 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 351 352 if (BBVectorize) { 353 MPM.add(createBBVectorizePass()); 354 addInstructionCombiningPass(MPM); 355 addExtensionsToPM(EP_Peephole, MPM); 356 if (OptLevel > 1 && UseGVNAfterVectorization) 357 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 358 else 359 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 360 361 // BBVectorize may have significantly shortened a loop body; unroll again. 362 if (!DisableUnrollLoops) 363 MPM.add(createLoopUnrollPass()); 364 } 365 } 366 367 if (LoadCombine) 368 MPM.add(createLoadCombinePass()); 369 370 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 371 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 372 // Clean up after everything. 373 addInstructionCombiningPass(MPM); 374 addExtensionsToPM(EP_Peephole, MPM); 375 } 376 377 void PassManagerBuilder::populateModulePassManager( 378 legacy::PassManagerBase &MPM) { 379 // Allow forcing function attributes as a debugging and tuning aid. 380 MPM.add(createForceFunctionAttrsLegacyPass()); 381 382 // If all optimizations are disabled, just run the always-inline pass and, 383 // if enabled, the function merging pass. 384 if (OptLevel == 0) { 385 addPGOInstrPasses(MPM); 386 if (Inliner) { 387 MPM.add(Inliner); 388 Inliner = nullptr; 389 } 390 391 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 392 // creates a CGSCC pass manager, but we don't want to add extensions into 393 // that pass manager. To prevent this we insert a no-op module pass to reset 394 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 395 // builds. The function merging pass is 396 if (MergeFunctions) 397 MPM.add(createMergeFunctionsPass()); 398 else if (!GlobalExtensions->empty() || !Extensions.empty()) 399 MPM.add(createBarrierNoopPass()); 400 401 if (PrepareForThinLTO) 402 // Rename anon globals to be able to export them in the summary. 403 MPM.add(createNameAnonGlobalPass()); 404 405 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 406 return; 407 } 408 409 // Add LibraryInfo if we have some. 410 if (LibraryInfo) 411 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 412 413 addInitialAliasAnalysisPasses(MPM); 414 415 // For ThinLTO there are two passes of indirect call promotion. The 416 // first is during the compile phase when PerformThinLTO=false and 417 // intra-module indirect call targets are promoted. The second is during 418 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 419 // inter-module indirect calls. For that we perform indirect call promotion 420 // earlier in the pass pipeline, here before globalopt. Otherwise imported 421 // available_externally functions look unreferenced and are removed. 422 if (PerformThinLTO) 423 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true)); 424 425 if (!DisableUnitAtATime) { 426 // Infer attributes about declarations if possible. 427 MPM.add(createInferFunctionAttrsLegacyPass()); 428 429 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 430 431 MPM.add(createIPSCCPPass()); // IP SCCP 432 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 433 // Promote any localized global vars. 434 MPM.add(createPromoteMemoryToRegisterPass()); 435 436 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 437 438 addInstructionCombiningPass(MPM); // Clean up after IPCP & DAE 439 addExtensionsToPM(EP_Peephole, MPM); 440 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE 441 } 442 443 if (!PerformThinLTO) { 444 /// PGO instrumentation is added during the compile phase for ThinLTO, do 445 /// not run it a second time 446 addPGOInstrPasses(MPM); 447 // Indirect call promotion that promotes intra-module targets only. 448 // For ThinLTO this is done earlier due to interactions with globalopt 449 // for imported functions. 450 MPM.add(createPGOIndirectCallPromotionLegacyPass()); 451 } 452 453 if (EnableNonLTOGlobalsModRef) 454 // We add a module alias analysis pass here. In part due to bugs in the 455 // analysis infrastructure this "works" in that the analysis stays alive 456 // for the entire SCC pass run below. 457 MPM.add(createGlobalsAAWrapperPass()); 458 459 // Start of CallGraph SCC passes. 460 if (!DisableUnitAtATime) 461 MPM.add(createPruneEHPass()); // Remove dead EH info 462 if (Inliner) { 463 MPM.add(Inliner); 464 Inliner = nullptr; 465 } 466 if (!DisableUnitAtATime) 467 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 468 if (OptLevel > 2) 469 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 470 471 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 472 addFunctionSimplificationPasses(MPM); 473 474 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 475 // pass manager that we are specifically trying to avoid. To prevent this 476 // we must insert a no-op module pass to reset the pass manager. 477 MPM.add(createBarrierNoopPass()); 478 479 if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO && 480 !PrepareForThinLTO) 481 // Remove avail extern fns and globals definitions if we aren't 482 // compiling an object file for later LTO. For LTO we want to preserve 483 // these so they are eligible for inlining at link-time. Note if they 484 // are unreferenced they will be removed by GlobalDCE later, so 485 // this only impacts referenced available externally globals. 486 // Eventually they will be suppressed during codegen, but eliminating 487 // here enables more opportunity for GlobalDCE as it may make 488 // globals referenced by available external functions dead 489 // and saves running remaining passes on the eliminated functions. 490 MPM.add(createEliminateAvailableExternallyPass()); 491 492 if (!DisableUnitAtATime) 493 MPM.add(createReversePostOrderFunctionAttrsPass()); 494 495 // If we are planning to perform ThinLTO later, let's not bloat the code with 496 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 497 // during ThinLTO and perform the rest of the optimizations afterward. 498 if (PrepareForThinLTO) { 499 // Reduce the size of the IR as much as possible. 500 MPM.add(createGlobalOptimizerPass()); 501 // Rename anon globals to be able to export them in the summary. 502 MPM.add(createNameAnonGlobalPass()); 503 return; 504 } 505 506 if (PerformThinLTO) 507 // Optimize globals now when performing ThinLTO, this enables more 508 // optimizations later. 509 MPM.add(createGlobalOptimizerPass()); 510 511 // Scheduling LoopVersioningLICM when inlining is over, because after that 512 // we may see more accurate aliasing. Reason to run this late is that too 513 // early versioning may prevent further inlining due to increase of code 514 // size. By placing it just after inlining other optimizations which runs 515 // later might get benefit of no-alias assumption in clone loop. 516 if (UseLoopVersioningLICM) { 517 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 518 MPM.add(createLICMPass()); // Hoist loop invariants 519 } 520 521 if (EnableNonLTOGlobalsModRef) 522 // We add a fresh GlobalsModRef run at this point. This is particularly 523 // useful as the above will have inlined, DCE'ed, and function-attr 524 // propagated everything. We should at this point have a reasonably minimal 525 // and richly annotated call graph. By computing aliasing and mod/ref 526 // information for all local globals here, the late loop passes and notably 527 // the vectorizer will be able to use them to help recognize vectorizable 528 // memory operations. 529 // 530 // Note that this relies on a bug in the pass manager which preserves 531 // a module analysis into a function pass pipeline (and throughout it) so 532 // long as the first function pass doesn't invalidate the module analysis. 533 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 534 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 535 // (doing nothing preserves it as it is required to be conservatively 536 // correct in the face of IR changes). 537 MPM.add(createGlobalsAAWrapperPass()); 538 539 if (RunFloat2Int) 540 MPM.add(createFloat2IntPass()); 541 542 addExtensionsToPM(EP_VectorizerStart, MPM); 543 544 // Re-rotate loops in all our loop nests. These may have fallout out of 545 // rotated form due to GVN or other transformations, and the vectorizer relies 546 // on the rotated form. Disable header duplication at -Oz. 547 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1)); 548 549 // Distribute loops to allow partial vectorization. I.e. isolate dependences 550 // into separate loop that would otherwise inhibit vectorization. This is 551 // currently only performed for loops marked with the metadata 552 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 553 MPM.add(createLoopDistributePass(/*ProcessAllLoopsByDefault=*/false)); 554 555 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize)); 556 557 // Eliminate loads by forwarding stores from the previous iteration to loads 558 // of the current iteration. 559 if (EnableLoopLoadElim) 560 MPM.add(createLoopLoadEliminationPass()); 561 562 // FIXME: Because of #pragma vectorize enable, the passes below are always 563 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when 564 // on -O1 and no #pragma is found). Would be good to have these two passes 565 // as function calls, so that we can only pass them when the vectorizer 566 // changed the code. 567 addInstructionCombiningPass(MPM); 568 if (OptLevel > 1 && ExtraVectorizerPasses) { 569 // At higher optimization levels, try to clean up any runtime overlap and 570 // alignment checks inserted by the vectorizer. We want to track correllated 571 // runtime checks for two inner loops in the same outer loop, fold any 572 // common computations, hoist loop-invariant aspects out of any outer loop, 573 // and unswitch the runtime checks if possible. Once hoisted, we may have 574 // dead (or speculatable) control flows or more combining opportunities. 575 MPM.add(createEarlyCSEPass()); 576 MPM.add(createCorrelatedValuePropagationPass()); 577 addInstructionCombiningPass(MPM); 578 MPM.add(createLICMPass()); 579 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); 580 MPM.add(createCFGSimplificationPass()); 581 addInstructionCombiningPass(MPM); 582 } 583 584 if (RunSLPAfterLoopVectorization) { 585 if (SLPVectorize) { 586 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 587 if (OptLevel > 1 && ExtraVectorizerPasses) { 588 MPM.add(createEarlyCSEPass()); 589 } 590 } 591 592 if (BBVectorize) { 593 MPM.add(createBBVectorizePass()); 594 addInstructionCombiningPass(MPM); 595 addExtensionsToPM(EP_Peephole, MPM); 596 if (OptLevel > 1 && UseGVNAfterVectorization) 597 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 598 else 599 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 600 601 // BBVectorize may have significantly shortened a loop body; unroll again. 602 if (!DisableUnrollLoops) 603 MPM.add(createLoopUnrollPass()); 604 } 605 } 606 607 addExtensionsToPM(EP_Peephole, MPM); 608 MPM.add(createCFGSimplificationPass()); 609 addInstructionCombiningPass(MPM); 610 611 if (!DisableUnrollLoops) { 612 MPM.add(createLoopUnrollPass()); // Unroll small loops 613 614 // LoopUnroll may generate some redundency to cleanup. 615 addInstructionCombiningPass(MPM); 616 617 // Runtime unrolling will introduce runtime check in loop prologue. If the 618 // unrolled loop is a inner loop, then the prologue will be inside the 619 // outer loop. LICM pass can help to promote the runtime check out if the 620 // checked value is loop invariant. 621 MPM.add(createLICMPass()); 622 623 // Get rid of LCSSA nodes. 624 MPM.add(createInstructionSimplifierPass()); 625 } 626 627 // After vectorization and unrolling, assume intrinsics may tell us more 628 // about pointer alignments. 629 MPM.add(createAlignmentFromAssumptionsPass()); 630 631 if (!DisableUnitAtATime) { 632 // FIXME: We shouldn't bother with this anymore. 633 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 634 635 // GlobalOpt already deletes dead functions and globals, at -O2 try a 636 // late pass of GlobalDCE. It is capable of deleting dead cycles. 637 if (OptLevel > 1) { 638 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 639 MPM.add(createConstantMergePass()); // Merge dup global constants 640 } 641 } 642 643 if (MergeFunctions) 644 MPM.add(createMergeFunctionsPass()); 645 646 addExtensionsToPM(EP_OptimizerLast, MPM); 647 } 648 649 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 650 // Remove unused virtual tables to improve the quality of code generated by 651 // whole-program devirtualization and bitset lowering. 652 PM.add(createGlobalDCEPass()); 653 654 // Provide AliasAnalysis services for optimizations. 655 addInitialAliasAnalysisPasses(PM); 656 657 if (ModuleSummary) 658 PM.add(createFunctionImportPass(ModuleSummary)); 659 660 // Allow forcing function attributes as a debugging and tuning aid. 661 PM.add(createForceFunctionAttrsLegacyPass()); 662 663 // Infer attributes about declarations if possible. 664 PM.add(createInferFunctionAttrsLegacyPass()); 665 666 if (OptLevel > 1) { 667 // Indirect call promotion. This should promote all the targets that are 668 // left by the earlier promotion pass that promotes intra-module targets. 669 // This two-step promotion is to save the compile time. For LTO, it should 670 // produce the same result as if we only do promotion here. 671 PM.add(createPGOIndirectCallPromotionLegacyPass(true)); 672 673 // Propagate constants at call sites into the functions they call. This 674 // opens opportunities for globalopt (and inlining) by substituting function 675 // pointers passed as arguments to direct uses of functions. 676 PM.add(createIPSCCPPass()); 677 } 678 679 // Infer attributes about definitions. The readnone attribute in particular is 680 // required for virtual constant propagation. 681 PM.add(createPostOrderFunctionAttrsLegacyPass()); 682 PM.add(createReversePostOrderFunctionAttrsPass()); 683 684 // Apply whole-program devirtualization and virtual constant propagation. 685 PM.add(createWholeProgramDevirtPass()); 686 687 // That's all we need at opt level 1. 688 if (OptLevel == 1) 689 return; 690 691 // Now that we internalized some globals, see if we can hack on them! 692 PM.add(createGlobalOptimizerPass()); 693 // Promote any localized global vars. 694 PM.add(createPromoteMemoryToRegisterPass()); 695 696 // Linking modules together can lead to duplicated global constants, only 697 // keep one copy of each constant. 698 PM.add(createConstantMergePass()); 699 700 // Remove unused arguments from functions. 701 PM.add(createDeadArgEliminationPass()); 702 703 // Reduce the code after globalopt and ipsccp. Both can open up significant 704 // simplification opportunities, and both can propagate functions through 705 // function pointers. When this happens, we often have to resolve varargs 706 // calls, etc, so let instcombine do this. 707 addInstructionCombiningPass(PM); 708 addExtensionsToPM(EP_Peephole, PM); 709 710 // Inline small functions 711 bool RunInliner = Inliner; 712 if (RunInliner) { 713 PM.add(Inliner); 714 Inliner = nullptr; 715 } 716 717 PM.add(createPruneEHPass()); // Remove dead EH info. 718 719 // Optimize globals again if we ran the inliner. 720 if (RunInliner) 721 PM.add(createGlobalOptimizerPass()); 722 PM.add(createGlobalDCEPass()); // Remove dead functions. 723 724 // If we didn't decide to inline a function, check to see if we can 725 // transform it to pass arguments by value instead of by reference. 726 PM.add(createArgumentPromotionPass()); 727 728 // The IPO passes may leave cruft around. Clean up after them. 729 addInstructionCombiningPass(PM); 730 addExtensionsToPM(EP_Peephole, PM); 731 PM.add(createJumpThreadingPass()); 732 733 // Break up allocas 734 PM.add(createSROAPass()); 735 736 // Run a few AA driven optimizations here and now, to cleanup the code. 737 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 738 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 739 740 PM.add(createLICMPass()); // Hoist loop invariants. 741 if (EnableMLSM) 742 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 743 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 744 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 745 746 // Nuke dead stores. 747 PM.add(createDeadStoreEliminationPass()); 748 749 // More loops are countable; try to optimize them. 750 PM.add(createIndVarSimplifyPass()); 751 PM.add(createLoopDeletionPass()); 752 if (EnableLoopInterchange) 753 PM.add(createLoopInterchangePass()); 754 755 if (!DisableUnrollLoops) 756 PM.add(createSimpleLoopUnrollPass()); // Unroll small loops 757 PM.add(createLoopVectorizePass(true, LoopVectorize)); 758 // The vectorizer may have significantly shortened a loop body; unroll again. 759 if (!DisableUnrollLoops) 760 PM.add(createLoopUnrollPass()); 761 762 // Now that we've optimized loops (in particular loop induction variables), 763 // we may have exposed more scalar opportunities. Run parts of the scalar 764 // optimizer again at this point. 765 addInstructionCombiningPass(PM); // Initial cleanup 766 PM.add(createCFGSimplificationPass()); // if-convert 767 PM.add(createSCCPPass()); // Propagate exposed constants 768 addInstructionCombiningPass(PM); // Clean up again 769 PM.add(createBitTrackingDCEPass()); 770 771 // More scalar chains could be vectorized due to more alias information 772 if (RunSLPAfterLoopVectorization) 773 if (SLPVectorize) 774 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 775 776 // After vectorization, assume intrinsics may tell us more about pointer 777 // alignments. 778 PM.add(createAlignmentFromAssumptionsPass()); 779 780 if (LoadCombine) 781 PM.add(createLoadCombinePass()); 782 783 // Cleanup and simplify the code after the scalar optimizations. 784 addInstructionCombiningPass(PM); 785 addExtensionsToPM(EP_Peephole, PM); 786 787 PM.add(createJumpThreadingPass()); 788 } 789 790 void PassManagerBuilder::addLateLTOOptimizationPasses( 791 legacy::PassManagerBase &PM) { 792 // Delete basic blocks, which optimization passes may have killed. 793 PM.add(createCFGSimplificationPass()); 794 795 // Drop bodies of available externally objects to improve GlobalDCE. 796 PM.add(createEliminateAvailableExternallyPass()); 797 798 // Now that we have optimized the program, discard unreachable functions. 799 PM.add(createGlobalDCEPass()); 800 801 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 802 // currently it damages debug info. 803 if (MergeFunctions) 804 PM.add(createMergeFunctionsPass()); 805 } 806 807 void PassManagerBuilder::populateThinLTOPassManager( 808 legacy::PassManagerBase &PM) { 809 PerformThinLTO = true; 810 811 if (VerifyInput) 812 PM.add(createVerifierPass()); 813 814 if (ModuleSummary) 815 PM.add(createFunctionImportPass(ModuleSummary)); 816 817 populateModulePassManager(PM); 818 819 if (VerifyOutput) 820 PM.add(createVerifierPass()); 821 PerformThinLTO = false; 822 } 823 824 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 825 if (LibraryInfo) 826 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 827 828 if (VerifyInput) 829 PM.add(createVerifierPass()); 830 831 if (OptLevel != 0) 832 addLTOOptimizationPasses(PM); 833 834 // Create a function that performs CFI checks for cross-DSO calls with targets 835 // in the current module. 836 PM.add(createCrossDSOCFIPass()); 837 838 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 839 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 840 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 841 PM.add(createLowerTypeTestsPass()); 842 843 if (OptLevel != 0) 844 addLateLTOOptimizationPasses(PM); 845 846 if (VerifyOutput) 847 PM.add(createVerifierPass()); 848 } 849 850 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) { 851 return reinterpret_cast<PassManagerBuilder*>(P); 852 } 853 854 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) { 855 return reinterpret_cast<LLVMPassManagerBuilderRef>(P); 856 } 857 858 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 859 PassManagerBuilder *PMB = new PassManagerBuilder(); 860 return wrap(PMB); 861 } 862 863 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 864 PassManagerBuilder *Builder = unwrap(PMB); 865 delete Builder; 866 } 867 868 void 869 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 870 unsigned OptLevel) { 871 PassManagerBuilder *Builder = unwrap(PMB); 872 Builder->OptLevel = OptLevel; 873 } 874 875 void 876 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 877 unsigned SizeLevel) { 878 PassManagerBuilder *Builder = unwrap(PMB); 879 Builder->SizeLevel = SizeLevel; 880 } 881 882 void 883 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 884 LLVMBool Value) { 885 PassManagerBuilder *Builder = unwrap(PMB); 886 Builder->DisableUnitAtATime = Value; 887 } 888 889 void 890 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 891 LLVMBool Value) { 892 PassManagerBuilder *Builder = unwrap(PMB); 893 Builder->DisableUnrollLoops = Value; 894 } 895 896 void 897 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 898 LLVMBool Value) { 899 // NOTE: The simplify-libcalls pass has been removed. 900 } 901 902 void 903 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 904 unsigned Threshold) { 905 PassManagerBuilder *Builder = unwrap(PMB); 906 Builder->Inliner = createFunctionInliningPass(Threshold); 907 } 908 909 void 910 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 911 LLVMPassManagerRef PM) { 912 PassManagerBuilder *Builder = unwrap(PMB); 913 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 914 Builder->populateFunctionPassManager(*FPM); 915 } 916 917 void 918 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 919 LLVMPassManagerRef PM) { 920 PassManagerBuilder *Builder = unwrap(PMB); 921 legacy::PassManagerBase *MPM = unwrap(PM); 922 Builder->populateModulePassManager(*MPM); 923 } 924 925 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 926 LLVMPassManagerRef PM, 927 LLVMBool Internalize, 928 LLVMBool RunInliner) { 929 PassManagerBuilder *Builder = unwrap(PMB); 930 legacy::PassManagerBase *LPM = unwrap(PM); 931 932 // A small backwards compatibility hack. populateLTOPassManager used to take 933 // an RunInliner option. 934 if (RunInliner && !Builder->Inliner) 935 Builder->Inliner = createFunctionInliningPass(); 936 937 Builder->populateLTOPassManager(*LPM); 938 } 939