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