1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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++.
13 //===----------------------------------------------------------------------===//
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"
32 RunLoopVectorization("vectorize-loops", cl::Hidden,
33 cl::desc("Run the Loop vectorization passes"));
36 LateVectorization("late-vectorize", cl::init(true), cl::Hidden,
37 cl::desc("Run the vectorization pasess late in the pass "
38 "pipeline (after the inliner)"));
41 RunSLPVectorization("vectorize-slp", cl::Hidden,
42 cl::desc("Run the SLP vectorization passes"));
45 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
46 cl::desc("Run the BB vectorization passes"));
49 UseGVNAfterVectorization("use-gvn-after-vectorization",
50 cl::init(false), cl::Hidden,
51 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
53 static cl::opt<bool> UseNewSROA("use-new-sroa",
54 cl::init(true), cl::Hidden,
55 cl::desc("Enable the new, experimental SROA pass"));
58 RunLoopRerolling("reroll-loops", cl::Hidden,
59 cl::desc("Run the loop rerolling pass"));
61 PassManagerBuilder::PassManagerBuilder() {
66 DisableUnitAtATime = false;
67 DisableUnrollLoops = false;
68 BBVectorize = RunBBVectorization;
69 SLPVectorize = RunSLPVectorization;
70 LoopVectorize = RunLoopVectorization;
71 LateVectorize = LateVectorization;
72 RerollLoops = RunLoopRerolling;
75 PassManagerBuilder::~PassManagerBuilder() {
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;
84 void PassManagerBuilder::addGlobalExtension(
85 PassManagerBuilder::ExtensionPointTy Ty,
86 PassManagerBuilder::ExtensionFn Fn) {
87 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
90 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
91 Extensions.push_back(std::make_pair(Ty, Fn));
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);
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());
113 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
114 addExtensionsToPM(EP_EarlyAsPossible, FPM);
116 // Add LibraryInfo if we have some.
117 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
119 if (OptLevel == 0) return;
121 addInitialAliasAnalysisPasses(FPM);
123 FPM.add(createCFGSimplificationPass());
125 FPM.add(createSROAPass());
127 FPM.add(createScalarReplAggregatesPass());
128 FPM.add(createEarlyCSEPass());
129 FPM.add(createLowerExpectIntrinsicPass());
132 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
133 // If all optimizations are disabled, just run the always-inline pass.
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());
147 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
151 // Add LibraryInfo if we have some.
152 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
154 addInitialAliasAnalysisPasses(MPM);
156 if (!DisableUnitAtATime) {
157 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
159 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
161 MPM.add(createIPSCCPPass()); // IP SCCP
162 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
164 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
165 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
168 // Start of CallGraph SCC passes.
169 if (!DisableUnitAtATime)
170 MPM.add(createPruneEHPass()); // Remove dead EH info
175 if (!DisableUnitAtATime)
176 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
178 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
180 // Start of function pass.
181 // Break up aggregate allocas, using SSAUpdater.
183 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
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
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
203 if (!LateVectorize && LoopVectorize)
204 MPM.add(createLoopVectorizePass(DisableUnrollLoops));
206 if (!DisableUnrollLoops)
207 MPM.add(createLoopUnrollPass()); // Unroll small loops
208 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
211 MPM.add(createGVNPass()); // Remove redundancies
212 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
213 MPM.add(createSCCPPass()); // Constant prop with SCCP
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
222 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
225 MPM.add(createLoopRerollPass());
227 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
230 MPM.add(createBBVectorizePass());
231 MPM.add(createInstructionCombiningPass());
232 if (OptLevel > 1 && UseGVNAfterVectorization)
233 MPM.add(createGVNPass()); // Remove redundancies
235 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
237 // BBVectorize may have significantly shortened a loop body; unroll again.
238 if (!DisableUnrollLoops)
239 MPM.add(createLoopUnrollPass());
242 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
243 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
244 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
246 // As an experimental mode, run any vectorization passes in a separate
247 // pipeline from the CGSCC pass manager that runs iteratively with the
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());
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());
262 if (!DisableUnitAtATime) {
263 // FIXME: We shouldn't bother with this anymore.
264 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
266 // GlobalOpt already deletes dead functions and globals, at -O2 try a
267 // late pass of GlobalDCE. It is capable of deleting dead cycles.
269 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
270 MPM.add(createConstantMergePass()); // Merge dup global constants
273 addExtensionsToPM(EP_OptimizerLast, MPM);
276 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
279 bool DisableGVNLoadPRE) {
280 // Provide AliasAnalysis services for optimizations.
281 addInitialAliasAnalysisPasses(PM);
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
287 PM.add(createInternalizePass("main"));
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());
294 // Now that we internalized some globals, see if we can hack on them!
295 PM.add(createGlobalOptimizerPass());
297 // Linking modules together can lead to duplicated global constants, only
298 // keep one copy of each constant.
299 PM.add(createConstantMergePass());
301 // Remove unused arguments from functions.
302 PM.add(createDeadArgEliminationPass());
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());
310 // Inline small functions
312 PM.add(createFunctionInliningPass());
314 PM.add(createPruneEHPass()); // Remove dead EH info.
316 // Optimize globals again if we ran the inliner.
318 PM.add(createGlobalOptimizerPass());
319 PM.add(createGlobalDCEPass()); // Remove dead functions.
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());
325 // The IPO passes may leave cruft around. Clean up after them.
326 PM.add(createInstructionCombiningPass());
327 PM.add(createJumpThreadingPass());
331 PM.add(createSROAPass());
333 PM.add(createScalarReplAggregatesPass());
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.
339 PM.add(createLICMPass()); // Hoist loop invariants.
340 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
341 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
344 PM.add(createDeadStoreEliminationPass());
346 // Cleanup and simplify the code after the scalar optimizations.
347 PM.add(createInstructionCombiningPass());
349 PM.add(createJumpThreadingPass());
351 // Delete basic blocks, which optimization passes may have killed.
352 PM.add(createCFGSimplificationPass());
354 // Now that we have optimized the program, discard unreachable functions.
355 PM.add(createGlobalDCEPass());
358 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
359 return reinterpret_cast<PassManagerBuilder*>(P);
362 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
363 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
366 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
367 PassManagerBuilder *PMB = new PassManagerBuilder();
371 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
372 PassManagerBuilder *Builder = unwrap(PMB);
377 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
379 PassManagerBuilder *Builder = unwrap(PMB);
380 Builder->OptLevel = OptLevel;
384 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
385 unsigned SizeLevel) {
386 PassManagerBuilder *Builder = unwrap(PMB);
387 Builder->SizeLevel = SizeLevel;
391 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
393 PassManagerBuilder *Builder = unwrap(PMB);
394 Builder->DisableUnitAtATime = Value;
398 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
400 PassManagerBuilder *Builder = unwrap(PMB);
401 Builder->DisableUnrollLoops = Value;
405 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
407 // NOTE: The simplify-libcalls pass has been removed.
411 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
412 unsigned Threshold) {
413 PassManagerBuilder *Builder = unwrap(PMB);
414 Builder->Inliner = createFunctionInliningPass(Threshold);
418 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
419 LLVMPassManagerRef PM) {
420 PassManagerBuilder *Builder = unwrap(PMB);
421 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
422 Builder->populateFunctionPassManager(*FPM);
426 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
427 LLVMPassManagerRef PM) {
428 PassManagerBuilder *Builder = unwrap(PMB);
429 PassManagerBase *MPM = unwrap(PM);
430 Builder->populateModulePassManager(*MPM);
433 void 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);