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