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