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 static cl::opt<bool> EnableGVN("enable-gvn",
82 cl::init(true), cl::Hidden,
83 cl::desc("Run the global value numbering pass"));
85 PassManagerBuilder::PassManagerBuilder() {
88 LibraryInfo = nullptr;
90 DisableTailCalls = false;
91 DisableUnitAtATime = false;
92 DisableUnrollLoops = false;
93 BBVectorize = RunBBVectorization;
94 SLPVectorize = RunSLPVectorization;
95 LoopVectorize = RunLoopVectorization;
96 RerollLoops = RunLoopRerolling;
97 LoadCombine = RunLoadCombine;
98 DisableGVNLoadPRE = false;
100 VerifyOutput = false;
102 MergeFunctions = false;
105 PassManagerBuilder::~PassManagerBuilder() {
110 /// Set of global extensions, automatically added as part of the standard set.
111 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
112 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
114 void PassManagerBuilder::addGlobalExtension(
115 PassManagerBuilder::ExtensionPointTy Ty,
116 PassManagerBuilder::ExtensionFn Fn) {
117 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
120 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
121 Extensions.push_back(std::make_pair(Ty, Fn));
124 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
125 PassManagerBase &PM) const {
126 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
127 if ((*GlobalExtensions)[i].first == ETy)
128 (*GlobalExtensions)[i].second(*this, PM);
129 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
130 if (Extensions[i].first == ETy)
131 Extensions[i].second(*this, PM);
135 PassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {
136 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
137 // BasicAliasAnalysis wins if they disagree. This is intended to help
138 // support "obvious" type-punning idioms.
140 PM.add(createCFLAliasAnalysisPass());
141 PM.add(createTypeBasedAliasAnalysisPass());
142 PM.add(createScopedNoAliasAAPass());
143 PM.add(createBasicAliasAnalysisPass());
146 void PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {
147 addExtensionsToPM(EP_EarlyAsPossible, FPM);
149 // Add LibraryInfo if we have some.
150 if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));
152 if (OptLevel == 0) return;
154 addInitialAliasAnalysisPasses(FPM);
156 FPM.add(createCFGSimplificationPass());
158 FPM.add(createSROAPass());
160 FPM.add(createScalarReplAggregatesPass());
161 FPM.add(createEarlyCSEPass());
162 FPM.add(createLowerExpectIntrinsicPass());
165 void PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {
166 // If all optimizations are disabled, just run the always-inline pass and,
167 // if enabled, the function merging pass.
174 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
175 // creates a CGSCC pass manager, but we don't want to add extensions into
176 // that pass manager. To prevent this we insert a no-op module pass to reset
177 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
178 // builds. The function merging pass is
180 MPM.add(createMergeFunctionsPass());
181 else if (!GlobalExtensions->empty() || !Extensions.empty())
182 MPM.add(createBarrierNoopPass());
184 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
188 // Add LibraryInfo if we have some.
189 if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));
191 addInitialAliasAnalysisPasses(MPM);
193 if (!DisableUnitAtATime) {
194 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
196 MPM.add(createIPSCCPPass()); // IP SCCP
197 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
199 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
201 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
202 addExtensionsToPM(EP_Peephole, MPM);
203 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
206 // Start of CallGraph SCC passes.
207 if (!DisableUnitAtATime)
208 MPM.add(createPruneEHPass()); // Remove dead EH info
213 if (!DisableUnitAtATime)
214 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
216 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
218 // Start of function pass.
219 // Break up aggregate allocas, using SSAUpdater.
221 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
223 MPM.add(createScalarReplAggregatesPass(-1, false));
224 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
225 MPM.add(createJumpThreadingPass()); // Thread jumps.
226 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
227 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
228 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
229 addExtensionsToPM(EP_Peephole, MPM);
231 if (!DisableTailCalls)
232 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
233 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
234 MPM.add(createReassociatePass()); // Reassociate expressions
235 // Rotate Loop - disable header duplication at -Oz
236 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
237 MPM.add(createLICMPass()); // Hoist loop invariants
238 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
239 MPM.add(createInstructionCombiningPass());
240 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
241 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
242 MPM.add(createLoopDeletionPass()); // Delete dead loops
244 if (!DisableUnrollLoops)
245 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
246 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
250 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
252 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
254 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
255 MPM.add(createSCCPPass()); // Constant prop with SCCP
257 // Run instcombine after redundancy elimination to exploit opportunities
258 // opened up by them.
259 MPM.add(createInstructionCombiningPass());
260 addExtensionsToPM(EP_Peephole, MPM);
261 MPM.add(createJumpThreadingPass()); // Thread jumps
262 MPM.add(createCorrelatedValuePropagationPass());
263 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
265 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
268 MPM.add(createLoopRerollPass());
269 if (!RunSLPAfterLoopVectorization) {
271 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
274 MPM.add(createBBVectorizePass());
275 MPM.add(createInstructionCombiningPass());
276 addExtensionsToPM(EP_Peephole, MPM);
277 if (OptLevel > 1 && UseGVNAfterVectorization)
278 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
280 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
282 // BBVectorize may have significantly shortened a loop body; unroll again.
283 if (!DisableUnrollLoops)
284 MPM.add(createLoopUnrollPass());
289 MPM.add(createLoadCombinePass());
291 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
292 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
293 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
294 addExtensionsToPM(EP_Peephole, MPM);
296 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
297 // pass manager that we are specifically trying to avoid. To prevent this
298 // we must insert a no-op module pass to reset the pass manager.
299 MPM.add(createBarrierNoopPass());
301 // Re-rotate loops in all our loop nests. These may have fallout out of
302 // rotated form due to GVN or other transformations, and the vectorizer relies
303 // on the rotated form.
304 if (ExtraVectorizerPasses)
305 MPM.add(createLoopRotatePass());
307 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
308 // FIXME: Because of #pragma vectorize enable, the passes below are always
309 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
310 // on -O1 and no #pragma is found). Would be good to have these two passes
311 // as function calls, so that we can only pass them when the vectorizer
313 MPM.add(createInstructionCombiningPass());
314 if (OptLevel > 1 && ExtraVectorizerPasses) {
315 // At higher optimization levels, try to clean up any runtime overlap and
316 // alignment checks inserted by the vectorizer. We want to track correllated
317 // runtime checks for two inner loops in the same outer loop, fold any
318 // common computations, hoist loop-invariant aspects out of any outer loop,
319 // and unswitch the runtime checks if possible. Once hoisted, we may have
320 // dead (or speculatable) control flows or more combining opportunities.
321 MPM.add(createEarlyCSEPass());
322 MPM.add(createCorrelatedValuePropagationPass());
323 MPM.add(createInstructionCombiningPass());
324 MPM.add(createLICMPass());
325 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
326 MPM.add(createCFGSimplificationPass());
327 MPM.add(createInstructionCombiningPass());
330 if (RunSLPAfterLoopVectorization) {
332 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
333 if (OptLevel > 1 && ExtraVectorizerPasses) {
334 MPM.add(createEarlyCSEPass());
339 MPM.add(createBBVectorizePass());
340 MPM.add(createInstructionCombiningPass());
341 addExtensionsToPM(EP_Peephole, MPM);
342 if (OptLevel > 1 && UseGVNAfterVectorization)
343 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
345 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
347 // BBVectorize may have significantly shortened a loop body; unroll again.
348 if (!DisableUnrollLoops)
349 MPM.add(createLoopUnrollPass());
353 addExtensionsToPM(EP_Peephole, MPM);
354 MPM.add(createCFGSimplificationPass());
355 MPM.add(createInstructionCombiningPass());
357 if (!DisableUnrollLoops)
358 MPM.add(createLoopUnrollPass()); // Unroll small loops
360 // After vectorization and unrolling, assume intrinsics may tell us more
361 // about pointer alignments.
362 MPM.add(createAlignmentFromAssumptionsPass());
364 if (!DisableUnitAtATime) {
365 // FIXME: We shouldn't bother with this anymore.
366 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
368 // GlobalOpt already deletes dead functions and globals, at -O2 try a
369 // late pass of GlobalDCE. It is capable of deleting dead cycles.
371 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
372 MPM.add(createConstantMergePass()); // Merge dup global constants
377 MPM.add(createMergeFunctionsPass());
379 addExtensionsToPM(EP_OptimizerLast, MPM);
382 void PassManagerBuilder::addLTOOptimizationPasses(PassManagerBase &PM) {
383 // Provide AliasAnalysis services for optimizations.
384 addInitialAliasAnalysisPasses(PM);
386 // Propagate constants at call sites into the functions they call. This
387 // opens opportunities for globalopt (and inlining) by substituting function
388 // pointers passed as arguments to direct uses of functions.
389 PM.add(createIPSCCPPass());
391 // Now that we internalized some globals, see if we can hack on them!
392 PM.add(createGlobalOptimizerPass());
394 // Linking modules together can lead to duplicated global constants, only
395 // keep one copy of each constant.
396 PM.add(createConstantMergePass());
398 // Remove unused arguments from functions.
399 PM.add(createDeadArgEliminationPass());
401 // Reduce the code after globalopt and ipsccp. Both can open up significant
402 // simplification opportunities, and both can propagate functions through
403 // function pointers. When this happens, we often have to resolve varargs
404 // calls, etc, so let instcombine do this.
405 PM.add(createInstructionCombiningPass());
406 addExtensionsToPM(EP_Peephole, PM);
408 // Inline small functions
409 bool RunInliner = Inliner;
415 PM.add(createPruneEHPass()); // Remove dead EH info.
417 // Optimize globals again if we ran the inliner.
419 PM.add(createGlobalOptimizerPass());
420 PM.add(createGlobalDCEPass()); // Remove dead functions.
422 // If we didn't decide to inline a function, check to see if we can
423 // transform it to pass arguments by value instead of by reference.
424 PM.add(createArgumentPromotionPass());
426 // The IPO passes may leave cruft around. Clean up after them.
427 PM.add(createInstructionCombiningPass());
428 addExtensionsToPM(EP_Peephole, PM);
429 PM.add(createJumpThreadingPass());
433 PM.add(createSROAPass());
435 PM.add(createScalarReplAggregatesPass());
437 // Run a few AA driven optimizations here and now, to cleanup the code.
438 PM.add(createFunctionAttrsPass()); // Add nocapture.
439 PM.add(createGlobalsModRefPass()); // IP alias analysis.
441 PM.add(createLICMPass()); // Hoist loop invariants.
443 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
444 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
445 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
448 PM.add(createDeadStoreEliminationPass());
450 // More loops are countable; try to optimize them.
451 PM.add(createIndVarSimplifyPass());
452 PM.add(createLoopDeletionPass());
453 PM.add(createLoopVectorizePass(true, LoopVectorize));
455 // More scalar chains could be vectorized due to more alias information
456 if (RunSLPAfterLoopVectorization)
458 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
460 // After vectorization, assume intrinsics may tell us more about pointer
462 PM.add(createAlignmentFromAssumptionsPass());
465 PM.add(createLoadCombinePass());
467 // Cleanup and simplify the code after the scalar optimizations.
468 PM.add(createInstructionCombiningPass());
469 addExtensionsToPM(EP_Peephole, PM);
471 PM.add(createJumpThreadingPass());
473 // Delete basic blocks, which optimization passes may have killed.
474 PM.add(createCFGSimplificationPass());
476 // Now that we have optimized the program, discard unreachable functions.
477 PM.add(createGlobalDCEPass());
479 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
480 // currently it damages debug info.
482 PM.add(createMergeFunctionsPass());
485 void PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,
488 PM.add(new DataLayoutPass());
489 TM->addAnalysisPasses(PM);
493 PM.add(new TargetLibraryInfo(*LibraryInfo));
496 PM.add(createVerifierPass());
499 PM.add(createStripSymbolsPass(true));
502 PM.add(createDebugInfoVerifierPass());
505 addLTOOptimizationPasses(PM);
508 PM.add(createVerifierPass());
509 PM.add(createDebugInfoVerifierPass());
513 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
514 return reinterpret_cast<PassManagerBuilder*>(P);
517 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
518 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
521 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
522 PassManagerBuilder *PMB = new PassManagerBuilder();
526 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
527 PassManagerBuilder *Builder = unwrap(PMB);
532 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
534 PassManagerBuilder *Builder = unwrap(PMB);
535 Builder->OptLevel = OptLevel;
539 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
540 unsigned SizeLevel) {
541 PassManagerBuilder *Builder = unwrap(PMB);
542 Builder->SizeLevel = SizeLevel;
546 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
548 PassManagerBuilder *Builder = unwrap(PMB);
549 Builder->DisableUnitAtATime = Value;
553 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
555 PassManagerBuilder *Builder = unwrap(PMB);
556 Builder->DisableUnrollLoops = Value;
560 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
562 // NOTE: The simplify-libcalls pass has been removed.
566 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
567 unsigned Threshold) {
568 PassManagerBuilder *Builder = unwrap(PMB);
569 Builder->Inliner = createFunctionInliningPass(Threshold);
573 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
574 LLVMPassManagerRef PM) {
575 PassManagerBuilder *Builder = unwrap(PMB);
576 FunctionPassManager *FPM = unwrap<FunctionPassManager>(PM);
577 Builder->populateFunctionPassManager(*FPM);
581 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
582 LLVMPassManagerRef PM) {
583 PassManagerBuilder *Builder = unwrap(PMB);
584 PassManagerBase *MPM = unwrap(PM);
585 Builder->populateModulePassManager(*MPM);
588 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
589 LLVMPassManagerRef PM,
590 LLVMBool Internalize,
591 LLVMBool RunInliner) {
592 PassManagerBuilder *Builder = unwrap(PMB);
593 PassManagerBase *LPM = unwrap(PM);
595 // A small backwards compatibility hack. populateLTOPassManager used to take
596 // an RunInliner option.
597 if (RunInliner && !Builder->Inliner)
598 Builder->Inliner = createFunctionInliningPass();
600 Builder->populateLTOPassManager(*LPM);