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