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 DisableUnitAtATime = false;
98 DisableUnrollLoops = false;
99 BBVectorize = RunBBVectorization;
100 SLPVectorize = RunSLPVectorization;
101 LoopVectorize = RunLoopVectorization;
102 RerollLoops = RunLoopRerolling;
103 LoadCombine = RunLoadCombine;
104 DisableGVNLoadPRE = false;
106 VerifyOutput = false;
107 MergeFunctions = false;
110 PassManagerBuilder::~PassManagerBuilder() {
115 /// Set of global extensions, automatically added as part of the standard set.
116 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
117 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
119 void PassManagerBuilder::addGlobalExtension(
120 PassManagerBuilder::ExtensionPointTy Ty,
121 PassManagerBuilder::ExtensionFn Fn) {
122 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
125 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
126 Extensions.push_back(std::make_pair(Ty, Fn));
129 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
130 legacy::PassManagerBase &PM) const {
131 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
132 if ((*GlobalExtensions)[i].first == ETy)
133 (*GlobalExtensions)[i].second(*this, PM);
134 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
135 if (Extensions[i].first == ETy)
136 Extensions[i].second(*this, PM);
139 void PassManagerBuilder::addInitialAliasAnalysisPasses(
140 legacy::PassManagerBase &PM) const {
141 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
142 // BasicAliasAnalysis wins if they disagree. This is intended to help
143 // support "obvious" type-punning idioms.
145 PM.add(createCFLAliasAnalysisPass());
146 PM.add(createTypeBasedAliasAnalysisPass());
147 PM.add(createScopedNoAliasAAPass());
148 PM.add(createBasicAliasAnalysisPass());
151 void PassManagerBuilder::populateFunctionPassManager(
152 legacy::FunctionPassManager &FPM) {
153 addExtensionsToPM(EP_EarlyAsPossible, FPM);
155 // Add LibraryInfo if we have some.
157 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
159 if (OptLevel == 0) return;
161 addInitialAliasAnalysisPasses(FPM);
163 FPM.add(createCFGSimplificationPass());
165 FPM.add(createSROAPass());
167 FPM.add(createScalarReplAggregatesPass());
168 FPM.add(createEarlyCSEPass());
169 FPM.add(createLowerExpectIntrinsicPass());
172 void PassManagerBuilder::populateModulePassManager(
173 legacy::PassManagerBase &MPM) {
174 // If all optimizations are disabled, just run the always-inline pass and,
175 // if enabled, the function merging pass.
182 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
183 // creates a CGSCC pass manager, but we don't want to add extensions into
184 // that pass manager. To prevent this we insert a no-op module pass to reset
185 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
186 // builds. The function merging pass is
188 MPM.add(createMergeFunctionsPass());
189 else if (!GlobalExtensions->empty() || !Extensions.empty())
190 MPM.add(createBarrierNoopPass());
192 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
196 // Add LibraryInfo if we have some.
198 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
200 addInitialAliasAnalysisPasses(MPM);
202 if (!DisableUnitAtATime) {
203 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
205 MPM.add(createIPSCCPPass()); // IP SCCP
206 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
208 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
210 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
211 addExtensionsToPM(EP_Peephole, MPM);
212 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
215 // Start of CallGraph SCC passes.
216 if (!DisableUnitAtATime)
217 MPM.add(createPruneEHPass()); // Remove dead EH info
222 if (!DisableUnitAtATime)
223 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
225 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
227 // Start of function pass.
228 // Break up aggregate allocas, using SSAUpdater.
230 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
232 MPM.add(createScalarReplAggregatesPass(-1, false));
233 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
234 MPM.add(createJumpThreadingPass()); // Thread jumps.
235 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
236 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
237 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
238 addExtensionsToPM(EP_Peephole, MPM);
240 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
241 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
242 MPM.add(createReassociatePass()); // Reassociate expressions
243 // Rotate Loop - disable header duplication at -Oz
244 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
245 MPM.add(createLICMPass()); // Hoist loop invariants
246 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
247 MPM.add(createInstructionCombiningPass());
248 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
249 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
250 MPM.add(createLoopDeletionPass()); // Delete dead loops
251 if (EnableLoopInterchange) {
252 MPM.add(createLoopInterchangePass()); // Interchange loops
253 MPM.add(createCFGSimplificationPass());
255 if (!DisableUnrollLoops)
256 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
257 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
261 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
262 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
264 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
265 MPM.add(createSCCPPass()); // Constant prop with SCCP
267 // Delete dead bit computations (instcombine runs after to fold away the dead
268 // computations, and then ADCE will run later to exploit any new DCE
269 // opportunities that creates).
270 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
272 // Run instcombine after redundancy elimination to exploit opportunities
273 // opened up by them.
274 MPM.add(createInstructionCombiningPass());
275 addExtensionsToPM(EP_Peephole, MPM);
276 MPM.add(createJumpThreadingPass()); // Thread jumps
277 MPM.add(createCorrelatedValuePropagationPass());
278 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
279 MPM.add(createLICMPass());
281 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
284 MPM.add(createLoopRerollPass());
285 if (!RunSLPAfterLoopVectorization) {
287 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
290 MPM.add(createBBVectorizePass());
291 MPM.add(createInstructionCombiningPass());
292 addExtensionsToPM(EP_Peephole, MPM);
293 if (OptLevel > 1 && UseGVNAfterVectorization)
294 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
296 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
298 // BBVectorize may have significantly shortened a loop body; unroll again.
299 if (!DisableUnrollLoops)
300 MPM.add(createLoopUnrollPass());
305 MPM.add(createLoadCombinePass());
307 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
308 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
309 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
310 addExtensionsToPM(EP_Peephole, MPM);
312 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
313 // pass manager that we are specifically trying to avoid. To prevent this
314 // we must insert a no-op module pass to reset the pass manager.
315 MPM.add(createBarrierNoopPass());
318 MPM.add(createFloat2IntPass());
320 // Re-rotate loops in all our loop nests. These may have fallout out of
321 // rotated form due to GVN or other transformations, and the vectorizer relies
322 // on the rotated form.
323 MPM.add(createLoopRotatePass());
325 // Distribute loops to allow partial vectorization. I.e. isolate dependences
326 // into separate loop that would otherwise inhibit vectorization.
327 if (EnableLoopDistribute)
328 MPM.add(createLoopDistributePass());
330 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
331 // FIXME: Because of #pragma vectorize enable, the passes below are always
332 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
333 // on -O1 and no #pragma is found). Would be good to have these two passes
334 // as function calls, so that we can only pass them when the vectorizer
336 MPM.add(createInstructionCombiningPass());
337 if (OptLevel > 1 && ExtraVectorizerPasses) {
338 // At higher optimization levels, try to clean up any runtime overlap and
339 // alignment checks inserted by the vectorizer. We want to track correllated
340 // runtime checks for two inner loops in the same outer loop, fold any
341 // common computations, hoist loop-invariant aspects out of any outer loop,
342 // and unswitch the runtime checks if possible. Once hoisted, we may have
343 // dead (or speculatable) control flows or more combining opportunities.
344 MPM.add(createEarlyCSEPass());
345 MPM.add(createCorrelatedValuePropagationPass());
346 MPM.add(createInstructionCombiningPass());
347 MPM.add(createLICMPass());
348 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
349 MPM.add(createCFGSimplificationPass());
350 MPM.add(createInstructionCombiningPass());
353 if (RunSLPAfterLoopVectorization) {
355 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
356 if (OptLevel > 1 && ExtraVectorizerPasses) {
357 MPM.add(createEarlyCSEPass());
362 MPM.add(createBBVectorizePass());
363 MPM.add(createInstructionCombiningPass());
364 addExtensionsToPM(EP_Peephole, MPM);
365 if (OptLevel > 1 && UseGVNAfterVectorization)
366 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
368 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
370 // BBVectorize may have significantly shortened a loop body; unroll again.
371 if (!DisableUnrollLoops)
372 MPM.add(createLoopUnrollPass());
376 addExtensionsToPM(EP_Peephole, MPM);
377 MPM.add(createCFGSimplificationPass());
378 MPM.add(createInstructionCombiningPass());
380 if (!DisableUnrollLoops) {
381 MPM.add(createLoopUnrollPass()); // Unroll small loops
383 // LoopUnroll may generate some redundency to cleanup.
384 MPM.add(createInstructionCombiningPass());
386 // Runtime unrolling will introduce runtime check in loop prologue. If the
387 // unrolled loop is a inner loop, then the prologue will be inside the
388 // outer loop. LICM pass can help to promote the runtime check out if the
389 // checked value is loop invariant.
390 MPM.add(createLICMPass());
393 // After vectorization and unrolling, assume intrinsics may tell us more
394 // about pointer alignments.
395 MPM.add(createAlignmentFromAssumptionsPass());
397 if (!DisableUnitAtATime) {
398 // FIXME: We shouldn't bother with this anymore.
399 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
401 // GlobalOpt already deletes dead functions and globals, at -O2 try a
402 // late pass of GlobalDCE. It is capable of deleting dead cycles.
404 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
405 MPM.add(createConstantMergePass()); // Merge dup global constants
410 MPM.add(createMergeFunctionsPass());
412 addExtensionsToPM(EP_OptimizerLast, MPM);
415 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
416 // Provide AliasAnalysis services for optimizations.
417 addInitialAliasAnalysisPasses(PM);
419 // Propagate constants at call sites into the functions they call. This
420 // opens opportunities for globalopt (and inlining) by substituting function
421 // pointers passed as arguments to direct uses of functions.
422 PM.add(createIPSCCPPass());
424 // Now that we internalized some globals, see if we can hack on them!
425 PM.add(createGlobalOptimizerPass());
427 // Linking modules together can lead to duplicated global constants, only
428 // keep one copy of each constant.
429 PM.add(createConstantMergePass());
431 // Remove unused arguments from functions.
432 PM.add(createDeadArgEliminationPass());
434 // Reduce the code after globalopt and ipsccp. Both can open up significant
435 // simplification opportunities, and both can propagate functions through
436 // function pointers. When this happens, we often have to resolve varargs
437 // calls, etc, so let instcombine do this.
438 PM.add(createInstructionCombiningPass());
439 addExtensionsToPM(EP_Peephole, PM);
441 // Inline small functions
442 bool RunInliner = Inliner;
448 PM.add(createPruneEHPass()); // Remove dead EH info.
450 // Optimize globals again if we ran the inliner.
452 PM.add(createGlobalOptimizerPass());
453 PM.add(createGlobalDCEPass()); // Remove dead functions.
455 // If we didn't decide to inline a function, check to see if we can
456 // transform it to pass arguments by value instead of by reference.
457 PM.add(createArgumentPromotionPass());
459 // The IPO passes may leave cruft around. Clean up after them.
460 PM.add(createInstructionCombiningPass());
461 addExtensionsToPM(EP_Peephole, PM);
462 PM.add(createJumpThreadingPass());
466 PM.add(createSROAPass());
468 PM.add(createScalarReplAggregatesPass());
470 // Run a few AA driven optimizations here and now, to cleanup the code.
471 PM.add(createFunctionAttrsPass()); // Add nocapture.
472 PM.add(createGlobalsModRefPass()); // IP alias analysis.
474 PM.add(createLICMPass()); // Hoist loop invariants.
476 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
477 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
478 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
481 PM.add(createDeadStoreEliminationPass());
483 // More loops are countable; try to optimize them.
484 PM.add(createIndVarSimplifyPass());
485 PM.add(createLoopDeletionPass());
486 if (EnableLoopInterchange)
487 PM.add(createLoopInterchangePass());
489 PM.add(createLoopVectorizePass(true, LoopVectorize));
491 // More scalar chains could be vectorized due to more alias information
492 if (RunSLPAfterLoopVectorization)
494 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
496 // After vectorization, assume intrinsics may tell us more about pointer
498 PM.add(createAlignmentFromAssumptionsPass());
501 PM.add(createLoadCombinePass());
503 // Cleanup and simplify the code after the scalar optimizations.
504 PM.add(createInstructionCombiningPass());
505 addExtensionsToPM(EP_Peephole, PM);
507 PM.add(createJumpThreadingPass());
510 void PassManagerBuilder::addLateLTOOptimizationPasses(
511 legacy::PassManagerBase &PM) {
512 // Delete basic blocks, which optimization passes may have killed.
513 PM.add(createCFGSimplificationPass());
515 // Now that we have optimized the program, discard unreachable functions.
516 PM.add(createGlobalDCEPass());
518 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
519 // currently it damages debug info.
521 PM.add(createMergeFunctionsPass());
524 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
526 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
529 PM.add(createVerifierPass());
532 addLTOOptimizationPasses(PM);
534 // Lower bit sets to globals. This pass supports Clang's control flow
535 // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
536 // is enabled. The pass does nothing if CFI is disabled.
537 PM.add(createLowerBitSetsPass());
540 addLateLTOOptimizationPasses(PM);
543 PM.add(createVerifierPass());
546 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
547 return reinterpret_cast<PassManagerBuilder*>(P);
550 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
551 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
554 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
555 PassManagerBuilder *PMB = new PassManagerBuilder();
559 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
560 PassManagerBuilder *Builder = unwrap(PMB);
565 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
567 PassManagerBuilder *Builder = unwrap(PMB);
568 Builder->OptLevel = OptLevel;
572 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
573 unsigned SizeLevel) {
574 PassManagerBuilder *Builder = unwrap(PMB);
575 Builder->SizeLevel = SizeLevel;
579 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
581 PassManagerBuilder *Builder = unwrap(PMB);
582 Builder->DisableUnitAtATime = Value;
586 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
588 PassManagerBuilder *Builder = unwrap(PMB);
589 Builder->DisableUnrollLoops = Value;
593 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
595 // NOTE: The simplify-libcalls pass has been removed.
599 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
600 unsigned Threshold) {
601 PassManagerBuilder *Builder = unwrap(PMB);
602 Builder->Inliner = createFunctionInliningPass(Threshold);
606 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
607 LLVMPassManagerRef PM) {
608 PassManagerBuilder *Builder = unwrap(PMB);
609 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
610 Builder->populateFunctionPassManager(*FPM);
614 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
615 LLVMPassManagerRef PM) {
616 PassManagerBuilder *Builder = unwrap(PMB);
617 legacy::PassManagerBase *MPM = unwrap(PM);
618 Builder->populateModulePassManager(*MPM);
621 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
622 LLVMPassManagerRef PM,
623 LLVMBool Internalize,
624 LLVMBool RunInliner) {
625 PassManagerBuilder *Builder = unwrap(PMB);
626 legacy::PassManagerBase *LPM = unwrap(PM);
628 // A small backwards compatibility hack. populateLTOPassManager used to take
629 // an RunInliner option.
630 if (RunInliner && !Builder->Inliner)
631 Builder->Inliner = createFunctionInliningPass();
633 Builder->populateLTOPassManager(*LPM);