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