Revert previous check in r168581, r169079 as they are still in code review status.
[oota-llvm.git] / lib / Transforms / IPO / PassManagerBuilder.cpp
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
18 #include "llvm-c/Transforms/PassManagerBuilder.h"
19
20 #include "llvm/PassManager.h"
21 #include "llvm/DefaultPasses.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/Analysis/Passes.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Target/TargetLibraryInfo.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Vectorize.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/Support/ManagedStatic.h"
32
33 using namespace llvm;
34
35 static cl::opt<bool>
36 RunLoopVectorization("vectorize-loops",
37                      cl::desc("Run the Loop vectorization passes"));
38
39 static cl::opt<bool>
40 RunBBVectorization("vectorize", cl::desc("Run the BB vectorization passes"));
41
42 static cl::opt<bool>
43 UseGVNAfterVectorization("use-gvn-after-vectorization",
44   cl::init(false), cl::Hidden,
45   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
46
47 static cl::opt<bool> UseNewSROA("use-new-sroa",
48   cl::init(true), cl::Hidden,
49   cl::desc("Enable the new, experimental SROA pass"));
50
51 PassManagerBuilder::PassManagerBuilder() {
52     OptLevel = 2;
53     SizeLevel = 0;
54     LibraryInfo = 0;
55     Inliner = 0;
56     DisableSimplifyLibCalls = false;
57     DisableUnitAtATime = false;
58     DisableUnrollLoops = false;
59     Vectorize = RunBBVectorization;
60     LoopVectorize = RunLoopVectorization;
61 }
62
63 PassManagerBuilder::~PassManagerBuilder() {
64   delete LibraryInfo;
65   delete Inliner;
66 }
67
68 /// Set of global extensions, automatically added as part of the standard set.
69 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
70    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
71
72 void PassManagerBuilder::addGlobalExtension(
73     PassManagerBuilder::ExtensionPointTy Ty,
74     PassManagerBuilder::ExtensionFn Fn) {
75   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
76 }
77
78 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
79   Extensions.push_back(std::make_pair(Ty, Fn));
80 }
81
82 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
83                                            PassManagerBase &PM) const {
84   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
85     if ((*GlobalExtensions)[i].first == ETy)
86       (*GlobalExtensions)[i].second(*this, PM);
87   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
88     if (Extensions[i].first == ETy)
89       Extensions[i].second(*this, PM);
90 }
91
92 void
93 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
94   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
95   // BasicAliasAnalysis wins if they disagree. This is intended to help
96   // support "obvious" type-punning idioms.
97   PM.add(createTypeBasedAliasAnalysisPass());
98   PM.add(createBasicAliasAnalysisPass());
99 }
100
101 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
102   addExtensionsToPM(EP_EarlyAsPossible, FPM);
103
104   // Add LibraryInfo if we have some.
105   if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
106
107   if (OptLevel == 0) return;
108
109   addInitialAliasAnalysisPasses(FPM);
110
111   FPM.add(createCFGSimplificationPass());
112   if (UseNewSROA)
113     FPM.add(createSROAPass());
114   else
115     FPM.add(createScalarReplAggregatesPass());
116   FPM.add(createEarlyCSEPass());
117   FPM.add(createLowerExpectIntrinsicPass());
118 }
119
120 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
121   // If all optimizations are disabled, just run the always-inline pass.
122   if (OptLevel == 0) {
123     if (Inliner) {
124       MPM.add(Inliner);
125       Inliner = 0;
126     }
127
128     // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
129     // pass manager, but we don't want to add extensions into that pass manager.
130     // To prevent this we must insert a no-op module pass to reset the pass
131     // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
132     if (!GlobalExtensions->empty() || !Extensions.empty())
133       MPM.add(createBarrierNoopPass());
134
135     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
136     return;
137   }
138
139   // Add LibraryInfo if we have some.
140   if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
141
142   addInitialAliasAnalysisPasses(MPM);
143
144   if (!DisableUnitAtATime) {
145     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
146
147     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
148
149     MPM.add(createIPSCCPPass());              // IP SCCP
150     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
151
152     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
153     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
154   }
155
156   // Start of CallGraph SCC passes.
157   if (!DisableUnitAtATime)
158     MPM.add(createPruneEHPass());             // Remove dead EH info
159   if (Inliner) {
160     MPM.add(Inliner);
161     Inliner = 0;
162   }
163   if (!DisableUnitAtATime)
164     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
165   if (OptLevel > 2)
166     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
167
168   // Start of function pass.
169   // Break up aggregate allocas, using SSAUpdater.
170   if (UseNewSROA)
171     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
172   else
173     MPM.add(createScalarReplAggregatesPass(-1, false));
174   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
175   if (!DisableSimplifyLibCalls)
176     MPM.add(createSimplifyLibCallsPass());    // Library Call Optimizations
177   MPM.add(createJumpThreadingPass());         // Thread jumps.
178   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
179   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
180   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
181
182   MPM.add(createTailCallEliminationPass());   // Eliminate tail calls
183   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
184   MPM.add(createReassociatePass());           // Reassociate expressions
185   MPM.add(createLoopRotatePass());            // Rotate Loop
186   MPM.add(createLICMPass());                  // Hoist loop invariants
187   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
188   MPM.add(createInstructionCombiningPass());
189   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
190   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
191   MPM.add(createLoopDeletionPass());          // Delete dead loops
192
193   if (LoopVectorize)
194     MPM.add(createLoopVectorizePass());
195
196   if (!DisableUnrollLoops)
197     MPM.add(createLoopUnrollPass());          // Unroll small loops
198   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
199
200   if (OptLevel > 1)
201     MPM.add(createGVNPass());                 // Remove redundancies
202   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
203   MPM.add(createSCCPPass());                  // Constant prop with SCCP
204
205   // Run instcombine after redundancy elimination to exploit opportunities
206   // opened up by them.
207   MPM.add(createInstructionCombiningPass());
208   MPM.add(createJumpThreadingPass());         // Thread jumps
209   MPM.add(createCorrelatedValuePropagationPass());
210   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
211
212   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
213
214   if (Vectorize) {
215     MPM.add(createBBVectorizePass());
216     MPM.add(createInstructionCombiningPass());
217     if (OptLevel > 1 && UseGVNAfterVectorization)
218       MPM.add(createGVNPass());                   // Remove redundancies
219     else
220       MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
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                                                   bool Internalize,
395                                                   bool RunInliner) {
396   PassManagerBuilder *Builder = unwrap(PMB);
397   PassManagerBase *LPM = unwrap(PM);
398   Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);
399 }