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