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 16 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 17 #include "llvm-c/Transforms/PassManagerBuilder.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/Analysis/Passes.h" 20 #include "llvm/IR/Verifier.h" 21 #include "llvm/PassManager.h" 22 #include "llvm/Support/CommandLine.h" 23 #include "llvm/Support/ManagedStatic.h" 24 #include "llvm/Target/TargetLibraryInfo.h" 25 #include "llvm/Transforms/IPO.h" 26 #include "llvm/Transforms/Scalar.h" 27 #include "llvm/Transforms/Vectorize.h" 28 29 using namespace llvm; 30 31 static cl::opt<bool> 32 RunLoopVectorization("vectorize-loops", cl::Hidden, 33 cl::desc("Run the Loop vectorization passes")); 34 35 static cl::opt<bool> 36 RunSLPVectorization("vectorize-slp", cl::Hidden, 37 cl::desc("Run the SLP vectorization passes")); 38 39 static cl::opt<bool> 40 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden, 41 cl::desc("Run the BB vectorization passes")); 42 43 static cl::opt<bool> 44 UseGVNAfterVectorization("use-gvn-after-vectorization", 45 cl::init(false), cl::Hidden, 46 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 47 48 static cl::opt<bool> UseNewSROA("use-new-sroa", 49 cl::init(true), cl::Hidden, 50 cl::desc("Enable the new, experimental SROA pass")); 51 52 static cl::opt<bool> 53 RunLoopRerolling("reroll-loops", cl::Hidden, 54 cl::desc("Run the loop rerolling pass")); 55 56 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false), 57 cl::Hidden, 58 cl::desc("Run the load combining pass")); 59 60 static cl::opt<bool> RunGVN("enable-gvn", cl::init(true), 61 cl::Hidden, 62 cl::desc("Run the global value numbering pass")); 63 64 PassManagerBuilder::PassManagerBuilder() { 65 OptLevel = 2; 66 SizeLevel = 0; 67 LibraryInfo = nullptr; 68 Inliner = nullptr; 69 DisableTailCalls = false; 70 DisableUnitAtATime = false; 71 DisableUnrollLoops = false; 72 BBVectorize = RunBBVectorization; 73 SLPVectorize = RunSLPVectorization; 74 LoopVectorize = RunLoopVectorization; 75 RerollLoops = RunLoopRerolling; 76 LoadCombine = RunLoadCombine; 77 } 78 79 PassManagerBuilder::~PassManagerBuilder() { 80 delete LibraryInfo; 81 delete Inliner; 82 } 83 84 /// Set of global extensions, automatically added as part of the standard set. 85 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy, 86 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions; 87 88 void PassManagerBuilder::addGlobalExtension( 89 PassManagerBuilder::ExtensionPointTy Ty, 90 PassManagerBuilder::ExtensionFn Fn) { 91 GlobalExtensions->push_back(std::make_pair(Ty, Fn)); 92 } 93 94 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 95 Extensions.push_back(std::make_pair(Ty, Fn)); 96 } 97 98 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 99 PassManagerBase &PM) const { 100 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i) 101 if ((*GlobalExtensions)[i].first == ETy) 102 (*GlobalExtensions)[i].second(*this, PM); 103 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 104 if (Extensions[i].first == ETy) 105 Extensions[i].second(*this, PM); 106 } 107 108 void 109 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const { 110 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 111 // BasicAliasAnalysis wins if they disagree. This is intended to help 112 // support "obvious" type-punning idioms. 113 PM.add(createTypeBasedAliasAnalysisPass()); 114 PM.add(createBasicAliasAnalysisPass()); 115 } 116 117 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) { 118 addExtensionsToPM(EP_EarlyAsPossible, FPM); 119 120 // Add LibraryInfo if we have some. 121 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo)); 122 123 if (OptLevel == 0) return; 124 125 addInitialAliasAnalysisPasses(FPM); 126 127 FPM.add(createCFGSimplificationPass()); 128 if (UseNewSROA) 129 FPM.add(createSROAPass()); 130 else 131 FPM.add(createScalarReplAggregatesPass()); 132 FPM.add(createEarlyCSEPass()); 133 FPM.add(createLowerExpectIntrinsicPass()); 134 } 135 136 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) { 137 // If all optimizations are disabled, just run the always-inline pass. 138 if (OptLevel == 0) { 139 if (Inliner) { 140 MPM.add(Inliner); 141 Inliner = nullptr; 142 } 143 144 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 145 // pass manager, but we don't want to add extensions into that pass manager. 146 // To prevent this we must insert a no-op module pass to reset the pass 147 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds. 148 if (!GlobalExtensions->empty() || !Extensions.empty()) 149 MPM.add(createBarrierNoopPass()); 150 151 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 152 return; 153 } 154 155 // Add LibraryInfo if we have some. 156 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo)); 157 158 addInitialAliasAnalysisPasses(MPM); 159 160 if (!DisableUnitAtATime) { 161 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 162 163 MPM.add(createIPSCCPPass()); // IP SCCP 164 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 165 166 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 167 168 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE 169 addExtensionsToPM(EP_Peephole, MPM); 170 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE 171 } 172 173 // Start of CallGraph SCC passes. 174 if (!DisableUnitAtATime) 175 MPM.add(createPruneEHPass()); // Remove dead EH info 176 if (Inliner) { 177 MPM.add(Inliner); 178 Inliner = nullptr; 179 } 180 if (!DisableUnitAtATime) 181 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs 182 if (OptLevel > 2) 183 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 184 185 // Start of function pass. 186 // Break up aggregate allocas, using SSAUpdater. 187 if (UseNewSROA) 188 MPM.add(createSROAPass(/*RequiresDomTree*/ false)); 189 else 190 MPM.add(createScalarReplAggregatesPass(-1, false)); 191 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 192 MPM.add(createJumpThreadingPass()); // Thread jumps. 193 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 194 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 195 MPM.add(createInstructionCombiningPass()); // Combine silly seq's 196 addExtensionsToPM(EP_Peephole, MPM); 197 198 if (!DisableTailCalls) 199 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 200 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 201 MPM.add(createReassociatePass()); // Reassociate expressions 202 // Rotate Loop - disable header duplication at -Oz 203 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1)); 204 MPM.add(createLICMPass()); // Hoist loop invariants 205 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); 206 MPM.add(createInstructionCombiningPass()); 207 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 208 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 209 MPM.add(createLoopDeletionPass()); // Delete dead loops 210 211 if (!DisableUnrollLoops) 212 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops 213 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 214 215 if (OptLevel > 1) { 216 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond 217 if (RunGVN) 218 MPM.add(createGVNPass()); // Remove redundancies 219 } 220 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 221 MPM.add(createSCCPPass()); // Constant prop with SCCP 222 223 // Run instcombine after redundancy elimination to exploit opportunities 224 // opened up by them. 225 MPM.add(createInstructionCombiningPass()); 226 addExtensionsToPM(EP_Peephole, MPM); 227 MPM.add(createJumpThreadingPass()); // Thread jumps 228 MPM.add(createCorrelatedValuePropagationPass()); 229 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 230 231 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 232 233 if (RerollLoops) 234 MPM.add(createLoopRerollPass()); 235 if (SLPVectorize) 236 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 237 238 if (BBVectorize) { 239 MPM.add(createBBVectorizePass()); 240 MPM.add(createInstructionCombiningPass()); 241 addExtensionsToPM(EP_Peephole, MPM); 242 if (OptLevel > 1 && UseGVNAfterVectorization) 243 MPM.add(createGVNPass()); // Remove redundancies 244 else 245 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 246 247 // BBVectorize may have significantly shortened a loop body; unroll again. 248 if (!DisableUnrollLoops) 249 MPM.add(createLoopUnrollPass()); 250 } 251 252 if (LoadCombine) 253 MPM.add(createLoadCombinePass()); 254 255 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 256 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 257 MPM.add(createInstructionCombiningPass()); // Clean up after everything. 258 addExtensionsToPM(EP_Peephole, MPM); 259 260 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 261 // pass manager that we are specifically trying to avoid. To prevent this 262 // we must insert a no-op module pass to reset the pass manager. 263 MPM.add(createBarrierNoopPass()); 264 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize)); 265 // FIXME: Because of #pragma vectorize enable, the passes below are always 266 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when 267 // on -O1 and no #pragma is found). Would be good to have these two passes 268 // as function calls, so that we can only pass them when the vectorizer 269 // changed the code. 270 MPM.add(createInstructionCombiningPass()); 271 addExtensionsToPM(EP_Peephole, MPM); 272 MPM.add(createCFGSimplificationPass()); 273 274 if (!DisableUnrollLoops) 275 MPM.add(createLoopUnrollPass()); // Unroll small loops 276 277 if (!DisableUnitAtATime) { 278 // FIXME: We shouldn't bother with this anymore. 279 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 280 281 // GlobalOpt already deletes dead functions and globals, at -O2 try a 282 // late pass of GlobalDCE. It is capable of deleting dead cycles. 283 if (OptLevel > 1) { 284 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 285 MPM.add(createConstantMergePass()); // Merge dup global constants 286 } 287 } 288 addExtensionsToPM(EP_OptimizerLast, MPM); 289 } 290 291 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM, 292 bool Internalize, 293 bool RunInliner, 294 bool DisableGVNLoadPRE) { 295 // Provide AliasAnalysis services for optimizations. 296 addInitialAliasAnalysisPasses(PM); 297 298 // Now that composite has been compiled, scan through the module, looking 299 // for a main function. If main is defined, mark all other functions 300 // internal. 301 if (Internalize) 302 PM.add(createInternalizePass("main")); 303 304 // Propagate constants at call sites into the functions they call. This 305 // opens opportunities for globalopt (and inlining) by substituting function 306 // pointers passed as arguments to direct uses of functions. 307 PM.add(createIPSCCPPass()); 308 309 // Now that we internalized some globals, see if we can hack on them! 310 PM.add(createGlobalOptimizerPass()); 311 312 // Linking modules together can lead to duplicated global constants, only 313 // keep one copy of each constant. 314 PM.add(createConstantMergePass()); 315 316 // Remove unused arguments from functions. 317 PM.add(createDeadArgEliminationPass()); 318 319 // Reduce the code after globalopt and ipsccp. Both can open up significant 320 // simplification opportunities, and both can propagate functions through 321 // function pointers. When this happens, we often have to resolve varargs 322 // calls, etc, so let instcombine do this. 323 PM.add(createInstructionCombiningPass()); 324 addExtensionsToPM(EP_Peephole, PM); 325 326 // Inline small functions 327 if (RunInliner) 328 PM.add(createFunctionInliningPass()); 329 330 PM.add(createPruneEHPass()); // Remove dead EH info. 331 332 // Optimize globals again if we ran the inliner. 333 if (RunInliner) 334 PM.add(createGlobalOptimizerPass()); 335 PM.add(createGlobalDCEPass()); // Remove dead functions. 336 337 // If we didn't decide to inline a function, check to see if we can 338 // transform it to pass arguments by value instead of by reference. 339 PM.add(createArgumentPromotionPass()); 340 341 // The IPO passes may leave cruft around. Clean up after them. 342 PM.add(createInstructionCombiningPass()); 343 addExtensionsToPM(EP_Peephole, PM); 344 PM.add(createJumpThreadingPass()); 345 346 // Break up allocas 347 if (UseNewSROA) 348 PM.add(createSROAPass()); 349 else 350 PM.add(createScalarReplAggregatesPass()); 351 352 // Run a few AA driven optimizations here and now, to cleanup the code. 353 PM.add(createFunctionAttrsPass()); // Add nocapture. 354 PM.add(createGlobalsModRefPass()); // IP alias analysis. 355 356 PM.add(createLICMPass()); // Hoist loop invariants. 357 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds 358 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 359 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 360 361 // Nuke dead stores. 362 PM.add(createDeadStoreEliminationPass()); 363 364 // More loops are countable; try to optimize them. 365 PM.add(createIndVarSimplifyPass()); 366 PM.add(createLoopDeletionPass()); 367 PM.add(createLoopVectorizePass(true, true)); 368 369 // More scalar chains could be vectorized due to more alias information 370 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 371 372 if (LoadCombine) 373 PM.add(createLoadCombinePass()); 374 375 // Cleanup and simplify the code after the scalar optimizations. 376 PM.add(createInstructionCombiningPass()); 377 addExtensionsToPM(EP_Peephole, PM); 378 379 PM.add(createJumpThreadingPass()); 380 381 // Delete basic blocks, which optimization passes may have killed. 382 PM.add(createCFGSimplificationPass()); 383 384 // Now that we have optimized the program, discard unreachable functions. 385 PM.add(createGlobalDCEPass()); 386 } 387 388 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) { 389 return reinterpret_cast<PassManagerBuilder*>(P); 390 } 391 392 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) { 393 return reinterpret_cast<LLVMPassManagerBuilderRef>(P); 394 } 395 396 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 397 PassManagerBuilder *PMB = new PassManagerBuilder(); 398 return wrap(PMB); 399 } 400 401 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 402 PassManagerBuilder *Builder = unwrap(PMB); 403 delete Builder; 404 } 405 406 void 407 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 408 unsigned OptLevel) { 409 PassManagerBuilder *Builder = unwrap(PMB); 410 Builder->OptLevel = OptLevel; 411 } 412 413 void 414 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 415 unsigned SizeLevel) { 416 PassManagerBuilder *Builder = unwrap(PMB); 417 Builder->SizeLevel = SizeLevel; 418 } 419 420 void 421 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 422 LLVMBool Value) { 423 PassManagerBuilder *Builder = unwrap(PMB); 424 Builder->DisableUnitAtATime = Value; 425 } 426 427 void 428 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 429 LLVMBool Value) { 430 PassManagerBuilder *Builder = unwrap(PMB); 431 Builder->DisableUnrollLoops = Value; 432 } 433 434 void 435 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 436 LLVMBool Value) { 437 // NOTE: The simplify-libcalls pass has been removed. 438 } 439 440 void 441 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 442 unsigned Threshold) { 443 PassManagerBuilder *Builder = unwrap(PMB); 444 Builder->Inliner = createFunctionInliningPass(Threshold); 445 } 446 447 void 448 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 449 LLVMPassManagerRef PM) { 450 PassManagerBuilder *Builder = unwrap(PMB); 451 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM); 452 Builder->populateFunctionPassManager(*FPM); 453 } 454 455 void 456 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 457 LLVMPassManagerRef PM) { 458 PassManagerBuilder *Builder = unwrap(PMB); 459 PassManagerBase *MPM = unwrap(PM); 460 Builder->populateModulePassManager(*MPM); 461 } 462 463 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 464 LLVMPassManagerRef PM, 465 LLVMBool Internalize, 466 LLVMBool RunInliner) { 467 PassManagerBuilder *Builder = unwrap(PMB); 468 PassManagerBase *LPM = unwrap(PM); 469 Builder->populateLTOPassManager(*LPM, Internalize != 0, RunInliner != 0); 470 } 471