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/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"
32 RunLoopVectorization("vectorize-loops", cl::Hidden,
33 cl::desc("Run the Loop vectorization passes"));
36 RunSLPVectorization("vectorize-slp", cl::Hidden,
37 cl::desc("Run the SLP vectorization passes"));
40 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
41 cl::desc("Run the BB vectorization passes"));
44 UseGVNAfterVectorization("use-gvn-after-vectorization",
45 cl::init(false), cl::Hidden,
46 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
48 static cl::opt<bool> UseNewSROA("use-new-sroa",
49 cl::init(true), cl::Hidden,
50 cl::desc("Enable the new, experimental SROA pass"));
53 RunLoopRerolling("reroll-loops", cl::Hidden,
54 cl::desc("Run the loop rerolling pass"));
56 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
58 cl::desc("Run the load combining pass"));
60 PassManagerBuilder::PassManagerBuilder() {
63 LibraryInfo = 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;
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(createScopedNoAliasAAPass());
111 PM.add(createBasicAliasAnalysisPass());
114 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
115 addExtensionsToPM(EP_EarlyAsPossible, FPM);
117 // Add LibraryInfo if we have some.
118 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
120 if (OptLevel == 0) return;
122 addInitialAliasAnalysisPasses(FPM);
124 FPM.add(createCFGSimplificationPass());
126 FPM.add(createSROAPass());
128 FPM.add(createScalarReplAggregatesPass());
129 FPM.add(createEarlyCSEPass());
130 FPM.add(createLowerExpectIntrinsicPass());
133 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
134 // If all optimizations are disabled, just run the always-inline pass.
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());
148 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
152 // Add LibraryInfo if we have some.
153 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
155 addInitialAliasAnalysisPasses(MPM);
157 if (!DisableUnitAtATime) {
158 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
160 MPM.add(createIPSCCPPass()); // IP SCCP
161 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
163 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
165 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
166 addExtensionsToPM(EP_Peephole, MPM);
167 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
170 // Start of CallGraph SCC passes.
171 if (!DisableUnitAtATime)
172 MPM.add(createPruneEHPass()); // Remove dead EH info
177 if (!DisableUnitAtATime)
178 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
180 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
182 // Start of function pass.
183 // Break up aggregate allocas, using SSAUpdater.
185 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
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);
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
207 if (!DisableUnrollLoops)
208 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
209 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
212 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
213 MPM.add(createGVNPass()); // Remove redundancies
215 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
216 MPM.add(createSCCPPass()); // Constant prop with SCCP
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
226 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
229 MPM.add(createLoopRerollPass());
231 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
234 MPM.add(createBBVectorizePass());
235 MPM.add(createInstructionCombiningPass());
236 addExtensionsToPM(EP_Peephole, MPM);
237 if (OptLevel > 1 && UseGVNAfterVectorization)
238 MPM.add(createGVNPass()); // Remove redundancies
240 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
242 // BBVectorize may have significantly shortened a loop body; unroll again.
243 if (!DisableUnrollLoops)
244 MPM.add(createLoopUnrollPass());
248 MPM.add(createLoadCombinePass());
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);
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
265 MPM.add(createInstructionCombiningPass());
266 addExtensionsToPM(EP_Peephole, MPM);
267 MPM.add(createCFGSimplificationPass());
269 if (!DisableUnrollLoops)
270 MPM.add(createLoopUnrollPass()); // Unroll small loops
272 if (!DisableUnitAtATime) {
273 // FIXME: We shouldn't bother with this anymore.
274 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
276 // GlobalOpt already deletes dead functions and globals, at -O2 try a
277 // late pass of GlobalDCE. It is capable of deleting dead cycles.
279 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
280 MPM.add(createConstantMergePass()); // Merge dup global constants
283 addExtensionsToPM(EP_OptimizerLast, MPM);
286 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
288 bool DisableGVNLoadPRE) {
289 // Provide AliasAnalysis services for optimizations.
290 addInitialAliasAnalysisPasses(PM);
292 // Propagate constants at call sites into the functions they call. This
293 // opens opportunities for globalopt (and inlining) by substituting function
294 // pointers passed as arguments to direct uses of functions.
295 PM.add(createIPSCCPPass());
297 // Now that we internalized some globals, see if we can hack on them!
298 PM.add(createGlobalOptimizerPass());
300 // Linking modules together can lead to duplicated global constants, only
301 // keep one copy of each constant.
302 PM.add(createConstantMergePass());
304 // Remove unused arguments from functions.
305 PM.add(createDeadArgEliminationPass());
307 // Reduce the code after globalopt and ipsccp. Both can open up significant
308 // simplification opportunities, and both can propagate functions through
309 // function pointers. When this happens, we often have to resolve varargs
310 // calls, etc, so let instcombine do this.
311 PM.add(createInstructionCombiningPass());
312 addExtensionsToPM(EP_Peephole, PM);
314 // Inline small functions
316 PM.add(createFunctionInliningPass());
318 PM.add(createPruneEHPass()); // Remove dead EH info.
320 // Optimize globals again if we ran the inliner.
322 PM.add(createGlobalOptimizerPass());
323 PM.add(createGlobalDCEPass()); // Remove dead functions.
325 // If we didn't decide to inline a function, check to see if we can
326 // transform it to pass arguments by value instead of by reference.
327 PM.add(createArgumentPromotionPass());
329 // The IPO passes may leave cruft around. Clean up after them.
330 PM.add(createInstructionCombiningPass());
331 addExtensionsToPM(EP_Peephole, PM);
332 PM.add(createJumpThreadingPass());
336 PM.add(createSROAPass());
338 PM.add(createScalarReplAggregatesPass());
340 // Run a few AA driven optimizations here and now, to cleanup the code.
341 PM.add(createFunctionAttrsPass()); // Add nocapture.
342 PM.add(createGlobalsModRefPass()); // IP alias analysis.
344 PM.add(createLICMPass()); // Hoist loop invariants.
345 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
346 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
347 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
350 PM.add(createDeadStoreEliminationPass());
352 // More loops are countable; try to optimize them.
353 PM.add(createIndVarSimplifyPass());
354 PM.add(createLoopDeletionPass());
355 PM.add(createLoopVectorizePass(true, true));
357 // More scalar chains could be vectorized due to more alias information
358 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
361 PM.add(createLoadCombinePass());
363 // Cleanup and simplify the code after the scalar optimizations.
364 PM.add(createInstructionCombiningPass());
365 addExtensionsToPM(EP_Peephole, PM);
367 PM.add(createJumpThreadingPass());
369 // Delete basic blocks, which optimization passes may have killed.
370 PM.add(createCFGSimplificationPass());
372 // Now that we have optimized the program, discard unreachable functions.
373 PM.add(createGlobalDCEPass());
376 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
377 return reinterpret_cast<PassManagerBuilder*>(P);
380 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
381 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
384 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
385 PassManagerBuilder *PMB = new PassManagerBuilder();
389 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
390 PassManagerBuilder *Builder = unwrap(PMB);
395 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
397 PassManagerBuilder *Builder = unwrap(PMB);
398 Builder->OptLevel = OptLevel;
402 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
403 unsigned SizeLevel) {
404 PassManagerBuilder *Builder = unwrap(PMB);
405 Builder->SizeLevel = SizeLevel;
409 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
411 PassManagerBuilder *Builder = unwrap(PMB);
412 Builder->DisableUnitAtATime = Value;
416 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
418 PassManagerBuilder *Builder = unwrap(PMB);
419 Builder->DisableUnrollLoops = Value;
423 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
425 // NOTE: The simplify-libcalls pass has been removed.
429 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
430 unsigned Threshold) {
431 PassManagerBuilder *Builder = unwrap(PMB);
432 Builder->Inliner = createFunctionInliningPass(Threshold);
436 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
437 LLVMPassManagerRef PM) {
438 PassManagerBuilder *Builder = unwrap(PMB);
439 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
440 Builder->populateFunctionPassManager(*FPM);
444 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
445 LLVMPassManagerRef PM) {
446 PassManagerBuilder *Builder = unwrap(PMB);
447 PassManagerBase *MPM = unwrap(PM);
448 Builder->populateModulePassManager(*MPM);
451 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
452 LLVMPassManagerRef PM,
453 LLVMBool Internalize,
454 LLVMBool RunInliner) {
455 PassManagerBuilder *Builder = unwrap(PMB);
456 PassManagerBase *LPM = unwrap(PM);
457 Builder->populateLTOPassManager(*LPM, RunInliner != 0, false);