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