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 PassManagerBuilder::PassManagerBuilder() {
61 DisableUnitAtATime = false;
62 DisableUnrollLoops = false;
63 BBVectorize = RunBBVectorization;
64 SLPVectorize = RunSLPVectorization;
65 LoopVectorize = RunLoopVectorization;
66 RerollLoops = RunLoopRerolling;
69 PassManagerBuilder::~PassManagerBuilder() {
74 /// Set of global extensions, automatically added as part of the standard set.
75 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
76 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
78 void PassManagerBuilder::addGlobalExtension(
79 PassManagerBuilder::ExtensionPointTy Ty,
80 PassManagerBuilder::ExtensionFn Fn) {
81 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
84 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
85 Extensions.push_back(std::make_pair(Ty, Fn));
88 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
89 PassManagerBase &PM) const {
90 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
91 if ((*GlobalExtensions)[i].first == ETy)
92 (*GlobalExtensions)[i].second(*this, PM);
93 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
94 if (Extensions[i].first == ETy)
95 Extensions[i].second(*this, PM);
99 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
100 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
101 // BasicAliasAnalysis wins if they disagree. This is intended to help
102 // support "obvious" type-punning idioms.
103 PM.add(createTypeBasedAliasAnalysisPass());
104 PM.add(createBasicAliasAnalysisPass());
107 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
108 addExtensionsToPM(EP_EarlyAsPossible, FPM);
110 // Add LibraryInfo if we have some.
111 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
113 if (OptLevel == 0) return;
115 addInitialAliasAnalysisPasses(FPM);
117 FPM.add(createCFGSimplificationPass());
119 FPM.add(createSROAPass());
121 FPM.add(createScalarReplAggregatesPass());
122 FPM.add(createEarlyCSEPass());
123 FPM.add(createLowerExpectIntrinsicPass());
126 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
127 // If all optimizations are disabled, just run the always-inline pass.
134 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
135 // pass manager, but we don't want to add extensions into that pass manager.
136 // To prevent this we must insert a no-op module pass to reset the pass
137 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
138 if (!GlobalExtensions->empty() || !Extensions.empty())
139 MPM.add(createBarrierNoopPass());
141 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
145 // Add LibraryInfo if we have some.
146 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
148 addInitialAliasAnalysisPasses(MPM);
150 if (!DisableUnitAtATime) {
151 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
153 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
155 MPM.add(createIPSCCPPass()); // IP SCCP
156 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
158 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
159 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
162 // Start of CallGraph SCC passes.
163 if (!DisableUnitAtATime)
164 MPM.add(createPruneEHPass()); // Remove dead EH info
169 if (!DisableUnitAtATime)
170 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
172 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
174 // Start of function pass.
175 // Break up aggregate allocas, using SSAUpdater.
177 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
179 MPM.add(createScalarReplAggregatesPass(-1, false));
180 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
181 MPM.add(createJumpThreadingPass()); // Thread jumps.
182 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
183 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
184 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
186 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
187 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
188 MPM.add(createReassociatePass()); // Reassociate expressions
189 MPM.add(createLoopRotatePass()); // Rotate Loop
190 MPM.add(createLICMPass()); // Hoist loop invariants
191 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
192 MPM.add(createInstructionCombiningPass());
193 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
194 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
195 MPM.add(createLoopDeletionPass()); // Delete dead loops
197 if (!DisableUnrollLoops)
198 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
199 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
202 MPM.add(createGVNPass()); // Remove redundancies
203 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
204 MPM.add(createSCCPPass()); // Constant prop with SCCP
206 // Run instcombine after redundancy elimination to exploit opportunities
207 // opened up by them.
208 MPM.add(createInstructionCombiningPass());
209 MPM.add(createJumpThreadingPass()); // Thread jumps
210 MPM.add(createCorrelatedValuePropagationPass());
211 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
213 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
216 MPM.add(createLoopRerollPass());
218 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
221 MPM.add(createBBVectorizePass());
222 MPM.add(createInstructionCombiningPass());
223 if (OptLevel > 1 && UseGVNAfterVectorization)
224 MPM.add(createGVNPass()); // Remove redundancies
226 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
228 // BBVectorize may have significantly shortened a loop body; unroll again.
229 if (!DisableUnrollLoops)
230 MPM.add(createLoopUnrollPass());
233 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
234 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
235 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
237 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
238 // pass manager that we are specifically trying to avoid. To prevent this
239 // we must insert a no-op module pass to reset the pass manager.
240 MPM.add(createBarrierNoopPass());
241 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
242 // FIXME: Because of #pragma vectorize enable, the passes below are always
243 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
244 // on -O1 and no #pragma is found). Would be good to have these two passes
245 // as function calls, so that we can only pass them when the vectorizer
247 MPM.add(createInstructionCombiningPass());
248 MPM.add(createCFGSimplificationPass());
250 if (!DisableUnrollLoops)
251 MPM.add(createLoopUnrollPass()); // Unroll small loops
253 if (!DisableUnitAtATime) {
254 // FIXME: We shouldn't bother with this anymore.
255 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
257 // GlobalOpt already deletes dead functions and globals, at -O2 try a
258 // late pass of GlobalDCE. It is capable of deleting dead cycles.
260 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
261 MPM.add(createConstantMergePass()); // Merge dup global constants
264 addExtensionsToPM(EP_OptimizerLast, MPM);
267 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
270 bool DisableGVNLoadPRE) {
271 // Provide AliasAnalysis services for optimizations.
272 addInitialAliasAnalysisPasses(PM);
274 // Now that composite has been compiled, scan through the module, looking
275 // for a main function. If main is defined, mark all other functions
278 PM.add(createInternalizePass("main"));
280 // Propagate constants at call sites into the functions they call. This
281 // opens opportunities for globalopt (and inlining) by substituting function
282 // pointers passed as arguments to direct uses of functions.
283 PM.add(createIPSCCPPass());
285 // Now that we internalized some globals, see if we can hack on them!
286 PM.add(createGlobalOptimizerPass());
288 // Linking modules together can lead to duplicated global constants, only
289 // keep one copy of each constant.
290 PM.add(createConstantMergePass());
292 // Remove unused arguments from functions.
293 PM.add(createDeadArgEliminationPass());
295 // Reduce the code after globalopt and ipsccp. Both can open up significant
296 // simplification opportunities, and both can propagate functions through
297 // function pointers. When this happens, we often have to resolve varargs
298 // calls, etc, so let instcombine do this.
299 PM.add(createInstructionCombiningPass());
301 // Inline small functions
303 PM.add(createFunctionInliningPass());
305 PM.add(createPruneEHPass()); // Remove dead EH info.
307 // Optimize globals again if we ran the inliner.
309 PM.add(createGlobalOptimizerPass());
310 PM.add(createGlobalDCEPass()); // Remove dead functions.
312 // If we didn't decide to inline a function, check to see if we can
313 // transform it to pass arguments by value instead of by reference.
314 PM.add(createArgumentPromotionPass());
316 // The IPO passes may leave cruft around. Clean up after them.
317 PM.add(createInstructionCombiningPass());
318 PM.add(createJumpThreadingPass());
322 PM.add(createSROAPass());
324 PM.add(createScalarReplAggregatesPass());
326 // Run a few AA driven optimizations here and now, to cleanup the code.
327 PM.add(createFunctionAttrsPass()); // Add nocapture.
328 PM.add(createGlobalsModRefPass()); // IP alias analysis.
330 PM.add(createLICMPass()); // Hoist loop invariants.
331 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
332 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
335 PM.add(createDeadStoreEliminationPass());
337 // More loops are countable; try to optimize them.
338 PM.add(createIndVarSimplifyPass());
339 PM.add(createLoopDeletionPass());
340 PM.add(createLoopVectorizePass(true, true));
342 // Cleanup and simplify the code after the scalar optimizations.
343 PM.add(createInstructionCombiningPass());
345 PM.add(createJumpThreadingPass());
347 // Delete basic blocks, which optimization passes may have killed.
348 PM.add(createCFGSimplificationPass());
350 // Now that we have optimized the program, discard unreachable functions.
351 PM.add(createGlobalDCEPass());
354 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
355 return reinterpret_cast<PassManagerBuilder*>(P);
358 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
359 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
362 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
363 PassManagerBuilder *PMB = new PassManagerBuilder();
367 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
368 PassManagerBuilder *Builder = unwrap(PMB);
373 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
375 PassManagerBuilder *Builder = unwrap(PMB);
376 Builder->OptLevel = OptLevel;
380 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
381 unsigned SizeLevel) {
382 PassManagerBuilder *Builder = unwrap(PMB);
383 Builder->SizeLevel = SizeLevel;
387 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
389 PassManagerBuilder *Builder = unwrap(PMB);
390 Builder->DisableUnitAtATime = Value;
394 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
396 PassManagerBuilder *Builder = unwrap(PMB);
397 Builder->DisableUnrollLoops = Value;
401 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
403 // NOTE: The simplify-libcalls pass has been removed.
407 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
408 unsigned Threshold) {
409 PassManagerBuilder *Builder = unwrap(PMB);
410 Builder->Inliner = createFunctionInliningPass(Threshold);
414 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
415 LLVMPassManagerRef PM) {
416 PassManagerBuilder *Builder = unwrap(PMB);
417 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
418 Builder->populateFunctionPassManager(*FPM);
422 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
423 LLVMPassManagerRef PM) {
424 PassManagerBuilder *Builder = unwrap(PMB);
425 PassManagerBase *MPM = unwrap(PM);
426 Builder->populateModulePassManager(*MPM);
429 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
430 LLVMPassManagerRef PM,
431 LLVMBool Internalize,
432 LLVMBool RunInliner) {
433 PassManagerBuilder *Builder = unwrap(PMB);
434 PassManagerBase *LPM = unwrap(PM);
435 Builder->populateLTOPassManager(*LPM, Internalize != 0, RunInliner != 0);