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;
82 PassManagerBuilder::~PassManagerBuilder() {
87 /// Set of global extensions, automatically added as part of the standard set.
88 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
89 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
91 void PassManagerBuilder::addGlobalExtension(
92 PassManagerBuilder::ExtensionPointTy Ty,
93 PassManagerBuilder::ExtensionFn Fn) {
94 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
97 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
98 Extensions.push_back(std::make_pair(Ty, Fn));
101 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
102 PassManagerBase &PM) const {
103 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
104 if ((*GlobalExtensions)[i].first == ETy)
105 (*GlobalExtensions)[i].second(*this, PM);
106 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
107 if (Extensions[i].first == ETy)
108 Extensions[i].second(*this, PM);
112 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
113 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
114 // BasicAliasAnalysis wins if they disagree. This is intended to help
115 // support "obvious" type-punning idioms.
116 PM.add(createTypeBasedAliasAnalysisPass());
117 PM.add(createScopedNoAliasAAPass());
118 PM.add(createBasicAliasAnalysisPass());
121 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
122 addExtensionsToPM(EP_EarlyAsPossible, FPM);
124 // Add LibraryInfo if we have some.
125 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
127 if (OptLevel == 0) return;
129 addInitialAliasAnalysisPasses(FPM);
131 FPM.add(createCFGSimplificationPass());
133 FPM.add(createSROAPass());
135 FPM.add(createScalarReplAggregatesPass());
136 FPM.add(createEarlyCSEPass());
137 FPM.add(createLowerExpectIntrinsicPass());
140 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
141 // If all optimizations are disabled, just run the always-inline pass.
148 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
149 // pass manager, but we don't want to add extensions into that pass manager.
150 // To prevent this we must insert a no-op module pass to reset the pass
151 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
152 if (!GlobalExtensions->empty() || !Extensions.empty())
153 MPM.add(createBarrierNoopPass());
155 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
159 // Add LibraryInfo if we have some.
160 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
162 addInitialAliasAnalysisPasses(MPM);
164 if (!DisableUnitAtATime) {
165 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
167 MPM.add(createIPSCCPPass()); // IP SCCP
168 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
170 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
172 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
173 addExtensionsToPM(EP_Peephole, MPM);
174 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
177 // Start of CallGraph SCC passes.
178 if (!DisableUnitAtATime)
179 MPM.add(createPruneEHPass()); // Remove dead EH info
184 if (!DisableUnitAtATime)
185 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
187 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
189 // Start of function pass.
190 // Break up aggregate allocas, using SSAUpdater.
192 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
194 MPM.add(createScalarReplAggregatesPass(-1, false));
195 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
196 MPM.add(createJumpThreadingPass()); // Thread jumps.
197 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
198 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
199 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
200 addExtensionsToPM(EP_Peephole, MPM);
202 if (!DisableTailCalls)
203 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
204 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
205 MPM.add(createReassociatePass()); // Reassociate expressions
206 MPM.add(createLoopRotatePass()); // Rotate Loop
207 MPM.add(createLICMPass()); // Hoist loop invariants
208 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
209 MPM.add(createInstructionCombiningPass());
210 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
211 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
212 MPM.add(createLoopDeletionPass()); // Delete dead loops
214 if (!DisableUnrollLoops)
215 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
216 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
219 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
220 MPM.add(createGVNPass()); // Remove redundancies
222 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
223 MPM.add(createSCCPPass()); // Constant prop with SCCP
225 // Run instcombine after redundancy elimination to exploit opportunities
226 // opened up by them.
227 MPM.add(createInstructionCombiningPass());
228 addExtensionsToPM(EP_Peephole, MPM);
229 MPM.add(createJumpThreadingPass()); // Thread jumps
230 MPM.add(createCorrelatedValuePropagationPass());
231 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
233 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
236 MPM.add(createLoopRerollPass());
237 if (!RunSLPAfterLoopVectorization) {
239 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
242 MPM.add(createBBVectorizePass());
243 MPM.add(createInstructionCombiningPass());
244 addExtensionsToPM(EP_Peephole, MPM);
245 if (OptLevel > 1 && UseGVNAfterVectorization)
246 MPM.add(createGVNPass()); // Remove redundancies
248 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
250 // BBVectorize may have significantly shortened a loop body; unroll again.
251 if (!DisableUnrollLoops)
252 MPM.add(createLoopUnrollPass());
257 MPM.add(createLoadCombinePass());
259 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
260 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
261 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
262 addExtensionsToPM(EP_Peephole, MPM);
264 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
265 // pass manager that we are specifically trying to avoid. To prevent this
266 // we must insert a no-op module pass to reset the pass manager.
267 MPM.add(createBarrierNoopPass());
268 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
269 // FIXME: Because of #pragma vectorize enable, the passes below are always
270 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
271 // on -O1 and no #pragma is found). Would be good to have these two passes
272 // as function calls, so that we can only pass them when the vectorizer
274 MPM.add(createInstructionCombiningPass());
276 if (RunSLPAfterLoopVectorization) {
278 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
281 MPM.add(createBBVectorizePass());
282 MPM.add(createInstructionCombiningPass());
283 addExtensionsToPM(EP_Peephole, MPM);
284 if (OptLevel > 1 && UseGVNAfterVectorization)
285 MPM.add(createGVNPass()); // Remove redundancies
287 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
289 // BBVectorize may have significantly shortened a loop body; unroll again.
290 if (!DisableUnrollLoops)
291 MPM.add(createLoopUnrollPass());
295 addExtensionsToPM(EP_Peephole, MPM);
296 MPM.add(createCFGSimplificationPass());
298 if (!DisableUnrollLoops)
299 MPM.add(createLoopUnrollPass()); // Unroll small loops
301 if (!DisableUnitAtATime) {
302 // FIXME: We shouldn't bother with this anymore.
303 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
305 // GlobalOpt already deletes dead functions and globals, at -O2 try a
306 // late pass of GlobalDCE. It is capable of deleting dead cycles.
308 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
309 MPM.add(createConstantMergePass()); // Merge dup global constants
312 addExtensionsToPM(EP_OptimizerLast, MPM);
315 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
317 bool DisableGVNLoadPRE) {
318 // Provide AliasAnalysis services for optimizations.
319 addInitialAliasAnalysisPasses(PM);
321 // Propagate constants at call sites into the functions they call. This
322 // opens opportunities for globalopt (and inlining) by substituting function
323 // pointers passed as arguments to direct uses of functions.
324 PM.add(createIPSCCPPass());
326 // Now that we internalized some globals, see if we can hack on them!
327 PM.add(createGlobalOptimizerPass());
329 // Linking modules together can lead to duplicated global constants, only
330 // keep one copy of each constant.
331 PM.add(createConstantMergePass());
333 // Remove unused arguments from functions.
334 PM.add(createDeadArgEliminationPass());
336 // Reduce the code after globalopt and ipsccp. Both can open up significant
337 // simplification opportunities, and both can propagate functions through
338 // function pointers. When this happens, we often have to resolve varargs
339 // calls, etc, so let instcombine do this.
340 PM.add(createInstructionCombiningPass());
341 addExtensionsToPM(EP_Peephole, PM);
343 // Inline small functions
345 PM.add(createFunctionInliningPass());
347 PM.add(createPruneEHPass()); // Remove dead EH info.
349 // Optimize globals again if we ran the inliner.
351 PM.add(createGlobalOptimizerPass());
352 PM.add(createGlobalDCEPass()); // Remove dead functions.
354 // If we didn't decide to inline a function, check to see if we can
355 // transform it to pass arguments by value instead of by reference.
356 PM.add(createArgumentPromotionPass());
358 // The IPO passes may leave cruft around. Clean up after them.
359 PM.add(createInstructionCombiningPass());
360 addExtensionsToPM(EP_Peephole, PM);
361 PM.add(createJumpThreadingPass());
365 PM.add(createSROAPass());
367 PM.add(createScalarReplAggregatesPass());
369 // Run a few AA driven optimizations here and now, to cleanup the code.
370 PM.add(createFunctionAttrsPass()); // Add nocapture.
371 PM.add(createGlobalsModRefPass()); // IP alias analysis.
373 PM.add(createLICMPass()); // Hoist loop invariants.
374 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
375 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
376 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
379 PM.add(createDeadStoreEliminationPass());
381 // More loops are countable; try to optimize them.
382 PM.add(createIndVarSimplifyPass());
383 PM.add(createLoopDeletionPass());
384 PM.add(createLoopVectorizePass(true, true));
386 // More scalar chains could be vectorized due to more alias information
387 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
390 PM.add(createLoadCombinePass());
392 // Cleanup and simplify the code after the scalar optimizations.
393 PM.add(createInstructionCombiningPass());
394 addExtensionsToPM(EP_Peephole, PM);
396 PM.add(createJumpThreadingPass());
398 // Delete basic blocks, which optimization passes may have killed.
399 PM.add(createCFGSimplificationPass());
401 // Now that we have optimized the program, discard unreachable functions.
402 PM.add(createGlobalDCEPass());
405 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
406 return reinterpret_cast<PassManagerBuilder*>(P);
409 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
410 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
413 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
414 PassManagerBuilder *PMB = new PassManagerBuilder();
418 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
419 PassManagerBuilder *Builder = unwrap(PMB);
424 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
426 PassManagerBuilder *Builder = unwrap(PMB);
427 Builder->OptLevel = OptLevel;
431 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
432 unsigned SizeLevel) {
433 PassManagerBuilder *Builder = unwrap(PMB);
434 Builder->SizeLevel = SizeLevel;
438 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
440 PassManagerBuilder *Builder = unwrap(PMB);
441 Builder->DisableUnitAtATime = Value;
445 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
447 PassManagerBuilder *Builder = unwrap(PMB);
448 Builder->DisableUnrollLoops = Value;
452 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
454 // NOTE: The simplify-libcalls pass has been removed.
458 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
459 unsigned Threshold) {
460 PassManagerBuilder *Builder = unwrap(PMB);
461 Builder->Inliner = createFunctionInliningPass(Threshold);
465 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
466 LLVMPassManagerRef PM) {
467 PassManagerBuilder *Builder = unwrap(PMB);
468 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
469 Builder->populateFunctionPassManager(*FPM);
473 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
474 LLVMPassManagerRef PM) {
475 PassManagerBuilder *Builder = unwrap(PMB);
476 PassManagerBase *MPM = unwrap(PM);
477 Builder->populateModulePassManager(*MPM);
480 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
481 LLVMPassManagerRef PM,
482 LLVMBool Internalize,
483 LLVMBool RunInliner) {
484 PassManagerBuilder *Builder = unwrap(PMB);
485 PassManagerBase *LPM = unwrap(PM);
486 Builder->populateLTOPassManager(*LPM, RunInliner != 0, false);