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