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> ExtraVectorizerPasses(
52 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
53 cl::desc("Run cleanup optimization passes after vectorization."));
55 static cl::opt<bool> UseNewSROA("use-new-sroa",
56 cl::init(true), cl::Hidden,
57 cl::desc("Enable the new, experimental SROA pass"));
60 RunLoopRerolling("reroll-loops", cl::Hidden,
61 cl::desc("Run the loop rerolling pass"));
63 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
65 cl::desc("Run the load combining pass"));
68 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
69 cl::init(true), cl::Hidden,
70 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
71 "vectorizer instead of before"));
73 static cl::opt<bool> UseCFLAA("use-cfl-aa",
74 cl::init(false), cl::Hidden,
75 cl::desc("Enable the new, experimental CFL alias analysis"));
78 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
79 cl::desc("Enable motion of merged load and store"));
81 PassManagerBuilder::PassManagerBuilder() {
84 LibraryInfo = nullptr;
86 DisableTailCalls = false;
87 DisableUnitAtATime = false;
88 DisableUnrollLoops = false;
89 BBVectorize = RunBBVectorization;
90 SLPVectorize = RunSLPVectorization;
91 LoopVectorize = RunLoopVectorization;
92 RerollLoops = RunLoopRerolling;
93 LoadCombine = RunLoadCombine;
94 DisableGVNLoadPRE = false;
98 MergeFunctions = false;
101 PassManagerBuilder::~PassManagerBuilder() {
106 /// Set of global extensions, automatically added as part of the standard set.
107 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
108 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
110 void PassManagerBuilder::addGlobalExtension(
111 PassManagerBuilder::ExtensionPointTy Ty,
112 PassManagerBuilder::ExtensionFn Fn) {
113 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
116 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
117 Extensions.push_back(std::make_pair(Ty, Fn));
120 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
121 PassManagerBase &PM) const {
122 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
123 if ((*GlobalExtensions)[i].first == ETy)
124 (*GlobalExtensions)[i].second(*this, PM);
125 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
126 if (Extensions[i].first == ETy)
127 Extensions[i].second(*this, PM);
131 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
132 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
133 // BasicAliasAnalysis wins if they disagree. This is intended to help
134 // support "obvious" type-punning idioms.
136 PM.add(createCFLAliasAnalysisPass());
137 PM.add(createTypeBasedAliasAnalysisPass());
138 PM.add(createScopedNoAliasAAPass());
139 PM.add(createBasicAliasAnalysisPass());
142 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
143 addExtensionsToPM(EP_EarlyAsPossible, FPM);
145 // Add LibraryInfo if we have some.
146 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
148 if (OptLevel == 0) return;
150 addInitialAliasAnalysisPasses(FPM);
152 FPM.add(createCFGSimplificationPass());
154 FPM.add(createSROAPass());
156 FPM.add(createScalarReplAggregatesPass());
157 FPM.add(createEarlyCSEPass());
158 FPM.add(createLowerExpectIntrinsicPass());
161 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
162 // If all optimizations are disabled, just run the always-inline pass.
169 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
170 // pass manager, but we don't want to add extensions into that pass manager.
171 // To prevent this we must insert a no-op module pass to reset the pass
172 // manager to get the same behavior as EP_OptimizerLast in non-O0 builds.
173 if (!GlobalExtensions->empty() || !Extensions.empty())
174 MPM.add(createBarrierNoopPass());
176 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
180 // Add LibraryInfo if we have some.
181 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
183 addInitialAliasAnalysisPasses(MPM);
185 if (!DisableUnitAtATime) {
186 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
188 MPM.add(createIPSCCPPass()); // IP SCCP
189 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
191 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
193 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
194 addExtensionsToPM(EP_Peephole, MPM);
195 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
198 // Start of CallGraph SCC passes.
199 if (!DisableUnitAtATime)
200 MPM.add(createPruneEHPass()); // Remove dead EH info
205 if (!DisableUnitAtATime)
206 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
208 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
210 // Start of function pass.
211 // Break up aggregate allocas, using SSAUpdater.
213 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
215 MPM.add(createScalarReplAggregatesPass(-1, false));
216 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
217 MPM.add(createJumpThreadingPass()); // Thread jumps.
218 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
219 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
220 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
221 addExtensionsToPM(EP_Peephole, MPM);
223 if (!DisableTailCalls)
224 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
225 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
226 MPM.add(createReassociatePass()); // Reassociate expressions
227 MPM.add(createLoopRotatePass()); // Rotate Loop
228 MPM.add(createLICMPass()); // Hoist loop invariants
229 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
230 MPM.add(createInstructionCombiningPass());
231 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
232 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
233 MPM.add(createLoopDeletionPass()); // Delete dead loops
235 if (!DisableUnrollLoops)
236 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
237 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
241 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
242 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
244 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
245 MPM.add(createSCCPPass()); // Constant prop with SCCP
247 // Run instcombine after redundancy elimination to exploit opportunities
248 // opened up by them.
249 MPM.add(createInstructionCombiningPass());
250 addExtensionsToPM(EP_Peephole, MPM);
251 MPM.add(createJumpThreadingPass()); // Thread jumps
252 MPM.add(createCorrelatedValuePropagationPass());
253 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
255 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
258 MPM.add(createLoopRerollPass());
259 if (!RunSLPAfterLoopVectorization) {
261 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
264 MPM.add(createBBVectorizePass());
265 MPM.add(createInstructionCombiningPass());
266 addExtensionsToPM(EP_Peephole, MPM);
267 if (OptLevel > 1 && UseGVNAfterVectorization)
268 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
270 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
272 // BBVectorize may have significantly shortened a loop body; unroll again.
273 if (!DisableUnrollLoops)
274 MPM.add(createLoopUnrollPass());
279 MPM.add(createLoadCombinePass());
281 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
282 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
283 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
284 addExtensionsToPM(EP_Peephole, MPM);
286 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
287 // pass manager that we are specifically trying to avoid. To prevent this
288 // we must insert a no-op module pass to reset the pass manager.
289 MPM.add(createBarrierNoopPass());
291 // Re-rotate loops in all our loop nests. These may have fallout out of
292 // rotated form due to GVN or other transformations, and the vectorizer relies
293 // on the rotated form.
294 if (ExtraVectorizerPasses)
295 MPM.add(createLoopRotatePass());
297 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
298 // FIXME: Because of #pragma vectorize enable, the passes below are always
299 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
300 // on -O1 and no #pragma is found). Would be good to have these two passes
301 // as function calls, so that we can only pass them when the vectorizer
303 MPM.add(createInstructionCombiningPass());
304 if (OptLevel > 1 && ExtraVectorizerPasses) {
305 // At higher optimization levels, try to clean up any runtime overlap and
306 // alignment checks inserted by the vectorizer. We want to track correllated
307 // runtime checks for two inner loops in the same outer loop, fold any
308 // common computations, hoist loop-invariant aspects out of any outer loop,
309 // and unswitch the runtime checks if possible. Once hoisted, we may have
310 // dead (or speculatable) control flows or more combining opportunities.
311 MPM.add(createEarlyCSEPass());
312 MPM.add(createCorrelatedValuePropagationPass());
313 MPM.add(createInstructionCombiningPass());
314 MPM.add(createLICMPass());
315 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
316 MPM.add(createCFGSimplificationPass());
317 MPM.add(createInstructionCombiningPass());
320 if (RunSLPAfterLoopVectorization) {
322 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
323 if (OptLevel > 1 && ExtraVectorizerPasses) {
324 MPM.add(createEarlyCSEPass());
329 MPM.add(createBBVectorizePass());
330 MPM.add(createInstructionCombiningPass());
331 addExtensionsToPM(EP_Peephole, MPM);
332 if (OptLevel > 1 && UseGVNAfterVectorization)
333 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
335 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
337 // BBVectorize may have significantly shortened a loop body; unroll again.
338 if (!DisableUnrollLoops)
339 MPM.add(createLoopUnrollPass());
343 addExtensionsToPM(EP_Peephole, MPM);
344 MPM.add(createCFGSimplificationPass());
345 MPM.add(createInstructionCombiningPass());
347 if (!DisableUnrollLoops)
348 MPM.add(createLoopUnrollPass()); // Unroll small loops
350 // After vectorization and unrolling, assume intrinsics may tell us more
351 // about pointer alignments.
352 MPM.add(createAlignmentFromAssumptionsPass());
354 if (!DisableUnitAtATime) {
355 // FIXME: We shouldn't bother with this anymore.
356 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
358 // GlobalOpt already deletes dead functions and globals, at -O2 try a
359 // late pass of GlobalDCE. It is capable of deleting dead cycles.
361 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
362 MPM.add(createConstantMergePass()); // Merge dup global constants
367 MPM.add(createMergeFunctionsPass());
369 addExtensionsToPM(EP_OptimizerLast, MPM);
372 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
373 // Provide AliasAnalysis services for optimizations.
374 addInitialAliasAnalysisPasses(PM);
376 // Propagate constants at call sites into the functions they call. This
377 // opens opportunities for globalopt (and inlining) by substituting function
378 // pointers passed as arguments to direct uses of functions.
379 PM.add(createIPSCCPPass());
381 // Now that we internalized some globals, see if we can hack on them!
382 PM.add(createGlobalOptimizerPass());
384 // Linking modules together can lead to duplicated global constants, only
385 // keep one copy of each constant.
386 PM.add(createConstantMergePass());
388 // Remove unused arguments from functions.
389 PM.add(createDeadArgEliminationPass());
391 // Reduce the code after globalopt and ipsccp. Both can open up significant
392 // simplification opportunities, and both can propagate functions through
393 // function pointers. When this happens, we often have to resolve varargs
394 // calls, etc, so let instcombine do this.
395 PM.add(createInstructionCombiningPass());
396 addExtensionsToPM(EP_Peephole, PM);
398 // Inline small functions
399 bool RunInliner = Inliner;
405 PM.add(createPruneEHPass()); // Remove dead EH info.
407 // Optimize globals again if we ran the inliner.
409 PM.add(createGlobalOptimizerPass());
410 PM.add(createGlobalDCEPass()); // Remove dead functions.
412 // If we didn't decide to inline a function, check to see if we can
413 // transform it to pass arguments by value instead of by reference.
414 PM.add(createArgumentPromotionPass());
416 // The IPO passes may leave cruft around. Clean up after them.
417 PM.add(createInstructionCombiningPass());
418 addExtensionsToPM(EP_Peephole, PM);
419 PM.add(createJumpThreadingPass());
423 PM.add(createSROAPass());
425 PM.add(createScalarReplAggregatesPass());
427 // Run a few AA driven optimizations here and now, to cleanup the code.
428 PM.add(createFunctionAttrsPass()); // Add nocapture.
429 PM.add(createGlobalsModRefPass()); // IP alias analysis.
431 PM.add(createLICMPass()); // Hoist loop invariants.
433 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
434 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
435 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
438 PM.add(createDeadStoreEliminationPass());
440 // More loops are countable; try to optimize them.
441 PM.add(createIndVarSimplifyPass());
442 PM.add(createLoopDeletionPass());
443 PM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
445 // More scalar chains could be vectorized due to more alias information
446 if (RunSLPAfterLoopVectorization)
448 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
450 // After vectorization, assume intrinsics may tell us more about pointer
452 PM.add(createAlignmentFromAssumptionsPass());
455 PM.add(createLoadCombinePass());
457 // Cleanup and simplify the code after the scalar optimizations.
458 PM.add(createInstructionCombiningPass());
459 addExtensionsToPM(EP_Peephole, PM);
461 PM.add(createJumpThreadingPass());
463 // Delete basic blocks, which optimization passes may have killed.
464 PM.add(createCFGSimplificationPass());
466 // Now that we have optimized the program, discard unreachable functions.
467 PM.add(createGlobalDCEPass());
469 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
470 // currently it damages debug info.
472 PM.add(createMergeFunctionsPass());
475 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
478 PM.add(new DataLayoutPass());
479 TM->addAnalysisPasses(PM);
483 PM.add(new TargetLibraryInfo(*LibraryInfo));
486 PM.add(createVerifierPass());
489 PM.add(createStripSymbolsPass(true));
492 PM.add(createDebugInfoVerifierPass());
495 addLTOOptimizationPasses(PM);
498 PM.add(createVerifierPass());
499 PM.add(createDebugInfoVerifierPass());
503 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
504 return reinterpret_cast<PassManagerBuilder*>(P);
507 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
508 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
511 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
512 PassManagerBuilder *PMB = new PassManagerBuilder();
516 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
517 PassManagerBuilder *Builder = unwrap(PMB);
522 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
524 PassManagerBuilder *Builder = unwrap(PMB);
525 Builder->OptLevel = OptLevel;
529 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
530 unsigned SizeLevel) {
531 PassManagerBuilder *Builder = unwrap(PMB);
532 Builder->SizeLevel = SizeLevel;
536 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
538 PassManagerBuilder *Builder = unwrap(PMB);
539 Builder->DisableUnitAtATime = Value;
543 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
545 PassManagerBuilder *Builder = unwrap(PMB);
546 Builder->DisableUnrollLoops = Value;
550 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
552 // NOTE: The simplify-libcalls pass has been removed.
556 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
557 unsigned Threshold) {
558 PassManagerBuilder *Builder = unwrap(PMB);
559 Builder->Inliner = createFunctionInliningPass(Threshold);
563 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
564 LLVMPassManagerRef PM) {
565 PassManagerBuilder *Builder = unwrap(PMB);
566 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
567 Builder->populateFunctionPassManager(*FPM);
571 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
572 LLVMPassManagerRef PM) {
573 PassManagerBuilder *Builder = unwrap(PMB);
574 PassManagerBase *MPM = unwrap(PM);
575 Builder->populateModulePassManager(*MPM);
578 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
579 LLVMPassManagerRef PM,
580 LLVMBool Internalize,
581 LLVMBool RunInliner) {
582 PassManagerBuilder *Builder = unwrap(PMB);
583 PassManagerBase *LPM = unwrap(PM);
585 // A small backwards compatibility hack. populateLTOPassManager used to take
586 // an RunInliner option.
587 if (RunInliner && !Builder->Inliner)
588 Builder->Inliner = createFunctionInliningPass();
590 Builder->populateLTOPassManager(*LPM);