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 PassManagerBuilder::PassManagerBuilder() {
91 LibraryInfo = nullptr;
93 DisableTailCalls = false;
94 DisableUnitAtATime = false;
95 DisableUnrollLoops = false;
96 BBVectorize = RunBBVectorization;
97 SLPVectorize = RunSLPVectorization;
98 LoopVectorize = RunLoopVectorization;
99 RerollLoops = RunLoopRerolling;
100 LoadCombine = RunLoadCombine;
101 DisableGVNLoadPRE = false;
103 VerifyOutput = false;
104 MergeFunctions = false;
107 PassManagerBuilder::~PassManagerBuilder() {
112 /// Set of global extensions, automatically added as part of the standard set.
113 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
114 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
116 void PassManagerBuilder::addGlobalExtension(
117 PassManagerBuilder::ExtensionPointTy Ty,
118 PassManagerBuilder::ExtensionFn Fn) {
119 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
122 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
123 Extensions.push_back(std::make_pair(Ty, Fn));
126 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
127 legacy::PassManagerBase &PM) const {
128 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
129 if ((*GlobalExtensions)[i].first == ETy)
130 (*GlobalExtensions)[i].second(*this, PM);
131 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
132 if (Extensions[i].first == ETy)
133 Extensions[i].second(*this, PM);
136 void PassManagerBuilder::addInitialAliasAnalysisPasses(
137 legacy::PassManagerBase &PM) const {
138 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
139 // BasicAliasAnalysis wins if they disagree. This is intended to help
140 // support "obvious" type-punning idioms.
142 PM.add(createCFLAliasAnalysisPass());
143 PM.add(createTypeBasedAliasAnalysisPass());
144 PM.add(createScopedNoAliasAAPass());
145 PM.add(createBasicAliasAnalysisPass());
148 void PassManagerBuilder::populateFunctionPassManager(
149 legacy::FunctionPassManager &FPM) {
150 addExtensionsToPM(EP_EarlyAsPossible, FPM);
152 // Add LibraryInfo if we have some.
154 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
156 if (OptLevel == 0) return;
158 addInitialAliasAnalysisPasses(FPM);
160 FPM.add(createCFGSimplificationPass());
162 FPM.add(createSROAPass());
164 FPM.add(createScalarReplAggregatesPass());
165 FPM.add(createEarlyCSEPass());
166 FPM.add(createLowerExpectIntrinsicPass());
169 void PassManagerBuilder::populateModulePassManager(
170 legacy::PassManagerBase &MPM) {
171 // If all optimizations are disabled, just run the always-inline pass and,
172 // if enabled, the function merging pass.
179 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
180 // creates a CGSCC pass manager, but we don't want to add extensions into
181 // that pass manager. To prevent this we insert a no-op module pass to reset
182 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
183 // builds. The function merging pass is
185 MPM.add(createMergeFunctionsPass());
186 else if (!GlobalExtensions->empty() || !Extensions.empty())
187 MPM.add(createBarrierNoopPass());
189 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
193 // Add LibraryInfo if we have some.
195 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
197 addInitialAliasAnalysisPasses(MPM);
199 if (!DisableUnitAtATime) {
200 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
202 MPM.add(createIPSCCPPass()); // IP SCCP
203 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
205 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
207 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
208 addExtensionsToPM(EP_Peephole, MPM);
209 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
212 // Start of CallGraph SCC passes.
213 if (!DisableUnitAtATime)
214 MPM.add(createPruneEHPass()); // Remove dead EH info
219 if (!DisableUnitAtATime)
220 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
222 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
224 // Start of function pass.
225 // Break up aggregate allocas, using SSAUpdater.
227 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
229 MPM.add(createScalarReplAggregatesPass(-1, false));
230 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
231 MPM.add(createJumpThreadingPass()); // Thread jumps.
232 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
233 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
234 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
235 addExtensionsToPM(EP_Peephole, MPM);
237 if (!DisableTailCalls)
238 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
239 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
240 MPM.add(createReassociatePass()); // Reassociate expressions
241 // Rotate Loop - disable header duplication at -Oz
242 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
243 MPM.add(createLICMPass()); // Hoist loop invariants
244 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
245 MPM.add(createInstructionCombiningPass());
246 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
247 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
248 MPM.add(createLoopDeletionPass()); // Delete dead loops
249 if (EnableLoopInterchange)
250 MPM.add(createLoopInterchangePass()); // Interchange loops
252 if (!DisableUnrollLoops)
253 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
254 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
258 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
259 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
261 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
262 MPM.add(createSCCPPass()); // Constant prop with SCCP
264 // Delete dead bit computations (instcombine runs after to fold away the dead
265 // computations, and then ADCE will run later to exploit any new DCE
266 // opportunities that creates).
267 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
269 // Run instcombine after redundancy elimination to exploit opportunities
270 // opened up by them.
271 MPM.add(createInstructionCombiningPass());
272 addExtensionsToPM(EP_Peephole, MPM);
273 MPM.add(createJumpThreadingPass()); // Thread jumps
274 MPM.add(createCorrelatedValuePropagationPass());
275 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
276 MPM.add(createLICMPass());
278 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
281 MPM.add(createLoopRerollPass());
282 if (!RunSLPAfterLoopVectorization) {
284 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
287 MPM.add(createBBVectorizePass());
288 MPM.add(createInstructionCombiningPass());
289 addExtensionsToPM(EP_Peephole, MPM);
290 if (OptLevel > 1 && UseGVNAfterVectorization)
291 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
293 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
295 // BBVectorize may have significantly shortened a loop body; unroll again.
296 if (!DisableUnrollLoops)
297 MPM.add(createLoopUnrollPass());
302 MPM.add(createLoadCombinePass());
304 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
305 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
306 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
307 addExtensionsToPM(EP_Peephole, MPM);
309 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
310 // pass manager that we are specifically trying to avoid. To prevent this
311 // we must insert a no-op module pass to reset the pass manager.
312 MPM.add(createBarrierNoopPass());
315 MPM.add(createFloat2IntPass());
317 // Re-rotate loops in all our loop nests. These may have fallout out of
318 // rotated form due to GVN or other transformations, and the vectorizer relies
319 // on the rotated form.
320 MPM.add(createLoopRotatePass());
322 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
323 // FIXME: Because of #pragma vectorize enable, the passes below are always
324 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
325 // on -O1 and no #pragma is found). Would be good to have these two passes
326 // as function calls, so that we can only pass them when the vectorizer
328 MPM.add(createInstructionCombiningPass());
329 if (OptLevel > 1 && ExtraVectorizerPasses) {
330 // At higher optimization levels, try to clean up any runtime overlap and
331 // alignment checks inserted by the vectorizer. We want to track correllated
332 // runtime checks for two inner loops in the same outer loop, fold any
333 // common computations, hoist loop-invariant aspects out of any outer loop,
334 // and unswitch the runtime checks if possible. Once hoisted, we may have
335 // dead (or speculatable) control flows or more combining opportunities.
336 MPM.add(createEarlyCSEPass());
337 MPM.add(createCorrelatedValuePropagationPass());
338 MPM.add(createInstructionCombiningPass());
339 MPM.add(createLICMPass());
340 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
341 MPM.add(createCFGSimplificationPass());
342 MPM.add(createInstructionCombiningPass());
345 if (RunSLPAfterLoopVectorization) {
347 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
348 if (OptLevel > 1 && ExtraVectorizerPasses) {
349 MPM.add(createEarlyCSEPass());
354 MPM.add(createBBVectorizePass());
355 MPM.add(createInstructionCombiningPass());
356 addExtensionsToPM(EP_Peephole, MPM);
357 if (OptLevel > 1 && UseGVNAfterVectorization)
358 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
360 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
362 // BBVectorize may have significantly shortened a loop body; unroll again.
363 if (!DisableUnrollLoops)
364 MPM.add(createLoopUnrollPass());
368 addExtensionsToPM(EP_Peephole, MPM);
369 MPM.add(createCFGSimplificationPass());
370 MPM.add(createInstructionCombiningPass());
372 if (!DisableUnrollLoops) {
373 MPM.add(createLoopUnrollPass()); // Unroll small loops
375 // This is a barrier pass to avoid combine LICM pass and loop unroll pass
376 // within same loop pass manager.
377 MPM.add(createInstructionSimplifierPass());
379 // Runtime unrolling will introduce runtime check in loop prologue. If the
380 // unrolled loop is a inner loop, then the prologue will be inside the
381 // outer loop. LICM pass can help to promote the runtime check out if the
382 // checked value is loop invariant.
383 MPM.add(createLICMPass());
386 // After vectorization and unrolling, assume intrinsics may tell us more
387 // about pointer alignments.
388 MPM.add(createAlignmentFromAssumptionsPass());
390 if (!DisableUnitAtATime) {
391 // FIXME: We shouldn't bother with this anymore.
392 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
394 // GlobalOpt already deletes dead functions and globals, at -O2 try a
395 // late pass of GlobalDCE. It is capable of deleting dead cycles.
397 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
398 MPM.add(createConstantMergePass()); // Merge dup global constants
403 MPM.add(createMergeFunctionsPass());
405 addExtensionsToPM(EP_OptimizerLast, MPM);
408 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
409 // Provide AliasAnalysis services for optimizations.
410 addInitialAliasAnalysisPasses(PM);
412 // Propagate constants at call sites into the functions they call. This
413 // opens opportunities for globalopt (and inlining) by substituting function
414 // pointers passed as arguments to direct uses of functions.
415 PM.add(createIPSCCPPass());
417 // Now that we internalized some globals, see if we can hack on them!
418 PM.add(createGlobalOptimizerPass());
420 // Linking modules together can lead to duplicated global constants, only
421 // keep one copy of each constant.
422 PM.add(createConstantMergePass());
424 // Remove unused arguments from functions.
425 PM.add(createDeadArgEliminationPass());
427 // Reduce the code after globalopt and ipsccp. Both can open up significant
428 // simplification opportunities, and both can propagate functions through
429 // function pointers. When this happens, we often have to resolve varargs
430 // calls, etc, so let instcombine do this.
431 PM.add(createInstructionCombiningPass());
432 addExtensionsToPM(EP_Peephole, PM);
434 // Inline small functions
435 bool RunInliner = Inliner;
441 PM.add(createPruneEHPass()); // Remove dead EH info.
443 // Optimize globals again if we ran the inliner.
445 PM.add(createGlobalOptimizerPass());
446 PM.add(createGlobalDCEPass()); // Remove dead functions.
448 // If we didn't decide to inline a function, check to see if we can
449 // transform it to pass arguments by value instead of by reference.
450 PM.add(createArgumentPromotionPass());
452 // The IPO passes may leave cruft around. Clean up after them.
453 PM.add(createInstructionCombiningPass());
454 addExtensionsToPM(EP_Peephole, PM);
455 PM.add(createJumpThreadingPass());
459 PM.add(createSROAPass());
461 PM.add(createScalarReplAggregatesPass());
463 // Run a few AA driven optimizations here and now, to cleanup the code.
464 PM.add(createFunctionAttrsPass()); // Add nocapture.
465 PM.add(createGlobalsModRefPass()); // IP alias analysis.
467 PM.add(createLICMPass()); // Hoist loop invariants.
469 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
470 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
471 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
474 PM.add(createDeadStoreEliminationPass());
476 // More loops are countable; try to optimize them.
477 PM.add(createIndVarSimplifyPass());
478 PM.add(createLoopDeletionPass());
479 if (EnableLoopInterchange)
480 PM.add(createLoopInterchangePass());
482 PM.add(createLoopVectorizePass(true, LoopVectorize));
484 // More scalar chains could be vectorized due to more alias information
485 if (RunSLPAfterLoopVectorization)
487 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
489 // After vectorization, assume intrinsics may tell us more about pointer
491 PM.add(createAlignmentFromAssumptionsPass());
494 PM.add(createLoadCombinePass());
496 // Cleanup and simplify the code after the scalar optimizations.
497 PM.add(createInstructionCombiningPass());
498 addExtensionsToPM(EP_Peephole, PM);
500 PM.add(createJumpThreadingPass());
503 void PassManagerBuilder::addLateLTOOptimizationPasses(
504 legacy::PassManagerBase &PM) {
505 // Delete basic blocks, which optimization passes may have killed.
506 PM.add(createCFGSimplificationPass());
508 // Now that we have optimized the program, discard unreachable functions.
509 PM.add(createGlobalDCEPass());
511 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
512 // currently it damages debug info.
514 PM.add(createMergeFunctionsPass());
517 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
519 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
522 PM.add(createVerifierPass());
525 addLTOOptimizationPasses(PM);
527 // Lower bit sets to globals. This pass supports Clang's control flow
528 // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
529 // is enabled. The pass does nothing if CFI is disabled.
530 PM.add(createLowerBitSetsPass());
533 addLateLTOOptimizationPasses(PM);
536 PM.add(createVerifierPass());
539 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
540 return reinterpret_cast<PassManagerBuilder*>(P);
543 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
544 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
547 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
548 PassManagerBuilder *PMB = new PassManagerBuilder();
552 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
553 PassManagerBuilder *Builder = unwrap(PMB);
558 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
560 PassManagerBuilder *Builder = unwrap(PMB);
561 Builder->OptLevel = OptLevel;
565 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
566 unsigned SizeLevel) {
567 PassManagerBuilder *Builder = unwrap(PMB);
568 Builder->SizeLevel = SizeLevel;
572 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
574 PassManagerBuilder *Builder = unwrap(PMB);
575 Builder->DisableUnitAtATime = Value;
579 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
581 PassManagerBuilder *Builder = unwrap(PMB);
582 Builder->DisableUnrollLoops = Value;
586 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
588 // NOTE: The simplify-libcalls pass has been removed.
592 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
593 unsigned Threshold) {
594 PassManagerBuilder *Builder = unwrap(PMB);
595 Builder->Inliner = createFunctionInliningPass(Threshold);
599 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
600 LLVMPassManagerRef PM) {
601 PassManagerBuilder *Builder = unwrap(PMB);
602 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
603 Builder->populateFunctionPassManager(*FPM);
607 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
608 LLVMPassManagerRef PM) {
609 PassManagerBuilder *Builder = unwrap(PMB);
610 legacy::PassManagerBase *MPM = unwrap(PM);
611 Builder->populateModulePassManager(*MPM);
614 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
615 LLVMPassManagerRef PM,
616 LLVMBool Internalize,
617 LLVMBool RunInliner) {
618 PassManagerBuilder *Builder = unwrap(PMB);
619 legacy::PassManagerBase *LPM = unwrap(PM);
621 // A small backwards compatibility hack. populateLTOPassManager used to take
622 // an RunInliner option.
623 if (RunInliner && !Builder->Inliner)
624 Builder->Inliner = createFunctionInliningPass();
626 Builder->populateLTOPassManager(*LPM);