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/DataLayout.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Target/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetSubtargetInfo.h"
28 #include "llvm/Transforms/IPO.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Vectorize.h"
35 RunLoopVectorization("vectorize-loops", cl::Hidden,
36 cl::desc("Run the Loop vectorization passes"));
39 RunSLPVectorization("vectorize-slp", cl::Hidden,
40 cl::desc("Run the SLP vectorization passes"));
43 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
44 cl::desc("Run the BB vectorization passes"));
47 UseGVNAfterVectorization("use-gvn-after-vectorization",
48 cl::init(false), cl::Hidden,
49 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
51 static cl::opt<bool> UseNewSROA("use-new-sroa",
52 cl::init(true), cl::Hidden,
53 cl::desc("Enable the new, experimental SROA pass"));
56 RunLoopRerolling("reroll-loops", cl::Hidden,
57 cl::desc("Run the loop rerolling pass"));
59 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
61 cl::desc("Run the load combining pass"));
64 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
65 cl::init(false), cl::Hidden,
66 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
67 "vectorizer instead of before"));
70 PassManagerBuilder::PassManagerBuilder() {
73 LibraryInfo = nullptr;
75 DisableTailCalls = false;
76 DisableUnitAtATime = false;
77 DisableUnrollLoops = false;
78 BBVectorize = RunBBVectorization;
79 SLPVectorize = RunSLPVectorization;
80 LoopVectorize = RunLoopVectorization;
81 RerollLoops = RunLoopRerolling;
82 LoadCombine = RunLoadCombine;
83 DisableGVNLoadPRE = false;
89 PassManagerBuilder::~PassManagerBuilder() {
94 /// Set of global extensions, automatically added as part of the standard set.
95 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
96 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
98 void PassManagerBuilder::addGlobalExtension(
99 PassManagerBuilder::ExtensionPointTy Ty,
100 PassManagerBuilder::ExtensionFn Fn) {
101 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
104 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
105 Extensions.push_back(std::make_pair(Ty, Fn));
108 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
109 PassManagerBase &PM) const {
110 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
111 if ((*GlobalExtensions)[i].first == ETy)
112 (*GlobalExtensions)[i].second(*this, PM);
113 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
114 if (Extensions[i].first == ETy)
115 Extensions[i].second(*this, PM);
119 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
120 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
121 // BasicAliasAnalysis wins if they disagree. This is intended to help
122 // support "obvious" type-punning idioms.
123 PM.add(createTypeBasedAliasAnalysisPass());
124 PM.add(createScopedNoAliasAAPass());
125 PM.add(createBasicAliasAnalysisPass());
128 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
129 addExtensionsToPM(EP_EarlyAsPossible, FPM);
131 // Add LibraryInfo if we have some.
132 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
134 if (OptLevel == 0) return;
136 addInitialAliasAnalysisPasses(FPM);
138 FPM.add(createCFGSimplificationPass());
140 FPM.add(createSROAPass());
142 FPM.add(createScalarReplAggregatesPass());
143 FPM.add(createEarlyCSEPass());
144 FPM.add(createLowerExpectIntrinsicPass());
147 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
148 // If all optimizations are disabled, just run the always-inline pass.
155 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
156 // pass manager, but we don't want to add extensions into that pass manager.
157 // To prevent this we must insert a no-op module pass to reset the pass
158 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
159 if (!GlobalExtensions->empty() || !Extensions.empty())
160 MPM.add(createBarrierNoopPass());
162 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
166 // Add LibraryInfo if we have some.
167 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
169 addInitialAliasAnalysisPasses(MPM);
171 if (!DisableUnitAtATime) {
172 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
174 MPM.add(createIPSCCPPass()); // IP SCCP
175 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
177 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
179 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
180 addExtensionsToPM(EP_Peephole, MPM);
181 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
184 // Start of CallGraph SCC passes.
185 if (!DisableUnitAtATime)
186 MPM.add(createPruneEHPass()); // Remove dead EH info
191 if (!DisableUnitAtATime)
192 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
194 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
196 // Start of function pass.
197 // Break up aggregate allocas, using SSAUpdater.
199 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
201 MPM.add(createScalarReplAggregatesPass(-1, false));
202 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
203 MPM.add(createJumpThreadingPass()); // Thread jumps.
204 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
205 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
206 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
207 addExtensionsToPM(EP_Peephole, MPM);
209 if (!DisableTailCalls)
210 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
211 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
212 MPM.add(createReassociatePass()); // Reassociate expressions
213 MPM.add(createLoopRotatePass()); // Rotate Loop
214 MPM.add(createLICMPass()); // Hoist loop invariants
215 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
216 MPM.add(createInstructionCombiningPass());
217 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
218 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
219 MPM.add(createLoopDeletionPass()); // Delete dead loops
221 if (!DisableUnrollLoops)
222 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
223 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
226 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
227 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
229 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
230 MPM.add(createSCCPPass()); // Constant prop with SCCP
232 // Run instcombine after redundancy elimination to exploit opportunities
233 // opened up by them.
234 MPM.add(createInstructionCombiningPass());
235 addExtensionsToPM(EP_Peephole, MPM);
236 MPM.add(createJumpThreadingPass()); // Thread jumps
237 MPM.add(createCorrelatedValuePropagationPass());
238 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
240 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
243 MPM.add(createLoopRerollPass());
244 if (!RunSLPAfterLoopVectorization) {
246 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
249 MPM.add(createBBVectorizePass());
250 MPM.add(createInstructionCombiningPass());
251 addExtensionsToPM(EP_Peephole, MPM);
252 if (OptLevel > 1 && UseGVNAfterVectorization)
253 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
255 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
257 // BBVectorize may have significantly shortened a loop body; unroll again.
258 if (!DisableUnrollLoops)
259 MPM.add(createLoopUnrollPass());
264 MPM.add(createLoadCombinePass());
266 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
267 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
268 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
269 addExtensionsToPM(EP_Peephole, MPM);
271 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
272 // pass manager that we are specifically trying to avoid. To prevent this
273 // we must insert a no-op module pass to reset the pass manager.
274 MPM.add(createBarrierNoopPass());
275 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
276 // FIXME: Because of #pragma vectorize enable, the passes below are always
277 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
278 // on -O1 and no #pragma is found). Would be good to have these two passes
279 // as function calls, so that we can only pass them when the vectorizer
281 MPM.add(createInstructionCombiningPass());
283 if (RunSLPAfterLoopVectorization) {
285 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
288 MPM.add(createBBVectorizePass());
289 MPM.add(createInstructionCombiningPass());
290 addExtensionsToPM(EP_Peephole, MPM);
291 if (OptLevel > 1 && UseGVNAfterVectorization)
292 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
294 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
296 // BBVectorize may have significantly shortened a loop body; unroll again.
297 if (!DisableUnrollLoops)
298 MPM.add(createLoopUnrollPass());
302 addExtensionsToPM(EP_Peephole, MPM);
303 MPM.add(createCFGSimplificationPass());
305 if (!DisableUnrollLoops)
306 MPM.add(createLoopUnrollPass()); // Unroll small loops
308 if (!DisableUnitAtATime) {
309 // FIXME: We shouldn't bother with this anymore.
310 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
312 // GlobalOpt already deletes dead functions and globals, at -O2 try a
313 // late pass of GlobalDCE. It is capable of deleting dead cycles.
315 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
316 MPM.add(createConstantMergePass()); // Merge dup global constants
319 addExtensionsToPM(EP_OptimizerLast, MPM);
322 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
323 // Provide AliasAnalysis services for optimizations.
324 addInitialAliasAnalysisPasses(PM);
326 // Propagate constants at call sites into the functions they call. This
327 // opens opportunities for globalopt (and inlining) by substituting function
328 // pointers passed as arguments to direct uses of functions.
329 PM.add(createIPSCCPPass());
331 // Now that we internalized some globals, see if we can hack on them!
332 PM.add(createGlobalOptimizerPass());
334 // Linking modules together can lead to duplicated global constants, only
335 // keep one copy of each constant.
336 PM.add(createConstantMergePass());
338 // Remove unused arguments from functions.
339 PM.add(createDeadArgEliminationPass());
341 // Reduce the code after globalopt and ipsccp. Both can open up significant
342 // simplification opportunities, and both can propagate functions through
343 // function pointers. When this happens, we often have to resolve varargs
344 // calls, etc, so let instcombine do this.
345 PM.add(createInstructionCombiningPass());
346 addExtensionsToPM(EP_Peephole, PM);
348 // Inline small functions
349 bool RunInliner = Inliner;
355 PM.add(createPruneEHPass()); // Remove dead EH info.
357 // Optimize globals again if we ran the inliner.
359 PM.add(createGlobalOptimizerPass());
360 PM.add(createGlobalDCEPass()); // Remove dead functions.
362 // If we didn't decide to inline a function, check to see if we can
363 // transform it to pass arguments by value instead of by reference.
364 PM.add(createArgumentPromotionPass());
366 // The IPO passes may leave cruft around. Clean up after them.
367 PM.add(createInstructionCombiningPass());
368 addExtensionsToPM(EP_Peephole, PM);
369 PM.add(createJumpThreadingPass());
373 PM.add(createSROAPass());
375 PM.add(createScalarReplAggregatesPass());
377 // Run a few AA driven optimizations here and now, to cleanup the code.
378 PM.add(createFunctionAttrsPass()); // Add nocapture.
379 PM.add(createGlobalsModRefPass()); // IP alias analysis.
381 PM.add(createLICMPass()); // Hoist loop invariants.
382 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
383 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
384 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
387 PM.add(createDeadStoreEliminationPass());
389 // More loops are countable; try to optimize them.
390 PM.add(createIndVarSimplifyPass());
391 PM.add(createLoopDeletionPass());
392 PM.add(createLoopVectorizePass(true, true));
394 // More scalar chains could be vectorized due to more alias information
395 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
398 PM.add(createLoadCombinePass());
400 // Cleanup and simplify the code after the scalar optimizations.
401 PM.add(createInstructionCombiningPass());
402 addExtensionsToPM(EP_Peephole, PM);
404 PM.add(createJumpThreadingPass());
406 // Delete basic blocks, which optimization passes may have killed.
407 PM.add(createCFGSimplificationPass());
409 // Now that we have optimized the program, discard unreachable functions.
410 PM.add(createGlobalDCEPass());
413 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
416 const DataLayout *DL = TM->getSubtargetImpl()->getDataLayout();
417 PM.add(new DataLayoutPass(*DL));
418 TM->addAnalysisPasses(PM);
422 PM.add(new TargetLibraryInfo(*LibraryInfo));
425 PM.add(createVerifierPass());
428 PM.add(createStripSymbolsPass(true));
431 PM.add(createDebugInfoVerifierPass());
434 addLTOOptimizationPasses(PM);
437 PM.add(createVerifierPass());
438 PM.add(createDebugInfoVerifierPass());
442 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
443 return reinterpret_cast<PassManagerBuilder*>(P);
446 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
447 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
450 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
451 PassManagerBuilder *PMB = new PassManagerBuilder();
455 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
456 PassManagerBuilder *Builder = unwrap(PMB);
461 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
463 PassManagerBuilder *Builder = unwrap(PMB);
464 Builder->OptLevel = OptLevel;
468 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
469 unsigned SizeLevel) {
470 PassManagerBuilder *Builder = unwrap(PMB);
471 Builder->SizeLevel = SizeLevel;
475 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
477 PassManagerBuilder *Builder = unwrap(PMB);
478 Builder->DisableUnitAtATime = Value;
482 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
484 PassManagerBuilder *Builder = unwrap(PMB);
485 Builder->DisableUnrollLoops = Value;
489 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
491 // NOTE: The simplify-libcalls pass has been removed.
495 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
496 unsigned Threshold) {
497 PassManagerBuilder *Builder = unwrap(PMB);
498 Builder->Inliner = createFunctionInliningPass(Threshold);
502 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
503 LLVMPassManagerRef PM) {
504 PassManagerBuilder *Builder = unwrap(PMB);
505 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
506 Builder->populateFunctionPassManager(*FPM);
510 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
511 LLVMPassManagerRef PM) {
512 PassManagerBuilder *Builder = unwrap(PMB);
513 PassManagerBase *MPM = unwrap(PM);
514 Builder->populateModulePassManager(*MPM);
517 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
518 LLVMPassManagerRef PM,
519 LLVMBool Internalize,
520 LLVMBool RunInliner) {
521 PassManagerBuilder *Builder = unwrap(PMB);
522 PassManagerBase *LPM = unwrap(PM);
524 // A small backwards compatibility hack. populateLTOPassManager used to take
525 // an RunInliner option.
526 if (RunInliner && !Builder->Inliner)
527 Builder->Inliner = createFunctionInliningPass();
529 Builder->populateLTOPassManager(*LPM);