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