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 static cl::opt<bool> RunGVN("enable-gvn", cl::init(true),
62 cl::desc("Run the global value numbering pass"));
64 PassManagerBuilder::PassManagerBuilder() {
67 LibraryInfo = nullptr;
69 DisableTailCalls = false;
70 DisableUnitAtATime = false;
71 DisableUnrollLoops = false;
72 BBVectorize = RunBBVectorization;
73 SLPVectorize = RunSLPVectorization;
74 LoopVectorize = RunLoopVectorization;
75 RerollLoops = RunLoopRerolling;
76 LoadCombine = RunLoadCombine;
79 PassManagerBuilder::~PassManagerBuilder() {
84 /// Set of global extensions, automatically added as part of the standard set.
85 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
86 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
88 void PassManagerBuilder::addGlobalExtension(
89 PassManagerBuilder::ExtensionPointTy Ty,
90 PassManagerBuilder::ExtensionFn Fn) {
91 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
94 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
95 Extensions.push_back(std::make_pair(Ty, Fn));
98 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
99 PassManagerBase &PM) const {
100 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
101 if ((*GlobalExtensions)[i].first == ETy)
102 (*GlobalExtensions)[i].second(*this, PM);
103 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
104 if (Extensions[i].first == ETy)
105 Extensions[i].second(*this, PM);
109 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
110 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
111 // BasicAliasAnalysis wins if they disagree. This is intended to help
112 // support "obvious" type-punning idioms.
113 PM.add(createTypeBasedAliasAnalysisPass());
114 PM.add(createBasicAliasAnalysisPass());
117 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
118 addExtensionsToPM(EP_EarlyAsPossible, FPM);
120 // Add LibraryInfo if we have some.
121 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
123 if (OptLevel == 0) return;
125 addInitialAliasAnalysisPasses(FPM);
127 FPM.add(createCFGSimplificationPass());
129 FPM.add(createSROAPass());
131 FPM.add(createScalarReplAggregatesPass());
132 FPM.add(createEarlyCSEPass());
133 FPM.add(createLowerExpectIntrinsicPass());
136 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
137 // If all optimizations are disabled, just run the always-inline pass.
144 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
145 // pass manager, but we don't want to add extensions into that pass manager.
146 // To prevent this we must insert a no-op module pass to reset the pass
147 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
148 if (!GlobalExtensions->empty() || !Extensions.empty())
149 MPM.add(createBarrierNoopPass());
151 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
155 // Add LibraryInfo if we have some.
156 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
158 addInitialAliasAnalysisPasses(MPM);
160 if (!DisableUnitAtATime) {
161 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
163 MPM.add(createIPSCCPPass()); // IP SCCP
164 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
166 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
168 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
169 addExtensionsToPM(EP_Peephole, MPM);
170 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
173 // Start of CallGraph SCC passes.
174 if (!DisableUnitAtATime)
175 MPM.add(createPruneEHPass()); // Remove dead EH info
180 if (!DisableUnitAtATime)
181 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
183 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
185 // Start of function pass.
186 // Break up aggregate allocas, using SSAUpdater.
188 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
190 MPM.add(createScalarReplAggregatesPass(-1, false));
191 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
192 MPM.add(createJumpThreadingPass()); // Thread jumps.
193 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
194 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
195 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
196 addExtensionsToPM(EP_Peephole, MPM);
198 if (!DisableTailCalls)
199 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
200 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
201 MPM.add(createReassociatePass()); // Reassociate expressions
202 // Rotate Loop - disable header duplication at -Oz
203 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
204 MPM.add(createLICMPass()); // Hoist loop invariants
205 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
206 MPM.add(createInstructionCombiningPass());
207 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
208 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
209 MPM.add(createLoopDeletionPass()); // Delete dead loops
211 if (!DisableUnrollLoops)
212 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
213 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
216 MPM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamond
218 MPM.add(createGVNPass()); // Remove redundancies
220 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
221 MPM.add(createSCCPPass()); // Constant prop with SCCP
223 // Run instcombine after redundancy elimination to exploit opportunities
224 // opened up by them.
225 MPM.add(createInstructionCombiningPass());
226 addExtensionsToPM(EP_Peephole, MPM);
227 MPM.add(createJumpThreadingPass()); // Thread jumps
228 MPM.add(createCorrelatedValuePropagationPass());
229 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
231 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
234 MPM.add(createLoopRerollPass());
236 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
239 MPM.add(createBBVectorizePass());
240 MPM.add(createInstructionCombiningPass());
241 addExtensionsToPM(EP_Peephole, MPM);
242 if (OptLevel > 1 && UseGVNAfterVectorization)
243 MPM.add(createGVNPass()); // Remove redundancies
245 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
247 // BBVectorize may have significantly shortened a loop body; unroll again.
248 if (!DisableUnrollLoops)
249 MPM.add(createLoopUnrollPass());
253 MPM.add(createLoadCombinePass());
255 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
256 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
257 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
258 addExtensionsToPM(EP_Peephole, MPM);
260 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
261 // pass manager that we are specifically trying to avoid. To prevent this
262 // we must insert a no-op module pass to reset the pass manager.
263 MPM.add(createBarrierNoopPass());
264 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
265 // FIXME: Because of #pragma vectorize enable, the passes below are always
266 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
267 // on -O1 and no #pragma is found). Would be good to have these two passes
268 // as function calls, so that we can only pass them when the vectorizer
270 MPM.add(createInstructionCombiningPass());
271 addExtensionsToPM(EP_Peephole, MPM);
272 MPM.add(createCFGSimplificationPass());
274 if (!DisableUnrollLoops)
275 MPM.add(createLoopUnrollPass()); // Unroll small loops
277 if (!DisableUnitAtATime) {
278 // FIXME: We shouldn't bother with this anymore.
279 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
281 // GlobalOpt already deletes dead functions and globals, at -O2 try a
282 // late pass of GlobalDCE. It is capable of deleting dead cycles.
284 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
285 MPM.add(createConstantMergePass()); // Merge dup global constants
288 addExtensionsToPM(EP_OptimizerLast, MPM);
291 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
294 bool DisableGVNLoadPRE) {
295 // Provide AliasAnalysis services for optimizations.
296 addInitialAliasAnalysisPasses(PM);
298 // Now that composite has been compiled, scan through the module, looking
299 // for a main function. If main is defined, mark all other functions
302 PM.add(createInternalizePass("main"));
304 // Propagate constants at call sites into the functions they call. This
305 // opens opportunities for globalopt (and inlining) by substituting function
306 // pointers passed as arguments to direct uses of functions.
307 PM.add(createIPSCCPPass());
309 // Now that we internalized some globals, see if we can hack on them!
310 PM.add(createGlobalOptimizerPass());
312 // Linking modules together can lead to duplicated global constants, only
313 // keep one copy of each constant.
314 PM.add(createConstantMergePass());
316 // Remove unused arguments from functions.
317 PM.add(createDeadArgEliminationPass());
319 // Reduce the code after globalopt and ipsccp. Both can open up significant
320 // simplification opportunities, and both can propagate functions through
321 // function pointers. When this happens, we often have to resolve varargs
322 // calls, etc, so let instcombine do this.
323 PM.add(createInstructionCombiningPass());
324 addExtensionsToPM(EP_Peephole, PM);
326 // Inline small functions
328 PM.add(createFunctionInliningPass());
330 PM.add(createPruneEHPass()); // Remove dead EH info.
332 // Optimize globals again if we ran the inliner.
334 PM.add(createGlobalOptimizerPass());
335 PM.add(createGlobalDCEPass()); // Remove dead functions.
337 // If we didn't decide to inline a function, check to see if we can
338 // transform it to pass arguments by value instead of by reference.
339 PM.add(createArgumentPromotionPass());
341 // The IPO passes may leave cruft around. Clean up after them.
342 PM.add(createInstructionCombiningPass());
343 addExtensionsToPM(EP_Peephole, PM);
344 PM.add(createJumpThreadingPass());
348 PM.add(createSROAPass());
350 PM.add(createScalarReplAggregatesPass());
352 // Run a few AA driven optimizations here and now, to cleanup the code.
353 PM.add(createFunctionAttrsPass()); // Add nocapture.
354 PM.add(createGlobalsModRefPass()); // IP alias analysis.
356 PM.add(createLICMPass()); // Hoist loop invariants.
357 PM.add(createMergedLoadStoreMotionPass()); // Merge load/stores in diamonds
358 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
359 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
362 PM.add(createDeadStoreEliminationPass());
364 // More loops are countable; try to optimize them.
365 PM.add(createIndVarSimplifyPass());
366 PM.add(createLoopDeletionPass());
367 PM.add(createLoopVectorizePass(true, true));
369 // More scalar chains could be vectorized due to more alias information
370 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
373 PM.add(createLoadCombinePass());
375 // Cleanup and simplify the code after the scalar optimizations.
376 PM.add(createInstructionCombiningPass());
377 addExtensionsToPM(EP_Peephole, PM);
379 PM.add(createJumpThreadingPass());
381 // Delete basic blocks, which optimization passes may have killed.
382 PM.add(createCFGSimplificationPass());
384 // Now that we have optimized the program, discard unreachable functions.
385 PM.add(createGlobalDCEPass());
388 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
389 return reinterpret_cast<PassManagerBuilder*>(P);
392 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
393 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
396 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
397 PassManagerBuilder *PMB = new PassManagerBuilder();
401 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
402 PassManagerBuilder *Builder = unwrap(PMB);
407 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
409 PassManagerBuilder *Builder = unwrap(PMB);
410 Builder->OptLevel = OptLevel;
414 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
415 unsigned SizeLevel) {
416 PassManagerBuilder *Builder = unwrap(PMB);
417 Builder->SizeLevel = SizeLevel;
421 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
423 PassManagerBuilder *Builder = unwrap(PMB);
424 Builder->DisableUnitAtATime = Value;
428 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
430 PassManagerBuilder *Builder = unwrap(PMB);
431 Builder->DisableUnrollLoops = Value;
435 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
437 // NOTE: The simplify-libcalls pass has been removed.
441 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
442 unsigned Threshold) {
443 PassManagerBuilder *Builder = unwrap(PMB);
444 Builder->Inliner = createFunctionInliningPass(Threshold);
448 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
449 LLVMPassManagerRef PM) {
450 PassManagerBuilder *Builder = unwrap(PMB);
451 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
452 Builder->populateFunctionPassManager(*FPM);
456 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
457 LLVMPassManagerRef PM) {
458 PassManagerBuilder *Builder = unwrap(PMB);
459 PassManagerBase *MPM = unwrap(PM);
460 Builder->populateModulePassManager(*MPM);
463 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
464 LLVMPassManagerRef PM,
465 LLVMBool Internalize,
466 LLVMBool RunInliner) {
467 PassManagerBuilder *Builder = unwrap(PMB);
468 PassManagerBase *LPM = unwrap(PM);
469 Builder->populateLTOPassManager(*LPM, Internalize != 0, RunInliner != 0);