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