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