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