LLVM API Documentation

PassManagerBuilder.cpp
Go to the documentation of this file.
00001 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the PassManagerBuilder class, which is used to set up a
00011 // "standard" optimization sequence suitable for languages like C and C++.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 
00016 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
00017 #include "llvm-c/Transforms/PassManagerBuilder.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/Analysis/Passes.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/Verifier.h"
00022 #include "llvm/PassManager.h"
00023 #include "llvm/Support/CommandLine.h"
00024 #include "llvm/Support/ManagedStatic.h"
00025 #include "llvm/Target/TargetLibraryInfo.h"
00026 #include "llvm/Target/TargetMachine.h"
00027 #include "llvm/Target/TargetSubtargetInfo.h"
00028 #include "llvm/Transforms/IPO.h"
00029 #include "llvm/Transforms/Scalar.h"
00030 #include "llvm/Transforms/Vectorize.h"
00031 
00032 using namespace llvm;
00033 
00034 static cl::opt<bool>
00035 RunLoopVectorization("vectorize-loops", cl::Hidden,
00036                      cl::desc("Run the Loop vectorization passes"));
00037 
00038 static cl::opt<bool>
00039 RunSLPVectorization("vectorize-slp", cl::Hidden,
00040                     cl::desc("Run the SLP vectorization passes"));
00041 
00042 static cl::opt<bool>
00043 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
00044                     cl::desc("Run the BB vectorization passes"));
00045 
00046 static cl::opt<bool>
00047 UseGVNAfterVectorization("use-gvn-after-vectorization",
00048   cl::init(false), cl::Hidden,
00049   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
00050 
00051 static cl::opt<bool> UseNewSROA("use-new-sroa",
00052   cl::init(true), cl::Hidden,
00053   cl::desc("Enable the new, experimental SROA pass"));
00054 
00055 static cl::opt<bool>
00056 RunLoopRerolling("reroll-loops", cl::Hidden,
00057                  cl::desc("Run the loop rerolling pass"));
00058 
00059 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
00060                                     cl::Hidden,
00061                                     cl::desc("Run the load combining pass"));
00062 
00063 static cl::opt<bool>
00064 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
00065   cl::init(false), cl::Hidden,
00066   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
00067            "vectorizer instead of before"));
00068 
00069 
00070 PassManagerBuilder::PassManagerBuilder() {
00071     OptLevel = 2;
00072     SizeLevel = 0;
00073     LibraryInfo = nullptr;
00074     Inliner = nullptr;
00075     DisableTailCalls = false;
00076     DisableUnitAtATime = false;
00077     DisableUnrollLoops = false;
00078     BBVectorize = RunBBVectorization;
00079     SLPVectorize = RunSLPVectorization;
00080     LoopVectorize = RunLoopVectorization;
00081     RerollLoops = RunLoopRerolling;
00082     LoadCombine = RunLoadCombine;
00083     DisableGVNLoadPRE = false;
00084     VerifyInput = false;
00085     VerifyOutput = false;
00086     StripDebug = false;
00087 }
00088 
00089 PassManagerBuilder::~PassManagerBuilder() {
00090   delete LibraryInfo;
00091   delete Inliner;
00092 }
00093 
00094 /// Set of global extensions, automatically added as part of the standard set.
00095 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
00096    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
00097 
00098 void PassManagerBuilder::addGlobalExtension(
00099     PassManagerBuilder::ExtensionPointTy Ty,
00100     PassManagerBuilder::ExtensionFn Fn) {
00101   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
00102 }
00103 
00104 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
00105   Extensions.push_back(std::make_pair(Ty, Fn));
00106 }
00107 
00108 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
00109                                            PassManagerBase &PM) const {
00110   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
00111     if ((*GlobalExtensions)[i].first == ETy)
00112       (*GlobalExtensions)[i].second(*this, PM);
00113   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
00114     if (Extensions[i].first == ETy)
00115       Extensions[i].second(*this, PM);
00116 }
00117 
00118 void
00119 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
00120   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
00121   // BasicAliasAnalysis wins if they disagree. This is intended to help
00122   // support "obvious" type-punning idioms.
00123   PM.add(createTypeBasedAliasAnalysisPass());
00124   PM.add(createScopedNoAliasAAPass());
00125   PM.add(createBasicAliasAnalysisPass());
00126 }
00127 
00128 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
00129   addExtensionsToPM(EP_EarlyAsPossible, FPM);
00130 
00131   // Add LibraryInfo if we have some.
00132   if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
00133 
00134   if (OptLevel == 0) return;
00135 
00136   addInitialAliasAnalysisPasses(FPM);
00137 
00138   FPM.add(createCFGSimplificationPass());
00139   if (UseNewSROA)
00140     FPM.add(createSROAPass());
00141   else
00142     FPM.add(createScalarReplAggregatesPass());
00143   FPM.add(createEarlyCSEPass());
00144   FPM.add(createLowerExpectIntrinsicPass());
00145 }
00146 
00147 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
00148   // If all optimizations are disabled, just run the always-inline pass.
00149   if (OptLevel == 0) {
00150     if (Inliner) {
00151       MPM.add(Inliner);
00152       Inliner = nullptr;
00153     }
00154 
00155     // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
00156     // pass manager, but we don't want to add extensions into that pass manager.
00157     // To prevent this we must insert a no-op module pass to reset the pass
00158     // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
00159     if (!GlobalExtensions->empty() || !Extensions.empty())
00160       MPM.add(createBarrierNoopPass());
00161 
00162     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
00163     return;
00164   }
00165 
00166   // Add LibraryInfo if we have some.
00167   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
00168 
00169   addInitialAliasAnalysisPasses(MPM);
00170 
00171   if (!DisableUnitAtATime) {
00172     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
00173 
00174     MPM.add(createIPSCCPPass());              // IP SCCP
00175     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
00176 
00177     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
00178 
00179     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
00180     addExtensionsToPM(EP_Peephole, MPM);
00181     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
00182   }
00183 
00184   // Start of CallGraph SCC passes.
00185   if (!DisableUnitAtATime)
00186     MPM.add(createPruneEHPass());             // Remove dead EH info
00187   if (Inliner) {
00188     MPM.add(Inliner);
00189     Inliner = nullptr;
00190   }
00191   if (!DisableUnitAtATime)
00192     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
00193   if (OptLevel > 2)
00194     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
00195 
00196   // Start of function pass.
00197   // Break up aggregate allocas, using SSAUpdater.
00198   if (UseNewSROA)
00199     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
00200   else
00201     MPM.add(createScalarReplAggregatesPass(-1, false));
00202   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
00203   MPM.add(createJumpThreadingPass());         // Thread jumps.
00204   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
00205   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
00206   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
00207   addExtensionsToPM(EP_Peephole, MPM);
00208 
00209   if (!DisableTailCalls)
00210     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
00211   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
00212   MPM.add(createReassociatePass());           // Reassociate expressions
00213   MPM.add(createLoopRotatePass());            // Rotate Loop
00214   MPM.add(createLICMPass());                  // Hoist loop invariants
00215   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
00216   MPM.add(createInstructionCombiningPass());
00217   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
00218   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
00219   MPM.add(createLoopDeletionPass());          // Delete dead loops
00220 
00221   if (!DisableUnrollLoops)
00222     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
00223   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
00224 
00225   if (OptLevel > 1) {
00226     MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
00227     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
00228   }
00229   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
00230   MPM.add(createSCCPPass());                  // Constant prop with SCCP
00231 
00232   // Run instcombine after redundancy elimination to exploit opportunities
00233   // opened up by them.
00234   MPM.add(createInstructionCombiningPass());
00235   addExtensionsToPM(EP_Peephole, MPM);
00236   MPM.add(createJumpThreadingPass());         // Thread jumps
00237   MPM.add(createCorrelatedValuePropagationPass());
00238   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
00239 
00240   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
00241 
00242   if (RerollLoops)
00243     MPM.add(createLoopRerollPass());
00244   if (!RunSLPAfterLoopVectorization) {
00245     if (SLPVectorize)
00246       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
00247 
00248     if (BBVectorize) {
00249       MPM.add(createBBVectorizePass());
00250       MPM.add(createInstructionCombiningPass());
00251       addExtensionsToPM(EP_Peephole, MPM);
00252       if (OptLevel > 1 && UseGVNAfterVectorization)
00253         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
00254       else
00255         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
00256 
00257       // BBVectorize may have significantly shortened a loop body; unroll again.
00258       if (!DisableUnrollLoops)
00259         MPM.add(createLoopUnrollPass());
00260     }
00261   }
00262 
00263   if (LoadCombine)
00264     MPM.add(createLoadCombinePass());
00265 
00266   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
00267   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
00268   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
00269   addExtensionsToPM(EP_Peephole, MPM);
00270 
00271   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
00272   // pass manager that we are specifically trying to avoid. To prevent this
00273   // we must insert a no-op module pass to reset the pass manager.
00274   MPM.add(createBarrierNoopPass());
00275   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
00276   // FIXME: Because of #pragma vectorize enable, the passes below are always
00277   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
00278   // on -O1 and no #pragma is found). Would be good to have these two passes
00279   // as function calls, so that we can only pass them when the vectorizer
00280   // changed the code.
00281   MPM.add(createInstructionCombiningPass());
00282 
00283   if (RunSLPAfterLoopVectorization) {
00284     if (SLPVectorize)
00285       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
00286 
00287     if (BBVectorize) {
00288       MPM.add(createBBVectorizePass());
00289       MPM.add(createInstructionCombiningPass());
00290       addExtensionsToPM(EP_Peephole, MPM);
00291       if (OptLevel > 1 && UseGVNAfterVectorization)
00292         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
00293       else
00294         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
00295 
00296       // BBVectorize may have significantly shortened a loop body; unroll again.
00297       if (!DisableUnrollLoops)
00298         MPM.add(createLoopUnrollPass());
00299     }
00300   }
00301 
00302   addExtensionsToPM(EP_Peephole, MPM);
00303   MPM.add(createCFGSimplificationPass());
00304 
00305   if (!DisableUnrollLoops)
00306     MPM.add(createLoopUnrollPass());    // Unroll small loops
00307 
00308   if (!DisableUnitAtATime) {
00309     // FIXME: We shouldn't bother with this anymore.
00310     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
00311 
00312     // GlobalOpt already deletes dead functions and globals, at -O2 try a
00313     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
00314     if (OptLevel > 1) {
00315       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
00316       MPM.add(createConstantMergePass());     // Merge dup global constants
00317     }
00318   }
00319   addExtensionsToPM(EP_OptimizerLast, MPM);
00320 }
00321 
00322 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
00323   // Provide AliasAnalysis services for optimizations.
00324   addInitialAliasAnalysisPasses(PM);
00325 
00326   // Propagate constants at call sites into the functions they call.  This
00327   // opens opportunities for globalopt (and inlining) by substituting function
00328   // pointers passed as arguments to direct uses of functions.
00329   PM.add(createIPSCCPPass());
00330 
00331   // Now that we internalized some globals, see if we can hack on them!
00332   PM.add(createGlobalOptimizerPass());
00333 
00334   // Linking modules together can lead to duplicated global constants, only
00335   // keep one copy of each constant.
00336   PM.add(createConstantMergePass());
00337 
00338   // Remove unused arguments from functions.
00339   PM.add(createDeadArgEliminationPass());
00340 
00341   // Reduce the code after globalopt and ipsccp.  Both can open up significant
00342   // simplification opportunities, and both can propagate functions through
00343   // function pointers.  When this happens, we often have to resolve varargs
00344   // calls, etc, so let instcombine do this.
00345   PM.add(createInstructionCombiningPass());
00346   addExtensionsToPM(EP_Peephole, PM);
00347 
00348   // Inline small functions
00349   bool RunInliner = Inliner;
00350   if (RunInliner) {
00351     PM.add(Inliner);
00352     Inliner = nullptr;
00353   }
00354 
00355   PM.add(createPruneEHPass());   // Remove dead EH info.
00356 
00357   // Optimize globals again if we ran the inliner.
00358   if (RunInliner)
00359     PM.add(createGlobalOptimizerPass());
00360   PM.add(createGlobalDCEPass()); // Remove dead functions.
00361 
00362   // If we didn't decide to inline a function, check to see if we can
00363   // transform it to pass arguments by value instead of by reference.
00364   PM.add(createArgumentPromotionPass());
00365 
00366   // The IPO passes may leave cruft around.  Clean up after them.
00367   PM.add(createInstructionCombiningPass());
00368   addExtensionsToPM(EP_Peephole, PM);
00369   PM.add(createJumpThreadingPass());
00370 
00371   // Break up allocas
00372   if (UseNewSROA)
00373     PM.add(createSROAPass());
00374   else
00375     PM.add(createScalarReplAggregatesPass());
00376 
00377   // Run a few AA driven optimizations here and now, to cleanup the code.
00378   PM.add(createFunctionAttrsPass()); // Add nocapture.
00379   PM.add(createGlobalsModRefPass()); // IP alias analysis.
00380 
00381   PM.add(createLICMPass());                 // Hoist loop invariants.
00382   PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
00383   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
00384   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
00385 
00386   // Nuke dead stores.
00387   PM.add(createDeadStoreEliminationPass());
00388 
00389   // More loops are countable; try to optimize them.
00390   PM.add(createIndVarSimplifyPass());
00391   PM.add(createLoopDeletionPass());
00392   PM.add(createLoopVectorizePass(true, true));
00393 
00394   // More scalar chains could be vectorized due to more alias information
00395   PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
00396 
00397   if (LoadCombine)
00398     PM.add(createLoadCombinePass());
00399 
00400   // Cleanup and simplify the code after the scalar optimizations.
00401   PM.add(createInstructionCombiningPass());
00402   addExtensionsToPM(EP_Peephole, PM);
00403 
00404   PM.add(createJumpThreadingPass());
00405 
00406   // Delete basic blocks, which optimization passes may have killed.
00407   PM.add(createCFGSimplificationPass());
00408 
00409   // Now that we have optimized the program, discard unreachable functions.
00410   PM.add(createGlobalDCEPass());
00411 }
00412 
00413 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
00414                                                 TargetMachine *TM) {
00415   if (TM) {
00416     const DataLayout *DL = TM->getSubtargetImpl()->getDataLayout();
00417     PM.add(new DataLayoutPass(*DL));
00418     TM->addAnalysisPasses(PM);
00419   }
00420 
00421   if (LibraryInfo)
00422     PM.add(new TargetLibraryInfo(*LibraryInfo));
00423 
00424   if (VerifyInput)
00425     PM.add(createVerifierPass());
00426 
00427   if (StripDebug)
00428     PM.add(createStripSymbolsPass(true));
00429 
00430   if (VerifyInput)
00431     PM.add(createDebugInfoVerifierPass());
00432 
00433   if (OptLevel != 0)
00434     addLTOOptimizationPasses(PM);
00435 
00436   if (VerifyOutput) {
00437     PM.add(createVerifierPass());
00438     PM.add(createDebugInfoVerifierPass());
00439   }
00440 }
00441 
00442 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
00443     return reinterpret_cast<PassManagerBuilder*>(P);
00444 }
00445 
00446 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
00447   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
00448 }
00449 
00450 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
00451   PassManagerBuilder *PMB = new PassManagerBuilder();
00452   return wrap(PMB);
00453 }
00454 
00455 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
00456   PassManagerBuilder *Builder = unwrap(PMB);
00457   delete Builder;
00458 }
00459 
00460 void
00461 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
00462                                   unsigned OptLevel) {
00463   PassManagerBuilder *Builder = unwrap(PMB);
00464   Builder->OptLevel = OptLevel;
00465 }
00466 
00467 void
00468 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
00469                                    unsigned SizeLevel) {
00470   PassManagerBuilder *Builder = unwrap(PMB);
00471   Builder->SizeLevel = SizeLevel;
00472 }
00473 
00474 void
00475 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
00476                                             LLVMBool Value) {
00477   PassManagerBuilder *Builder = unwrap(PMB);
00478   Builder->DisableUnitAtATime = Value;
00479 }
00480 
00481 void
00482 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
00483                                             LLVMBool Value) {
00484   PassManagerBuilder *Builder = unwrap(PMB);
00485   Builder->DisableUnrollLoops = Value;
00486 }
00487 
00488 void
00489 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
00490                                                  LLVMBool Value) {
00491   // NOTE: The simplify-libcalls pass has been removed.
00492 }
00493 
00494 void
00495 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
00496                                               unsigned Threshold) {
00497   PassManagerBuilder *Builder = unwrap(PMB);
00498   Builder->Inliner = createFunctionInliningPass(Threshold);
00499 }
00500 
00501 void
00502 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
00503                                                   LLVMPassManagerRef PM) {
00504   PassManagerBuilder *Builder = unwrap(PMB);
00505   FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
00506   Builder->populateFunctionPassManager(*FPM);
00507 }
00508 
00509 void
00510 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
00511                                                 LLVMPassManagerRef PM) {
00512   PassManagerBuilder *Builder = unwrap(PMB);
00513   PassManagerBase *MPM = unwrap(PM);
00514   Builder->populateModulePassManager(*MPM);
00515 }
00516 
00517 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
00518                                                   LLVMPassManagerRef PM,
00519                                                   LLVMBool Internalize,
00520                                                   LLVMBool RunInliner) {
00521   PassManagerBuilder *Builder = unwrap(PMB);
00522   PassManagerBase *LPM = unwrap(PM);
00523 
00524   // A small backwards compatibility hack. populateLTOPassManager used to take
00525   // an RunInliner option.
00526   if (RunInliner && !Builder->Inliner)
00527     Builder->Inliner = createFunctionInliningPass();
00528 
00529   Builder->populateLTOPassManager(*LPM);
00530 }