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