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/IR/LegacyPassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Vectorize.h"
34 RunLoopVectorization("vectorize-loops", cl::Hidden,
35 cl::desc("Run the Loop vectorization passes"));
38 RunSLPVectorization("vectorize-slp", cl::Hidden,
39 cl::desc("Run the SLP vectorization passes"));
42 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
43 cl::desc("Run the BB vectorization passes"));
46 UseGVNAfterVectorization("use-gvn-after-vectorization",
47 cl::init(false), cl::Hidden,
48 cl::desc("Run GVN instead of Early CSE after vectorization passes"));
50 static cl::opt<bool> ExtraVectorizerPasses(
51 "extra-vectorizer-passes", cl::init(false), cl::Hidden,
52 cl::desc("Run cleanup optimization passes after vectorization."));
54 static cl::opt<bool> UseNewSROA("use-new-sroa",
55 cl::init(true), cl::Hidden,
56 cl::desc("Enable the new, experimental SROA pass"));
59 RunLoopRerolling("reroll-loops", cl::Hidden,
60 cl::desc("Run the loop rerolling pass"));
63 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
64 cl::desc("Run the float2int (float demotion) pass"));
66 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
68 cl::desc("Run the load combining pass"));
71 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
72 cl::init(true), cl::Hidden,
73 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
74 "vectorizer instead of before"));
76 static cl::opt<bool> UseCFLAA("use-cfl-aa",
77 cl::init(false), cl::Hidden,
78 cl::desc("Enable the new, experimental CFL alias analysis"));
81 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
82 cl::desc("Enable motion of merged load and store"));
84 static cl::opt<bool> EnableLoopInterchange(
85 "enable-loopinterchange", cl::init(false), cl::Hidden,
86 cl::desc("Enable the new, experimental LoopInterchange Pass"));
88 static cl::opt<bool> EnableLoopDistribute(
89 "enable-loop-distribute", cl::init(false), cl::Hidden,
90 cl::desc("Enable the new, experimental LoopDistribution Pass"));
92 PassManagerBuilder::PassManagerBuilder() {
95 LibraryInfo = nullptr;
97 DisableTailCalls = false;
98 DisableUnitAtATime = false;
99 DisableUnrollLoops = false;
100 BBVectorize = RunBBVectorization;
101 SLPVectorize = RunSLPVectorization;
102 LoopVectorize = RunLoopVectorization;
103 RerollLoops = RunLoopRerolling;
104 LoadCombine = RunLoadCombine;
105 DisableGVNLoadPRE = false;
107 VerifyOutput = false;
108 MergeFunctions = false;
111 PassManagerBuilder::~PassManagerBuilder() {
116 /// Set of global extensions, automatically added as part of the standard set.
117 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
118 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
120 void PassManagerBuilder::addGlobalExtension(
121 PassManagerBuilder::ExtensionPointTy Ty,
122 PassManagerBuilder::ExtensionFn Fn) {
123 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
126 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
127 Extensions.push_back(std::make_pair(Ty, Fn));
130 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
131 legacy::PassManagerBase &PM) const {
132 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
133 if ((*GlobalExtensions)[i].first == ETy)
134 (*GlobalExtensions)[i].second(*this, PM);
135 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
136 if (Extensions[i].first == ETy)
137 Extensions[i].second(*this, PM);
140 void PassManagerBuilder::addInitialAliasAnalysisPasses(
141 legacy::PassManagerBase &PM) const {
142 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
143 // BasicAliasAnalysis wins if they disagree. This is intended to help
144 // support "obvious" type-punning idioms.
146 PM.add(createCFLAliasAnalysisPass());
147 PM.add(createTypeBasedAliasAnalysisPass());
148 PM.add(createScopedNoAliasAAPass());
149 PM.add(createBasicAliasAnalysisPass());
152 void PassManagerBuilder::populateFunctionPassManager(
153 legacy::FunctionPassManager &FPM) {
154 addExtensionsToPM(EP_EarlyAsPossible, FPM);
156 // Add LibraryInfo if we have some.
158 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
160 if (OptLevel == 0) return;
162 addInitialAliasAnalysisPasses(FPM);
164 FPM.add(createCFGSimplificationPass());
166 FPM.add(createSROAPass());
168 FPM.add(createScalarReplAggregatesPass());
169 FPM.add(createEarlyCSEPass());
170 FPM.add(createLowerExpectIntrinsicPass());
173 void PassManagerBuilder::populateModulePassManager(
174 legacy::PassManagerBase &MPM) {
175 // If all optimizations are disabled, just run the always-inline pass and,
176 // if enabled, the function merging pass.
183 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
184 // creates a CGSCC pass manager, but we don't want to add extensions into
185 // that pass manager. To prevent this we insert a no-op module pass to reset
186 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
187 // builds. The function merging pass is
189 MPM.add(createMergeFunctionsPass());
190 else if (!GlobalExtensions->empty() || !Extensions.empty())
191 MPM.add(createBarrierNoopPass());
193 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
197 // Add LibraryInfo if we have some.
199 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
201 addInitialAliasAnalysisPasses(MPM);
203 if (!DisableUnitAtATime) {
204 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
206 MPM.add(createIPSCCPPass()); // IP SCCP
207 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
209 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
211 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
212 addExtensionsToPM(EP_Peephole, MPM);
213 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
216 // Start of CallGraph SCC passes.
217 if (!DisableUnitAtATime)
218 MPM.add(createPruneEHPass()); // Remove dead EH info
223 if (!DisableUnitAtATime)
224 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
226 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
228 // Start of function pass.
229 // Break up aggregate allocas, using SSAUpdater.
231 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
233 MPM.add(createScalarReplAggregatesPass(-1, false));
235 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
236 MPM.add(createJumpThreadingPass()); // Thread jumps.
237 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
238 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
239 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
240 addExtensionsToPM(EP_Peephole, MPM);
242 if (!DisableTailCalls)
243 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
244 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
245 MPM.add(createReassociatePass()); // Reassociate expressions
246 // Rotate Loop - disable header duplication at -Oz
247 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
248 MPM.add(createLICMPass()); // Hoist loop invariants
249 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
250 MPM.add(createInstructionCombiningPass());
251 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
252 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
253 MPM.add(createLoopDeletionPass()); // Delete dead loops
254 if (EnableLoopInterchange) {
255 MPM.add(createLoopInterchangePass()); // Interchange loops
256 MPM.add(createCFGSimplificationPass());
258 if (!DisableUnrollLoops)
259 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
260 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
264 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
265 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
267 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
268 MPM.add(createSCCPPass()); // Constant prop with SCCP
270 // Delete dead bit computations (instcombine runs after to fold away the dead
271 // computations, and then ADCE will run later to exploit any new DCE
272 // opportunities that creates).
273 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
275 // Run instcombine after redundancy elimination to exploit opportunities
276 // opened up by them.
277 MPM.add(createInstructionCombiningPass());
278 addExtensionsToPM(EP_Peephole, MPM);
279 MPM.add(createJumpThreadingPass()); // Thread jumps
280 MPM.add(createCorrelatedValuePropagationPass());
281 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
282 MPM.add(createLICMPass());
284 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
287 MPM.add(createLoopRerollPass());
288 if (!RunSLPAfterLoopVectorization) {
290 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
293 MPM.add(createBBVectorizePass());
294 MPM.add(createInstructionCombiningPass());
295 addExtensionsToPM(EP_Peephole, MPM);
296 if (OptLevel > 1 && UseGVNAfterVectorization)
297 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
299 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
301 // BBVectorize may have significantly shortened a loop body; unroll again.
302 if (!DisableUnrollLoops)
303 MPM.add(createLoopUnrollPass());
308 MPM.add(createLoadCombinePass());
310 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
311 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
312 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
313 addExtensionsToPM(EP_Peephole, MPM);
315 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
316 // pass manager that we are specifically trying to avoid. To prevent this
317 // we must insert a no-op module pass to reset the pass manager.
318 MPM.add(createBarrierNoopPass());
321 MPM.add(createFloat2IntPass());
323 // Re-rotate loops in all our loop nests. These may have fallout out of
324 // rotated form due to GVN or other transformations, and the vectorizer relies
325 // on the rotated form.
326 MPM.add(createLoopRotatePass());
328 // Distribute loops to allow partial vectorization. I.e. isolate dependences
329 // into separate loop that would otherwise inhibit vectorization.
330 if (EnableLoopDistribute)
331 MPM.add(createLoopDistributePass());
333 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
334 // FIXME: Because of #pragma vectorize enable, the passes below are always
335 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
336 // on -O1 and no #pragma is found). Would be good to have these two passes
337 // as function calls, so that we can only pass them when the vectorizer
339 MPM.add(createInstructionCombiningPass());
340 if (OptLevel > 1 && ExtraVectorizerPasses) {
341 // At higher optimization levels, try to clean up any runtime overlap and
342 // alignment checks inserted by the vectorizer. We want to track correllated
343 // runtime checks for two inner loops in the same outer loop, fold any
344 // common computations, hoist loop-invariant aspects out of any outer loop,
345 // and unswitch the runtime checks if possible. Once hoisted, we may have
346 // dead (or speculatable) control flows or more combining opportunities.
347 MPM.add(createEarlyCSEPass());
348 MPM.add(createCorrelatedValuePropagationPass());
349 MPM.add(createInstructionCombiningPass());
350 MPM.add(createLICMPass());
351 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
352 MPM.add(createCFGSimplificationPass());
353 MPM.add(createInstructionCombiningPass());
356 if (RunSLPAfterLoopVectorization) {
358 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
359 if (OptLevel > 1 && ExtraVectorizerPasses) {
360 MPM.add(createEarlyCSEPass());
365 MPM.add(createBBVectorizePass());
366 MPM.add(createInstructionCombiningPass());
367 addExtensionsToPM(EP_Peephole, MPM);
368 if (OptLevel > 1 && UseGVNAfterVectorization)
369 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
371 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
373 // BBVectorize may have significantly shortened a loop body; unroll again.
374 if (!DisableUnrollLoops)
375 MPM.add(createLoopUnrollPass());
379 addExtensionsToPM(EP_Peephole, MPM);
380 MPM.add(createCFGSimplificationPass());
381 MPM.add(createInstructionCombiningPass());
383 if (!DisableUnrollLoops) {
384 MPM.add(createLoopUnrollPass()); // Unroll small loops
386 // LoopUnroll may generate some redundency to cleanup.
387 MPM.add(createInstructionCombiningPass());
389 // This is a barrier pass to avoid combine LICM pass and loop unroll pass
390 // within same loop pass manager.
391 MPM.add(createInstructionSimplifierPass());
393 // Runtime unrolling will introduce runtime check in loop prologue. If the
394 // unrolled loop is a inner loop, then the prologue will be inside the
395 // outer loop. LICM pass can help to promote the runtime check out if the
396 // checked value is loop invariant.
397 MPM.add(createLICMPass());
400 // After vectorization and unrolling, assume intrinsics may tell us more
401 // about pointer alignments.
402 MPM.add(createAlignmentFromAssumptionsPass());
404 if (!DisableUnitAtATime) {
405 // FIXME: We shouldn't bother with this anymore.
406 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
408 // GlobalOpt already deletes dead functions and globals, at -O2 try a
409 // late pass of GlobalDCE. It is capable of deleting dead cycles.
411 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
412 MPM.add(createConstantMergePass()); // Merge dup global constants
417 MPM.add(createMergeFunctionsPass());
419 addExtensionsToPM(EP_OptimizerLast, MPM);
422 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
423 // Provide AliasAnalysis services for optimizations.
424 addInitialAliasAnalysisPasses(PM);
426 // Propagate constants at call sites into the functions they call. This
427 // opens opportunities for globalopt (and inlining) by substituting function
428 // pointers passed as arguments to direct uses of functions.
429 PM.add(createIPSCCPPass());
431 // Now that we internalized some globals, see if we can hack on them!
432 PM.add(createGlobalOptimizerPass());
434 // Linking modules together can lead to duplicated global constants, only
435 // keep one copy of each constant.
436 PM.add(createConstantMergePass());
438 // Remove unused arguments from functions.
439 PM.add(createDeadArgEliminationPass());
441 // Reduce the code after globalopt and ipsccp. Both can open up significant
442 // simplification opportunities, and both can propagate functions through
443 // function pointers. When this happens, we often have to resolve varargs
444 // calls, etc, so let instcombine do this.
445 PM.add(createInstructionCombiningPass());
446 addExtensionsToPM(EP_Peephole, PM);
448 // Inline small functions
449 bool RunInliner = Inliner;
455 PM.add(createPruneEHPass()); // Remove dead EH info.
457 // Optimize globals again if we ran the inliner.
459 PM.add(createGlobalOptimizerPass());
460 PM.add(createGlobalDCEPass()); // Remove dead functions.
462 // If we didn't decide to inline a function, check to see if we can
463 // transform it to pass arguments by value instead of by reference.
464 PM.add(createArgumentPromotionPass());
466 // The IPO passes may leave cruft around. Clean up after them.
467 PM.add(createInstructionCombiningPass());
468 addExtensionsToPM(EP_Peephole, PM);
469 PM.add(createJumpThreadingPass());
473 PM.add(createSROAPass());
475 PM.add(createScalarReplAggregatesPass());
477 // Run a few AA driven optimizations here and now, to cleanup the code.
478 PM.add(createFunctionAttrsPass()); // Add nocapture.
479 PM.add(createGlobalsModRefPass()); // IP alias analysis.
481 PM.add(createLICMPass()); // Hoist loop invariants.
483 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
484 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
485 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
488 PM.add(createDeadStoreEliminationPass());
490 // More loops are countable; try to optimize them.
491 PM.add(createIndVarSimplifyPass());
492 PM.add(createLoopDeletionPass());
493 if (EnableLoopInterchange)
494 PM.add(createLoopInterchangePass());
496 PM.add(createLoopVectorizePass(true, LoopVectorize));
498 // More scalar chains could be vectorized due to more alias information
499 if (RunSLPAfterLoopVectorization)
501 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
503 // After vectorization, assume intrinsics may tell us more about pointer
505 PM.add(createAlignmentFromAssumptionsPass());
508 PM.add(createLoadCombinePass());
510 // Cleanup and simplify the code after the scalar optimizations.
511 PM.add(createInstructionCombiningPass());
512 addExtensionsToPM(EP_Peephole, PM);
514 PM.add(createJumpThreadingPass());
517 void PassManagerBuilder::addLateLTOOptimizationPasses(
518 legacy::PassManagerBase &PM) {
519 // Delete basic blocks, which optimization passes may have killed.
520 PM.add(createCFGSimplificationPass());
522 // Now that we have optimized the program, discard unreachable functions.
523 PM.add(createGlobalDCEPass());
525 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
526 // currently it damages debug info.
528 PM.add(createMergeFunctionsPass());
531 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
533 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
536 PM.add(createVerifierPass());
539 addLTOOptimizationPasses(PM);
541 // Lower bit sets to globals. This pass supports Clang's control flow
542 // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
543 // is enabled. The pass does nothing if CFI is disabled.
544 PM.add(createLowerBitSetsPass());
547 addLateLTOOptimizationPasses(PM);
550 PM.add(createVerifierPass());
553 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
554 return reinterpret_cast<PassManagerBuilder*>(P);
557 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
558 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
561 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
562 PassManagerBuilder *PMB = new PassManagerBuilder();
566 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
567 PassManagerBuilder *Builder = unwrap(PMB);
572 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
574 PassManagerBuilder *Builder = unwrap(PMB);
575 Builder->OptLevel = OptLevel;
579 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
580 unsigned SizeLevel) {
581 PassManagerBuilder *Builder = unwrap(PMB);
582 Builder->SizeLevel = SizeLevel;
586 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
588 PassManagerBuilder *Builder = unwrap(PMB);
589 Builder->DisableUnitAtATime = Value;
593 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
595 PassManagerBuilder *Builder = unwrap(PMB);
596 Builder->DisableUnrollLoops = Value;
600 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
602 // NOTE: The simplify-libcalls pass has been removed.
606 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
607 unsigned Threshold) {
608 PassManagerBuilder *Builder = unwrap(PMB);
609 Builder->Inliner = createFunctionInliningPass(Threshold);
613 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
614 LLVMPassManagerRef PM) {
615 PassManagerBuilder *Builder = unwrap(PMB);
616 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
617 Builder->populateFunctionPassManager(*FPM);
621 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
622 LLVMPassManagerRef PM) {
623 PassManagerBuilder *Builder = unwrap(PMB);
624 legacy::PassManagerBase *MPM = unwrap(PM);
625 Builder->populateModulePassManager(*MPM);
628 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
629 LLVMPassManagerRef PM,
630 LLVMBool Internalize,
631 LLVMBool RunInliner) {
632 PassManagerBuilder *Builder = unwrap(PMB);
633 legacy::PassManagerBase *LPM = unwrap(PM);
635 // A small backwards compatibility hack. populateLTOPassManager used to take
636 // an RunInliner option.
637 if (RunInliner && !Builder->Inliner)
638 Builder->Inliner = createFunctionInliningPass();
640 Builder->populateLTOPassManager(*LPM);