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