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"));
61 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
62 cl::init(false), cl::Hidden,
63 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
64 "vectorizer instead of before"));
67 PassManagerBuilder::PassManagerBuilder() {
70 LibraryInfo = nullptr;
72 DisableTailCalls = false;
73 DisableUnitAtATime = false;
74 DisableUnrollLoops = false;
75 BBVectorize = RunBBVectorization;
76 SLPVectorize = RunSLPVectorization;
77 LoopVectorize = RunLoopVectorization;
78 RerollLoops = RunLoopRerolling;
79 LoadCombine = RunLoadCombine;
80 DisableGVNLoadPRE = false;
83 PassManagerBuilder::~PassManagerBuilder() {
88 /// Set of global extensions, automatically added as part of the standard set.
89 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
90 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
92 void PassManagerBuilder::addGlobalExtension(
93 PassManagerBuilder::ExtensionPointTy Ty,
94 PassManagerBuilder::ExtensionFn Fn) {
95 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
98 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
99 Extensions.push_back(std::make_pair(Ty, Fn));
102 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
103 PassManagerBase &PM) const {
104 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
105 if ((*GlobalExtensions)[i].first == ETy)
106 (*GlobalExtensions)[i].second(*this, PM);
107 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
108 if (Extensions[i].first == ETy)
109 Extensions[i].second(*this, PM);
113 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
114 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
115 // BasicAliasAnalysis wins if they disagree. This is intended to help
116 // support "obvious" type-punning idioms.
117 PM.add(createTypeBasedAliasAnalysisPass());
118 PM.add(createScopedNoAliasAAPass());
119 PM.add(createBasicAliasAnalysisPass());
122 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
123 addExtensionsToPM(EP_EarlyAsPossible, FPM);
125 // Add LibraryInfo if we have some.
126 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
128 if (OptLevel == 0) return;
130 addInitialAliasAnalysisPasses(FPM);
132 FPM.add(createCFGSimplificationPass());
134 FPM.add(createSROAPass());
136 FPM.add(createScalarReplAggregatesPass());
137 FPM.add(createEarlyCSEPass());
138 FPM.add(createLowerExpectIntrinsicPass());
141 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
142 // If all optimizations are disabled, just run the always-inline pass.
149 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
150 // pass manager, but we don't want to add extensions into that pass manager.
151 // To prevent this we must insert a no-op module pass to reset the pass
152 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
153 if (!GlobalExtensions->empty() || !Extensions.empty())
154 MPM.add(createBarrierNoopPass());
156 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
160 // Add LibraryInfo if we have some.
161 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
163 addInitialAliasAnalysisPasses(MPM);
165 if (!DisableUnitAtATime) {
166 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
168 MPM.add(createIPSCCPPass()); // IP SCCP
169 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
171 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
173 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
174 addExtensionsToPM(EP_Peephole, MPM);
175 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
178 // Start of CallGraph SCC passes.
179 if (!DisableUnitAtATime)
180 MPM.add(createPruneEHPass()); // Remove dead EH info
185 if (!DisableUnitAtATime)
186 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
188 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
190 // Start of function pass.
191 // Break up aggregate allocas, using SSAUpdater.
193 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
195 MPM.add(createScalarReplAggregatesPass(-1, false));
196 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
197 MPM.add(createJumpThreadingPass()); // Thread jumps.
198 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
199 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
200 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
201 addExtensionsToPM(EP_Peephole, MPM);
203 if (!DisableTailCalls)
204 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
205 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
206 MPM.add(createReassociatePass()); // Reassociate expressions
207 MPM.add(createLoopRotatePass()); // Rotate Loop
208 MPM.add(createLICMPass()); // Hoist loop invariants
209 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
210 MPM.add(createInstructionCombiningPass());
211 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
212 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
213 MPM.add(createLoopDeletionPass()); // Delete dead loops
215 if (!DisableUnrollLoops)
216 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
217 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
220 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
221 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
223 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
224 MPM.add(createSCCPPass()); // Constant prop with SCCP
226 // Run instcombine after redundancy elimination to exploit opportunities
227 // opened up by them.
228 MPM.add(createInstructionCombiningPass());
229 addExtensionsToPM(EP_Peephole, MPM);
230 MPM.add(createJumpThreadingPass()); // Thread jumps
231 MPM.add(createCorrelatedValuePropagationPass());
232 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
234 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
237 MPM.add(createLoopRerollPass());
238 if (!RunSLPAfterLoopVectorization) {
240 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
243 MPM.add(createBBVectorizePass());
244 MPM.add(createInstructionCombiningPass());
245 addExtensionsToPM(EP_Peephole, MPM);
246 if (OptLevel > 1 && UseGVNAfterVectorization)
247 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
249 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
251 // BBVectorize may have significantly shortened a loop body; unroll again.
252 if (!DisableUnrollLoops)
253 MPM.add(createLoopUnrollPass());
258 MPM.add(createLoadCombinePass());
260 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
261 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
262 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
263 addExtensionsToPM(EP_Peephole, MPM);
265 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
266 // pass manager that we are specifically trying to avoid. To prevent this
267 // we must insert a no-op module pass to reset the pass manager.
268 MPM.add(createBarrierNoopPass());
269 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
270 // FIXME: Because of #pragma vectorize enable, the passes below are always
271 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
272 // on -O1 and no #pragma is found). Would be good to have these two passes
273 // as function calls, so that we can only pass them when the vectorizer
275 MPM.add(createInstructionCombiningPass());
277 if (RunSLPAfterLoopVectorization) {
279 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
282 MPM.add(createBBVectorizePass());
283 MPM.add(createInstructionCombiningPass());
284 addExtensionsToPM(EP_Peephole, MPM);
285 if (OptLevel > 1 && UseGVNAfterVectorization)
286 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
288 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
290 // BBVectorize may have significantly shortened a loop body; unroll again.
291 if (!DisableUnrollLoops)
292 MPM.add(createLoopUnrollPass());
296 addExtensionsToPM(EP_Peephole, MPM);
297 MPM.add(createCFGSimplificationPass());
299 if (!DisableUnrollLoops)
300 MPM.add(createLoopUnrollPass()); // Unroll small loops
302 if (!DisableUnitAtATime) {
303 // FIXME: We shouldn't bother with this anymore.
304 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
306 // GlobalOpt already deletes dead functions and globals, at -O2 try a
307 // late pass of GlobalDCE. It is capable of deleting dead cycles.
309 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
310 MPM.add(createConstantMergePass()); // Merge dup global constants
313 addExtensionsToPM(EP_OptimizerLast, MPM);
316 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM) {
317 // Provide AliasAnalysis services for optimizations.
318 addInitialAliasAnalysisPasses(PM);
320 // Propagate constants at call sites into the functions they call. This
321 // opens opportunities for globalopt (and inlining) by substituting function
322 // pointers passed as arguments to direct uses of functions.
323 PM.add(createIPSCCPPass());
325 // Now that we internalized some globals, see if we can hack on them!
326 PM.add(createGlobalOptimizerPass());
328 // Linking modules together can lead to duplicated global constants, only
329 // keep one copy of each constant.
330 PM.add(createConstantMergePass());
332 // Remove unused arguments from functions.
333 PM.add(createDeadArgEliminationPass());
335 // Reduce the code after globalopt and ipsccp. Both can open up significant
336 // simplification opportunities, and both can propagate functions through
337 // function pointers. When this happens, we often have to resolve varargs
338 // calls, etc, so let instcombine do this.
339 PM.add(createInstructionCombiningPass());
340 addExtensionsToPM(EP_Peephole, PM);
342 // Inline small functions
343 bool RunInliner = Inliner;
349 PM.add(createPruneEHPass()); // Remove dead EH info.
351 // Optimize globals again if we ran the inliner.
353 PM.add(createGlobalOptimizerPass());
354 PM.add(createGlobalDCEPass()); // Remove dead functions.
356 // If we didn't decide to inline a function, check to see if we can
357 // transform it to pass arguments by value instead of by reference.
358 PM.add(createArgumentPromotionPass());
360 // The IPO passes may leave cruft around. Clean up after them.
361 PM.add(createInstructionCombiningPass());
362 addExtensionsToPM(EP_Peephole, PM);
363 PM.add(createJumpThreadingPass());
367 PM.add(createSROAPass());
369 PM.add(createScalarReplAggregatesPass());
371 // Run a few AA driven optimizations here and now, to cleanup the code.
372 PM.add(createFunctionAttrsPass()); // Add nocapture.
373 PM.add(createGlobalsModRefPass()); // IP alias analysis.
375 PM.add(createLICMPass()); // Hoist loop invariants.
376 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
377 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
378 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
381 PM.add(createDeadStoreEliminationPass());
383 // More loops are countable; try to optimize them.
384 PM.add(createIndVarSimplifyPass());
385 PM.add(createLoopDeletionPass());
386 PM.add(createLoopVectorizePass(true, true));
388 // More scalar chains could be vectorized due to more alias information
389 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
392 PM.add(createLoadCombinePass());
394 // Cleanup and simplify the code after the scalar optimizations.
395 PM.add(createInstructionCombiningPass());
396 addExtensionsToPM(EP_Peephole, PM);
398 PM.add(createJumpThreadingPass());
400 // Delete basic blocks, which optimization passes may have killed.
401 PM.add(createCFGSimplificationPass());
403 // Now that we have optimized the program, discard unreachable functions.
404 PM.add(createGlobalDCEPass());
407 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
408 return reinterpret_cast<PassManagerBuilder*>(P);
411 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
412 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
415 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
416 PassManagerBuilder *PMB = new PassManagerBuilder();
420 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
421 PassManagerBuilder *Builder = unwrap(PMB);
426 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
428 PassManagerBuilder *Builder = unwrap(PMB);
429 Builder->OptLevel = OptLevel;
433 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
434 unsigned SizeLevel) {
435 PassManagerBuilder *Builder = unwrap(PMB);
436 Builder->SizeLevel = SizeLevel;
440 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
442 PassManagerBuilder *Builder = unwrap(PMB);
443 Builder->DisableUnitAtATime = Value;
447 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
449 PassManagerBuilder *Builder = unwrap(PMB);
450 Builder->DisableUnrollLoops = Value;
454 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
456 // NOTE: The simplify-libcalls pass has been removed.
460 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
461 unsigned Threshold) {
462 PassManagerBuilder *Builder = unwrap(PMB);
463 Builder->Inliner = createFunctionInliningPass(Threshold);
467 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
468 LLVMPassManagerRef PM) {
469 PassManagerBuilder *Builder = unwrap(PMB);
470 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
471 Builder->populateFunctionPassManager(*FPM);
475 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
476 LLVMPassManagerRef PM) {
477 PassManagerBuilder *Builder = unwrap(PMB);
478 PassManagerBase *MPM = unwrap(PM);
479 Builder->populateModulePassManager(*MPM);
482 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
483 LLVMPassManagerRef PM,
484 LLVMBool Internalize,
485 LLVMBool RunInliner) {
486 PassManagerBuilder *Builder = unwrap(PMB);
487 PassManagerBase *LPM = unwrap(PM);
489 // A small backwards compatibility hack. populateLTOPassManager used to take
490 // an RunInliner option.
491 if (RunInliner && !Builder->Inliner)
492 Builder->Inliner = createFunctionInliningPass();
494 Builder->populateLTOPassManager(*LPM);