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