Reinstate r133513 (reverted in r133700) with an additional fix for a
[oota-llvm.git] / include / llvm / Support / PassManagerBuilder.h
1 //===-- llvm/Support/PassManagerBuilder.h - Build Standard Pass -*- C++ -*-===//
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 // These are implemented as inline functions so that we do not have to worry
14 // about link issues.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_SUPPORT_PASSMANAGERBUILDER_H
19 #define LLVM_SUPPORT_PASSMANAGERBUILDER_H
20
21 #include "llvm/PassManager.h"
22 #include "llvm/DefaultPasses.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Target/TargetLibraryInfo.h"
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/IPO.h"
28
29 namespace llvm {
30   
31 /// PassManagerBuilder - This class is used to set up a standard optimization
32 /// sequence for languages like C and C++, allowing some APIs to customize the
33 /// pass sequence in various ways. A simple example of using it would be:
34 ///
35 ///  PassManagerBuilder Builder;
36 ///  Builder.OptLevel = 2;
37 ///  Builder.populateFunctionPassManager(FPM);
38 ///  Builder.populateModulePassManager(MPM);
39 ///
40 /// In addition to setting up the basic passes, PassManagerBuilder allows
41 /// frontends to vend a plugin API, where plugins are allowed to add extensions
42 /// to the default pass manager.  They do this by specifying where in the pass
43 /// pipeline they want to be added, along with a callback function that adds
44 /// the pass(es).  For example, a plugin that wanted to add a loop optimization
45 /// could do something like this:
46 ///
47 /// static void addMyLoopPass(const PMBuilder &Builder, PassManagerBase &PM) {
48 ///   if (Builder.getOptLevel() > 2 && Builder.getOptSizeLevel() == 0)
49 ///     PM.add(createMyAwesomePass());
50 /// }
51 ///   ...
52 ///   Builder.addExtension(PassManagerBuilder::EP_LoopOptimizerEnd,
53 ///                        addMyLoopPass);
54 ///   ...
55 class PassManagerBuilder {
56 public:
57   
58   /// Extensions are passed the builder itself (so they can see how it is
59   /// configured) as well as the pass manager to add stuff to.
60   typedef void (*ExtensionFn)(const PassManagerBuilder &Builder,
61                               PassManagerBase &PM);
62   enum ExtensionPointTy {
63     /// EP_EarlyAsPossible - This extension point allows adding passes before
64     /// any other transformations, allowing them to see the code as it is coming
65     /// out of the frontend.
66     EP_EarlyAsPossible,
67     
68     /// EP_LoopOptimizerEnd - This extension point allows adding loop passes to
69     /// the end of the loop optimizer.
70     EP_LoopOptimizerEnd
71   };
72   
73   /// The Optimization Level - Specify the basic optimization level.
74   ///    0 = -O0, 1 = -O1, 2 = -O2, 3 = -O3
75   unsigned OptLevel;
76   
77   /// SizeLevel - How much we're optimizing for size.
78   ///    0 = none, 1 = -Os, 2 = -Oz
79   unsigned SizeLevel;
80   
81   /// LibraryInfo - Specifies information about the runtime library for the
82   /// optimizer.  If this is non-null, it is added to both the function and
83   /// per-module pass pipeline.
84   TargetLibraryInfo *LibraryInfo;
85   
86   /// Inliner - Specifies the inliner to use.  If this is non-null, it is
87   /// added to the per-module passes.
88   Pass *Inliner;
89   
90   bool DisableSimplifyLibCalls;
91   bool DisableUnitAtATime;
92   bool DisableUnrollLoops;
93   
94 private:
95   /// ExtensionList - This is list of all of the extensions that are registered.
96   std::vector<std::pair<ExtensionPointTy, ExtensionFn> > Extensions;
97   
98 public:
99   PassManagerBuilder() {
100     OptLevel = 2;
101     SizeLevel = 0;
102     LibraryInfo = 0;
103     Inliner = 0;
104     DisableSimplifyLibCalls = false;
105     DisableUnitAtATime = false;
106     DisableUnrollLoops = false;
107   }
108   
109   ~PassManagerBuilder() {
110     delete LibraryInfo;
111     delete Inliner;
112   }
113   
114   void addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
115     Extensions.push_back(std::make_pair(Ty, Fn));
116   }
117   
118 private:
119   void addExtensionsToPM(ExtensionPointTy ETy, PassManagerBase &PM) const {
120     for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
121       if (Extensions[i].first == ETy)
122         Extensions[i].second(*this, PM);
123   }
124   
125   void addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
126     // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
127     // BasicAliasAnalysis wins if they disagree. This is intended to help
128     // support "obvious" type-punning idioms.
129     PM.add(createTypeBasedAliasAnalysisPass());
130     PM.add(createBasicAliasAnalysisPass());
131   }
132 public:
133   
134   /// populateFunctionPassManager - This fills in the function pass manager,
135   /// which is expected to be run on each function immediately as it is
136   /// generated.  The idea is to reduce the size of the IR in memory.
137   void populateFunctionPassManager(FunctionPassManager &FPM) {
138     addExtensionsToPM(EP_EarlyAsPossible, FPM);
139     
140     // Add LibraryInfo if we have some.
141     if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
142
143     if (OptLevel == 0) return;
144
145     addInitialAliasAnalysisPasses(FPM);
146     
147     FPM.add(createCFGSimplificationPass());
148     FPM.add(createScalarReplAggregatesPass());
149     FPM.add(createEarlyCSEPass());
150   }
151   
152   /// populateModulePassManager - This sets up the primary pass manager.
153   void populateModulePassManager(PassManagerBase &MPM) {
154     // If all optimizations are disabled, just run the always-inline pass.
155     if (OptLevel == 0) {
156       if (Inliner) {
157         MPM.add(Inliner);
158         Inliner = 0;
159       }
160       return;
161     }
162       
163     // Add LibraryInfo if we have some.
164     if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
165
166     addInitialAliasAnalysisPasses(MPM);
167     
168     if (!DisableUnitAtATime) {
169       MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
170       
171       MPM.add(createIPSCCPPass());              // IP SCCP
172       MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
173       
174       MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
175       MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
176     }
177     
178     // Start of CallGraph SCC passes.
179     if (!DisableUnitAtATime)
180       MPM.add(createPruneEHPass());             // Remove dead EH info
181     if (Inliner) {
182       MPM.add(Inliner);
183       Inliner = 0;
184     }
185     if (!DisableUnitAtATime)
186       MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
187     if (OptLevel > 2)
188       MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
189     
190     // Start of function pass.
191     MPM.add(createObjCARCExpandPass());         // Canonicalize ObjC ARC code.
192     // Break up aggregate allocas, using SSAUpdater.
193     MPM.add(createScalarReplAggregatesPass(-1, false));
194     MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
195     if (!DisableSimplifyLibCalls)
196       MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
197     MPM.add(createJumpThreadingPass());         // Thread jumps.
198     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
199     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
200     MPM.add(createInstructionCombiningPass());  // Combine silly seq's
201     
202     MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
203     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
204     MPM.add(createReassociatePass());           // Reassociate expressions
205     MPM.add(createLoopRotatePass());            // Rotate Loop
206     MPM.add(createLICMPass());                  // Hoist loop invariants
207     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
208     MPM.add(createInstructionCombiningPass());  
209     MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
210     MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
211     MPM.add(createLoopDeletionPass());          // Delete dead loops
212     if (!DisableUnrollLoops)
213       MPM.add(createLoopUnrollPass());          // Unroll small loops
214     addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
215
216     if (OptLevel > 1)
217       MPM.add(createGVNPass());                 // Remove redundancies
218     MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
219     MPM.add(createSCCPPass());                  // Constant prop with SCCP
220     
221     // Run instcombine after redundancy elimination to exploit opportunities
222     // opened up by them.
223     MPM.add(createInstructionCombiningPass());
224     MPM.add(createJumpThreadingPass());         // Thread jumps
225     MPM.add(createCorrelatedValuePropagationPass());
226     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
227     MPM.add(createObjCARCOptPass());            // Objective-C ARC optimizations.
228     MPM.add(createAggressiveDCEPass());         // Delete dead instructions
229     MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
230     MPM.add(createInstructionCombiningPass());  // Clean up after everything.
231     
232     if (!DisableUnitAtATime) {
233       MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
234       MPM.add(createDeadTypeEliminationPass()); // Eliminate dead types
235       
236       // GlobalOpt already deletes dead functions and globals, at -O3 try a
237       // late pass of GlobalDCE.  It is capable of deleting dead cycles.
238       if (OptLevel > 2)
239         MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
240       
241       if (OptLevel > 1)
242         MPM.add(createConstantMergePass());     // Merge dup global constants
243     }
244   }
245   
246   void populateLTOPassManager(PassManagerBase &PM, bool Internalize,
247                               bool RunInliner) {
248     // Provide AliasAnalysis services for optimizations.
249     addInitialAliasAnalysisPasses(PM);
250     
251     // Now that composite has been compiled, scan through the module, looking
252     // for a main function.  If main is defined, mark all other functions
253     // internal.
254     if (Internalize)
255       PM.add(createInternalizePass(true));
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     PM.add(createScalarReplAggregatesPass());
298     
299     // Run a few AA driven optimizations here and now, to cleanup the code.
300     PM.add(createFunctionAttrsPass()); // Add nocapture.
301     PM.add(createGlobalsModRefPass()); // IP alias analysis.
302     
303     PM.add(createLICMPass());      // Hoist loop invariants.
304     PM.add(createGVNPass());       // Remove redundancies.
305     PM.add(createMemCpyOptPass()); // Remove dead memcpys.
306     // Nuke dead stores.
307     PM.add(createDeadStoreEliminationPass());
308     
309     // Cleanup and simplify the code after the scalar optimizations.
310     PM.add(createInstructionCombiningPass());
311     
312     PM.add(createJumpThreadingPass());
313     
314     // Delete basic blocks, which optimization passes may have killed.
315     PM.add(createCFGSimplificationPass());
316    
317     // Now that we have optimized the program, discard unreachable functions.
318     PM.add(createGlobalDCEPass());
319   }
320 };
321
322   
323 } // end namespace llvm
324 #endif