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"));
62 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
64 cl::desc("Run the load combining pass"));
67 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
68 cl::init(true), cl::Hidden,
69 cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
70 "vectorizer instead of before"));
72 static cl::opt<bool> UseCFLAA("use-cfl-aa",
73 cl::init(false), cl::Hidden,
74 cl::desc("Enable the new, experimental CFL alias analysis"));
77 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
78 cl::desc("Enable motion of merged load and store"));
80 static cl::opt<bool> EnableLoopInterchange(
81 "enable-loopinterchange", cl::init(false), cl::Hidden,
82 cl::desc("Enable the new, experimental LoopInterchange Pass"));
84 PassManagerBuilder::PassManagerBuilder() {
87 LibraryInfo = nullptr;
89 DisableTailCalls = false;
90 DisableUnitAtATime = false;
91 DisableUnrollLoops = false;
92 BBVectorize = RunBBVectorization;
93 SLPVectorize = RunSLPVectorization;
94 LoopVectorize = RunLoopVectorization;
95 RerollLoops = RunLoopRerolling;
96 LoadCombine = RunLoadCombine;
97 DisableGVNLoadPRE = false;
100 MergeFunctions = false;
103 PassManagerBuilder::~PassManagerBuilder() {
108 /// Set of global extensions, automatically added as part of the standard set.
109 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
110 PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
112 void PassManagerBuilder::addGlobalExtension(
113 PassManagerBuilder::ExtensionPointTy Ty,
114 PassManagerBuilder::ExtensionFn Fn) {
115 GlobalExtensions->push_back(std::make_pair(Ty, Fn));
118 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
119 Extensions.push_back(std::make_pair(Ty, Fn));
122 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
123 legacy::PassManagerBase &PM) const {
124 for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
125 if ((*GlobalExtensions)[i].first == ETy)
126 (*GlobalExtensions)[i].second(*this, PM);
127 for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
128 if (Extensions[i].first == ETy)
129 Extensions[i].second(*this, PM);
132 void PassManagerBuilder::addInitialAliasAnalysisPasses(
133 legacy::PassManagerBase &PM) const {
134 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
135 // BasicAliasAnalysis wins if they disagree. This is intended to help
136 // support "obvious" type-punning idioms.
138 PM.add(createCFLAliasAnalysisPass());
139 PM.add(createTypeBasedAliasAnalysisPass());
140 PM.add(createScopedNoAliasAAPass());
141 PM.add(createBasicAliasAnalysisPass());
144 void PassManagerBuilder::populateFunctionPassManager(
145 legacy::FunctionPassManager &FPM) {
146 addExtensionsToPM(EP_EarlyAsPossible, FPM);
148 // Add LibraryInfo if we have some.
150 FPM.add(new TargetLibraryInfoWrapperPass(*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(
166 legacy::PassManagerBase &MPM) {
167 // If all optimizations are disabled, just run the always-inline pass and,
168 // if enabled, the function merging pass.
175 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
176 // creates a CGSCC pass manager, but we don't want to add extensions into
177 // that pass manager. To prevent this we insert a no-op module pass to reset
178 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
179 // builds. The function merging pass is
181 MPM.add(createMergeFunctionsPass());
182 else if (!GlobalExtensions->empty() || !Extensions.empty())
183 MPM.add(createBarrierNoopPass());
185 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
189 // Add LibraryInfo if we have some.
191 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
193 addInitialAliasAnalysisPasses(MPM);
195 if (!DisableUnitAtATime) {
196 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
198 MPM.add(createIPSCCPPass()); // IP SCCP
199 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
201 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
203 MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
204 addExtensionsToPM(EP_Peephole, MPM);
205 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
208 // Start of CallGraph SCC passes.
209 if (!DisableUnitAtATime)
210 MPM.add(createPruneEHPass()); // Remove dead EH info
215 if (!DisableUnitAtATime)
216 MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
218 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
220 // Start of function pass.
221 // Break up aggregate allocas, using SSAUpdater.
223 MPM.add(createSROAPass(/*RequiresDomTree*/ false));
225 MPM.add(createScalarReplAggregatesPass(-1, false));
226 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
227 MPM.add(createJumpThreadingPass()); // Thread jumps.
228 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
229 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
230 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
231 addExtensionsToPM(EP_Peephole, MPM);
233 if (!DisableTailCalls)
234 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
235 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
236 MPM.add(createReassociatePass()); // Reassociate expressions
237 // Rotate Loop - disable header duplication at -Oz
238 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
239 MPM.add(createLICMPass()); // Hoist loop invariants
240 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
241 MPM.add(createInstructionCombiningPass());
242 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
243 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
244 MPM.add(createLoopDeletionPass()); // Delete dead loops
245 if (EnableLoopInterchange)
246 MPM.add(createLoopInterchangePass()); // Interchange loops
248 if (!DisableUnrollLoops)
249 MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
250 addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
254 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
255 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
257 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
258 MPM.add(createSCCPPass()); // Constant prop with SCCP
260 // Delete dead bit computations (instcombine runs after to fold away the dead
261 // computations, and then ADCE will run later to exploit any new DCE
262 // opportunities that creates).
263 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
265 // Run instcombine after redundancy elimination to exploit opportunities
266 // opened up by them.
267 MPM.add(createInstructionCombiningPass());
268 addExtensionsToPM(EP_Peephole, MPM);
269 MPM.add(createJumpThreadingPass()); // Thread jumps
270 MPM.add(createCorrelatedValuePropagationPass());
271 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
272 MPM.add(createLICMPass());
274 addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
277 MPM.add(createLoopRerollPass());
278 if (!RunSLPAfterLoopVectorization) {
280 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
283 MPM.add(createBBVectorizePass());
284 MPM.add(createInstructionCombiningPass());
285 addExtensionsToPM(EP_Peephole, MPM);
286 if (OptLevel > 1 && UseGVNAfterVectorization)
287 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
289 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
291 // BBVectorize may have significantly shortened a loop body; unroll again.
292 if (!DisableUnrollLoops)
293 MPM.add(createLoopUnrollPass());
298 MPM.add(createLoadCombinePass());
300 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
301 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
302 MPM.add(createInstructionCombiningPass()); // Clean up after everything.
303 addExtensionsToPM(EP_Peephole, MPM);
305 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
306 // pass manager that we are specifically trying to avoid. To prevent this
307 // we must insert a no-op module pass to reset the pass manager.
308 MPM.add(createBarrierNoopPass());
310 // Re-rotate loops in all our loop nests. These may have fallout out of
311 // rotated form due to GVN or other transformations, and the vectorizer relies
312 // on the rotated form.
313 MPM.add(createLoopRotatePass());
315 MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
316 // FIXME: Because of #pragma vectorize enable, the passes below are always
317 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
318 // on -O1 and no #pragma is found). Would be good to have these two passes
319 // as function calls, so that we can only pass them when the vectorizer
321 MPM.add(createInstructionCombiningPass());
322 if (OptLevel > 1 && ExtraVectorizerPasses) {
323 // At higher optimization levels, try to clean up any runtime overlap and
324 // alignment checks inserted by the vectorizer. We want to track correllated
325 // runtime checks for two inner loops in the same outer loop, fold any
326 // common computations, hoist loop-invariant aspects out of any outer loop,
327 // and unswitch the runtime checks if possible. Once hoisted, we may have
328 // dead (or speculatable) control flows or more combining opportunities.
329 MPM.add(createEarlyCSEPass());
330 MPM.add(createCorrelatedValuePropagationPass());
331 MPM.add(createInstructionCombiningPass());
332 MPM.add(createLICMPass());
333 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
334 MPM.add(createCFGSimplificationPass());
335 MPM.add(createInstructionCombiningPass());
338 if (RunSLPAfterLoopVectorization) {
340 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
341 if (OptLevel > 1 && ExtraVectorizerPasses) {
342 MPM.add(createEarlyCSEPass());
347 MPM.add(createBBVectorizePass());
348 MPM.add(createInstructionCombiningPass());
349 addExtensionsToPM(EP_Peephole, MPM);
350 if (OptLevel > 1 && UseGVNAfterVectorization)
351 MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
353 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
355 // BBVectorize may have significantly shortened a loop body; unroll again.
356 if (!DisableUnrollLoops)
357 MPM.add(createLoopUnrollPass());
361 addExtensionsToPM(EP_Peephole, MPM);
362 MPM.add(createCFGSimplificationPass());
363 MPM.add(createInstructionCombiningPass());
365 if (!DisableUnrollLoops) {
366 MPM.add(createLoopUnrollPass()); // Unroll small loops
368 // This is a barrier pass to avoid combine LICM pass and loop unroll pass
369 // within same loop pass manager.
370 MPM.add(createInstructionSimplifierPass());
372 // Runtime unrolling will introduce runtime check in loop prologue. If the
373 // unrolled loop is a inner loop, then the prologue will be inside the
374 // outer loop. LICM pass can help to promote the runtime check out if the
375 // checked value is loop invariant.
376 MPM.add(createLICMPass());
379 // After vectorization and unrolling, assume intrinsics may tell us more
380 // about pointer alignments.
381 MPM.add(createAlignmentFromAssumptionsPass());
383 if (!DisableUnitAtATime) {
384 // FIXME: We shouldn't bother with this anymore.
385 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
387 // GlobalOpt already deletes dead functions and globals, at -O2 try a
388 // late pass of GlobalDCE. It is capable of deleting dead cycles.
390 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
391 MPM.add(createConstantMergePass()); // Merge dup global constants
396 MPM.add(createMergeFunctionsPass());
398 addExtensionsToPM(EP_OptimizerLast, MPM);
401 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
402 // Provide AliasAnalysis services for optimizations.
403 addInitialAliasAnalysisPasses(PM);
405 // Propagate constants at call sites into the functions they call. This
406 // opens opportunities for globalopt (and inlining) by substituting function
407 // pointers passed as arguments to direct uses of functions.
408 PM.add(createIPSCCPPass());
410 // Now that we internalized some globals, see if we can hack on them!
411 PM.add(createGlobalOptimizerPass());
413 // Linking modules together can lead to duplicated global constants, only
414 // keep one copy of each constant.
415 PM.add(createConstantMergePass());
417 // Remove unused arguments from functions.
418 PM.add(createDeadArgEliminationPass());
420 // Reduce the code after globalopt and ipsccp. Both can open up significant
421 // simplification opportunities, and both can propagate functions through
422 // function pointers. When this happens, we often have to resolve varargs
423 // calls, etc, so let instcombine do this.
424 PM.add(createInstructionCombiningPass());
425 addExtensionsToPM(EP_Peephole, PM);
427 // Inline small functions
428 bool RunInliner = Inliner;
434 PM.add(createPruneEHPass()); // Remove dead EH info.
436 // Optimize globals again if we ran the inliner.
438 PM.add(createGlobalOptimizerPass());
439 PM.add(createGlobalDCEPass()); // Remove dead functions.
441 // If we didn't decide to inline a function, check to see if we can
442 // transform it to pass arguments by value instead of by reference.
443 PM.add(createArgumentPromotionPass());
445 // The IPO passes may leave cruft around. Clean up after them.
446 PM.add(createInstructionCombiningPass());
447 addExtensionsToPM(EP_Peephole, PM);
448 PM.add(createJumpThreadingPass());
452 PM.add(createSROAPass());
454 PM.add(createScalarReplAggregatesPass());
456 // Run a few AA driven optimizations here and now, to cleanup the code.
457 PM.add(createFunctionAttrsPass()); // Add nocapture.
458 PM.add(createGlobalsModRefPass()); // IP alias analysis.
460 PM.add(createLICMPass()); // Hoist loop invariants.
462 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
463 PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
464 PM.add(createMemCpyOptPass()); // Remove dead memcpys.
467 PM.add(createDeadStoreEliminationPass());
469 // More loops are countable; try to optimize them.
470 PM.add(createIndVarSimplifyPass());
471 PM.add(createLoopDeletionPass());
472 if (EnableLoopInterchange)
473 PM.add(createLoopInterchangePass());
475 PM.add(createLoopVectorizePass(true, LoopVectorize));
477 // More scalar chains could be vectorized due to more alias information
478 if (RunSLPAfterLoopVectorization)
480 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
482 // After vectorization, assume intrinsics may tell us more about pointer
484 PM.add(createAlignmentFromAssumptionsPass());
487 PM.add(createLoadCombinePass());
489 // Cleanup and simplify the code after the scalar optimizations.
490 PM.add(createInstructionCombiningPass());
491 addExtensionsToPM(EP_Peephole, PM);
493 PM.add(createJumpThreadingPass());
496 void PassManagerBuilder::addLateLTOOptimizationPasses(
497 legacy::PassManagerBase &PM) {
498 // Delete basic blocks, which optimization passes may have killed.
499 PM.add(createCFGSimplificationPass());
501 // Now that we have optimized the program, discard unreachable functions.
502 PM.add(createGlobalDCEPass());
504 // FIXME: this is profitable (for compiler time) to do at -O0 too, but
505 // currently it damages debug info.
507 PM.add(createMergeFunctionsPass());
510 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
512 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
515 PM.add(createVerifierPass());
516 PM.add(createDebugInfoVerifierPass());
520 addLTOOptimizationPasses(PM);
522 // Lower bit sets to globals. This pass supports Clang's control flow
523 // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
524 // is enabled. The pass does nothing if CFI is disabled.
525 PM.add(createLowerBitSetsPass());
528 addLateLTOOptimizationPasses(PM);
531 PM.add(createVerifierPass());
532 PM.add(createDebugInfoVerifierPass());
536 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
537 return reinterpret_cast<PassManagerBuilder*>(P);
540 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
541 return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
544 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
545 PassManagerBuilder *PMB = new PassManagerBuilder();
549 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
550 PassManagerBuilder *Builder = unwrap(PMB);
555 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
557 PassManagerBuilder *Builder = unwrap(PMB);
558 Builder->OptLevel = OptLevel;
562 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
563 unsigned SizeLevel) {
564 PassManagerBuilder *Builder = unwrap(PMB);
565 Builder->SizeLevel = SizeLevel;
569 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
571 PassManagerBuilder *Builder = unwrap(PMB);
572 Builder->DisableUnitAtATime = Value;
576 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
578 PassManagerBuilder *Builder = unwrap(PMB);
579 Builder->DisableUnrollLoops = Value;
583 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
585 // NOTE: The simplify-libcalls pass has been removed.
589 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
590 unsigned Threshold) {
591 PassManagerBuilder *Builder = unwrap(PMB);
592 Builder->Inliner = createFunctionInliningPass(Threshold);
596 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
597 LLVMPassManagerRef PM) {
598 PassManagerBuilder *Builder = unwrap(PMB);
599 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
600 Builder->populateFunctionPassManager(*FPM);
604 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
605 LLVMPassManagerRef PM) {
606 PassManagerBuilder *Builder = unwrap(PMB);
607 legacy::PassManagerBase *MPM = unwrap(PM);
608 Builder->populateModulePassManager(*MPM);
611 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
612 LLVMPassManagerRef PM,
613 LLVMBool Internalize,
614 LLVMBool RunInliner) {
615 PassManagerBuilder *Builder = unwrap(PMB);
616 legacy::PassManagerBase *LPM = unwrap(PM);
618 // A small backwards compatibility hack. populateLTOPassManager used to take
619 // an RunInliner option.
620 if (RunInliner && !Builder->Inliner)
621 Builder->Inliner = createFunctionInliningPass();
623 Builder->populateLTOPassManager(*LPM);