[PM/AA] Extract a minimal interface for CFLAA to its own header file.
[oota-llvm.git] / lib / Transforms / IPO / PassManagerBuilder.cpp
1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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++.
12 //
13 //===----------------------------------------------------------------------===//
14
15
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/BasicAliasAnalysis.h"
26 #include "llvm/Analysis/CFLAliasAnalysis.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Vectorize.h"
32
33 using namespace llvm;
34
35 static cl::opt<bool>
36 RunLoopVectorization("vectorize-loops", cl::Hidden,
37                      cl::desc("Run the Loop vectorization passes"));
38
39 static cl::opt<bool>
40 RunSLPVectorization("vectorize-slp", cl::Hidden,
41                     cl::desc("Run the SLP vectorization passes"));
42
43 static cl::opt<bool>
44 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
45                     cl::desc("Run the BB vectorization passes"));
46
47 static cl::opt<bool>
48 UseGVNAfterVectorization("use-gvn-after-vectorization",
49   cl::init(false), cl::Hidden,
50   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
51
52 static cl::opt<bool> ExtraVectorizerPasses(
53     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
54     cl::desc("Run cleanup optimization passes after vectorization."));
55
56 static cl::opt<bool> UseNewSROA("use-new-sroa",
57   cl::init(true), cl::Hidden,
58   cl::desc("Enable the new, experimental SROA pass"));
59
60 static cl::opt<bool>
61 RunLoopRerolling("reroll-loops", cl::Hidden,
62                  cl::desc("Run the loop rerolling pass"));
63
64 static cl::opt<bool>
65 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
66              cl::desc("Run the float2int (float demotion) pass"));
67
68 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
69                                     cl::Hidden,
70                                     cl::desc("Run the load combining pass"));
71
72 static cl::opt<bool>
73 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
74   cl::init(true), cl::Hidden,
75   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
76            "vectorizer instead of before"));
77
78 static cl::opt<bool> UseCFLAA("use-cfl-aa",
79   cl::init(false), cl::Hidden,
80   cl::desc("Enable the new, experimental CFL alias analysis"));
81
82 static cl::opt<bool>
83 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
84            cl::desc("Enable motion of merged load and store"));
85
86 static cl::opt<bool> EnableLoopInterchange(
87     "enable-loopinterchange", cl::init(false), cl::Hidden,
88     cl::desc("Enable the new, experimental LoopInterchange Pass"));
89
90 static cl::opt<bool> EnableLoopDistribute(
91     "enable-loop-distribute", cl::init(false), cl::Hidden,
92     cl::desc("Enable the new, experimental LoopDistribution Pass"));
93
94 static cl::opt<bool> EnableNonLTOGlobalsModRef(
95     "enable-non-lto-gmr", cl::init(false), cl::Hidden,
96     cl::desc(
97         "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline."));
98
99 PassManagerBuilder::PassManagerBuilder() {
100     OptLevel = 2;
101     SizeLevel = 0;
102     LibraryInfo = nullptr;
103     Inliner = nullptr;
104     DisableUnitAtATime = false;
105     DisableUnrollLoops = false;
106     BBVectorize = RunBBVectorization;
107     SLPVectorize = RunSLPVectorization;
108     LoopVectorize = RunLoopVectorization;
109     RerollLoops = RunLoopRerolling;
110     LoadCombine = RunLoadCombine;
111     DisableGVNLoadPRE = false;
112     VerifyInput = false;
113     VerifyOutput = false;
114     MergeFunctions = false;
115     PrepareForLTO = false;
116 }
117
118 PassManagerBuilder::~PassManagerBuilder() {
119   delete LibraryInfo;
120   delete Inliner;
121 }
122
123 /// Set of global extensions, automatically added as part of the standard set.
124 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
125    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
126
127 void PassManagerBuilder::addGlobalExtension(
128     PassManagerBuilder::ExtensionPointTy Ty,
129     PassManagerBuilder::ExtensionFn Fn) {
130   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
131 }
132
133 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
134   Extensions.push_back(std::make_pair(Ty, Fn));
135 }
136
137 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
138                                            legacy::PassManagerBase &PM) const {
139   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
140     if ((*GlobalExtensions)[i].first == ETy)
141       (*GlobalExtensions)[i].second(*this, PM);
142   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
143     if (Extensions[i].first == ETy)
144       Extensions[i].second(*this, PM);
145 }
146
147 void PassManagerBuilder::addInitialAliasAnalysisPasses(
148     legacy::PassManagerBase &PM) const {
149   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
150   // BasicAliasAnalysis wins if they disagree. This is intended to help
151   // support "obvious" type-punning idioms.
152   if (UseCFLAA)
153     PM.add(createCFLAliasAnalysisPass());
154   PM.add(createTypeBasedAliasAnalysisPass());
155   PM.add(createScopedNoAliasAAPass());
156   PM.add(createBasicAliasAnalysisPass());
157 }
158
159 void PassManagerBuilder::populateFunctionPassManager(
160     legacy::FunctionPassManager &FPM) {
161   addExtensionsToPM(EP_EarlyAsPossible, FPM);
162
163   // Add LibraryInfo if we have some.
164   if (LibraryInfo)
165     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
166
167   if (OptLevel == 0) return;
168
169   addInitialAliasAnalysisPasses(FPM);
170
171   FPM.add(createCFGSimplificationPass());
172   if (UseNewSROA)
173     FPM.add(createSROAPass());
174   else
175     FPM.add(createScalarReplAggregatesPass());
176   FPM.add(createEarlyCSEPass());
177   FPM.add(createLowerExpectIntrinsicPass());
178 }
179
180 void PassManagerBuilder::populateModulePassManager(
181     legacy::PassManagerBase &MPM) {
182   // If all optimizations are disabled, just run the always-inline pass and,
183   // if enabled, the function merging pass.
184   if (OptLevel == 0) {
185     if (Inliner) {
186       MPM.add(Inliner);
187       Inliner = nullptr;
188     }
189
190     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
191     // creates a CGSCC pass manager, but we don't want to add extensions into
192     // that pass manager. To prevent this we insert a no-op module pass to reset
193     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
194     // builds. The function merging pass is 
195     if (MergeFunctions)
196       MPM.add(createMergeFunctionsPass());
197     else if (!GlobalExtensions->empty() || !Extensions.empty())
198       MPM.add(createBarrierNoopPass());
199
200     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
201     return;
202   }
203
204   // Add LibraryInfo if we have some.
205   if (LibraryInfo)
206     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
207
208   addInitialAliasAnalysisPasses(MPM);
209
210   if (!DisableUnitAtATime) {
211     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
212
213     MPM.add(createIPSCCPPass());              // IP SCCP
214     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
215
216     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
217
218     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
219     addExtensionsToPM(EP_Peephole, MPM);
220     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
221   }
222
223   if (EnableNonLTOGlobalsModRef)
224     // We add a module alias analysis pass here. In part due to bugs in the
225     // analysis infrastructure this "works" in that the analysis stays alive
226     // for the entire SCC pass run below.
227     MPM.add(createGlobalsModRefPass());
228
229   // Start of CallGraph SCC passes.
230   if (!DisableUnitAtATime)
231     MPM.add(createPruneEHPass());             // Remove dead EH info
232   if (Inliner) {
233     MPM.add(Inliner);
234     Inliner = nullptr;
235   }
236   if (!DisableUnitAtATime)
237     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
238   if (OptLevel > 2)
239     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
240
241   // Start of function pass.
242   // Break up aggregate allocas, using SSAUpdater.
243   if (UseNewSROA)
244     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
245   else
246     MPM.add(createScalarReplAggregatesPass(-1, false));
247   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
248   MPM.add(createJumpThreadingPass());         // Thread jumps.
249   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
250   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
251   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
252   addExtensionsToPM(EP_Peephole, MPM);
253
254   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
255   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
256   MPM.add(createReassociatePass());           // Reassociate expressions
257   // Rotate Loop - disable header duplication at -Oz
258   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
259   MPM.add(createLICMPass());                  // Hoist loop invariants
260   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
261   MPM.add(createInstructionCombiningPass());
262   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
263   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
264   MPM.add(createLoopDeletionPass());          // Delete dead loops
265   if (EnableLoopInterchange) {
266     MPM.add(createLoopInterchangePass()); // Interchange loops
267     MPM.add(createCFGSimplificationPass());
268   }
269   if (!DisableUnrollLoops)
270     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
271   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
272
273   if (OptLevel > 1) {
274     if (EnableMLSM)
275       MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
276     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
277   }
278   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
279   MPM.add(createSCCPPass());                  // Constant prop with SCCP
280
281   // Delete dead bit computations (instcombine runs after to fold away the dead
282   // computations, and then ADCE will run later to exploit any new DCE
283   // opportunities that creates).
284   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
285
286   // Run instcombine after redundancy elimination to exploit opportunities
287   // opened up by them.
288   MPM.add(createInstructionCombiningPass());
289   addExtensionsToPM(EP_Peephole, MPM);
290   MPM.add(createJumpThreadingPass());         // Thread jumps
291   MPM.add(createCorrelatedValuePropagationPass());
292   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
293   MPM.add(createLICMPass());
294
295   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
296
297   if (RerollLoops)
298     MPM.add(createLoopRerollPass());
299   if (!RunSLPAfterLoopVectorization) {
300     if (SLPVectorize)
301       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
302
303     if (BBVectorize) {
304       MPM.add(createBBVectorizePass());
305       MPM.add(createInstructionCombiningPass());
306       addExtensionsToPM(EP_Peephole, MPM);
307       if (OptLevel > 1 && UseGVNAfterVectorization)
308         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
309       else
310         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
311
312       // BBVectorize may have significantly shortened a loop body; unroll again.
313       if (!DisableUnrollLoops)
314         MPM.add(createLoopUnrollPass());
315     }
316   }
317
318   if (LoadCombine)
319     MPM.add(createLoadCombinePass());
320
321   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
322   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
323   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
324   addExtensionsToPM(EP_Peephole, MPM);
325
326   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
327   // pass manager that we are specifically trying to avoid. To prevent this
328   // we must insert a no-op module pass to reset the pass manager.
329   MPM.add(createBarrierNoopPass());
330
331   if (EnableNonLTOGlobalsModRef)
332     // We add a fresh GlobalsModRef run at this point. This is particularly
333     // useful as the above will have inlined, DCE'ed, and function-attr
334     // propagated everything. We should at this point have a reasonably minimal
335     // and richly annotated call graph. By computing aliasing and mod/ref
336     // information for all local globals here, the late loop passes and notably
337     // the vectorizer will be able to use them to help recognize vectorizable
338     // memory operations.
339     //
340     // Note that this relies on a bug in the pass manager which preserves
341     // a module analysis into a function pass pipeline (and throughout it) so
342     // long as the first function pass doesn't invalidate the module analysis.
343     // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
344     // this to work. Fortunately, it is trivial to preserve AliasAnalysis
345     // (doing nothing preserves it as it is required to be conservatively
346     // correct in the face of IR changes).
347     MPM.add(createGlobalsModRefPass());
348
349   if (RunFloat2Int)
350     MPM.add(createFloat2IntPass());
351
352   addExtensionsToPM(EP_VectorizerStart, MPM);
353
354   // Re-rotate loops in all our loop nests. These may have fallout out of
355   // rotated form due to GVN or other transformations, and the vectorizer relies
356   // on the rotated form. Disable header duplication at -Oz.
357   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
358
359   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
360   // into separate loop that would otherwise inhibit vectorization.
361   if (EnableLoopDistribute)
362     MPM.add(createLoopDistributePass());
363
364   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
365   // FIXME: Because of #pragma vectorize enable, the passes below are always
366   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
367   // on -O1 and no #pragma is found). Would be good to have these two passes
368   // as function calls, so that we can only pass them when the vectorizer
369   // changed the code.
370   MPM.add(createInstructionCombiningPass());
371   if (OptLevel > 1 && ExtraVectorizerPasses) {
372     // At higher optimization levels, try to clean up any runtime overlap and
373     // alignment checks inserted by the vectorizer. We want to track correllated
374     // runtime checks for two inner loops in the same outer loop, fold any
375     // common computations, hoist loop-invariant aspects out of any outer loop,
376     // and unswitch the runtime checks if possible. Once hoisted, we may have
377     // dead (or speculatable) control flows or more combining opportunities.
378     MPM.add(createEarlyCSEPass());
379     MPM.add(createCorrelatedValuePropagationPass());
380     MPM.add(createInstructionCombiningPass());
381     MPM.add(createLICMPass());
382     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
383     MPM.add(createCFGSimplificationPass());
384     MPM.add(createInstructionCombiningPass());
385   }
386
387   if (RunSLPAfterLoopVectorization) {
388     if (SLPVectorize) {
389       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
390       if (OptLevel > 1 && ExtraVectorizerPasses) {
391         MPM.add(createEarlyCSEPass());
392       }
393     }
394
395     if (BBVectorize) {
396       MPM.add(createBBVectorizePass());
397       MPM.add(createInstructionCombiningPass());
398       addExtensionsToPM(EP_Peephole, MPM);
399       if (OptLevel > 1 && UseGVNAfterVectorization)
400         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
401       else
402         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
403
404       // BBVectorize may have significantly shortened a loop body; unroll again.
405       if (!DisableUnrollLoops)
406         MPM.add(createLoopUnrollPass());
407     }
408   }
409
410   addExtensionsToPM(EP_Peephole, MPM);
411   MPM.add(createCFGSimplificationPass());
412   MPM.add(createInstructionCombiningPass());
413
414   if (!DisableUnrollLoops) {
415     MPM.add(createLoopUnrollPass());    // Unroll small loops
416
417     // LoopUnroll may generate some redundency to cleanup.
418     MPM.add(createInstructionCombiningPass());
419
420     // Runtime unrolling will introduce runtime check in loop prologue. If the
421     // unrolled loop is a inner loop, then the prologue will be inside the
422     // outer loop. LICM pass can help to promote the runtime check out if the
423     // checked value is loop invariant.
424     MPM.add(createLICMPass());
425   }
426
427   // After vectorization and unrolling, assume intrinsics may tell us more
428   // about pointer alignments.
429   MPM.add(createAlignmentFromAssumptionsPass());
430
431   if (!DisableUnitAtATime) {
432     // FIXME: We shouldn't bother with this anymore.
433     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
434
435     // GlobalOpt already deletes dead functions and globals, at -O2 try a
436     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
437     if (OptLevel > 1) {
438       if (!PrepareForLTO) {
439         // Remove avail extern fns and globals definitions if we aren't
440         // compiling an object file for later LTO. For LTO we want to preserve
441         // these so they are eligible for inlining at link-time. Note if they
442         // are unreferenced they will be removed by GlobalDCE below, so
443         // this only impacts referenced available externally globals.
444         // Eventually they will be suppressed during codegen, but eliminating
445         // here enables more opportunity for GlobalDCE as it may make
446         // globals referenced by available external functions dead.
447         MPM.add(createEliminateAvailableExternallyPass());
448       }
449       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
450       MPM.add(createConstantMergePass());     // Merge dup global constants
451     }
452   }
453
454   if (MergeFunctions)
455     MPM.add(createMergeFunctionsPass());
456
457   addExtensionsToPM(EP_OptimizerLast, MPM);
458 }
459
460 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
461   // Provide AliasAnalysis services for optimizations.
462   addInitialAliasAnalysisPasses(PM);
463
464   // Propagate constants at call sites into the functions they call.  This
465   // opens opportunities for globalopt (and inlining) by substituting function
466   // pointers passed as arguments to direct uses of functions.
467   PM.add(createIPSCCPPass());
468
469   // Now that we internalized some globals, see if we can hack on them!
470   PM.add(createGlobalOptimizerPass());
471
472   // Linking modules together can lead to duplicated global constants, only
473   // keep one copy of each constant.
474   PM.add(createConstantMergePass());
475
476   // Remove unused arguments from functions.
477   PM.add(createDeadArgEliminationPass());
478
479   // Reduce the code after globalopt and ipsccp.  Both can open up significant
480   // simplification opportunities, and both can propagate functions through
481   // function pointers.  When this happens, we often have to resolve varargs
482   // calls, etc, so let instcombine do this.
483   PM.add(createInstructionCombiningPass());
484   addExtensionsToPM(EP_Peephole, PM);
485
486   // Inline small functions
487   bool RunInliner = Inliner;
488   if (RunInliner) {
489     PM.add(Inliner);
490     Inliner = nullptr;
491   }
492
493   PM.add(createPruneEHPass());   // Remove dead EH info.
494
495   // Optimize globals again if we ran the inliner.
496   if (RunInliner)
497     PM.add(createGlobalOptimizerPass());
498   PM.add(createGlobalDCEPass()); // Remove dead functions.
499
500   // If we didn't decide to inline a function, check to see if we can
501   // transform it to pass arguments by value instead of by reference.
502   PM.add(createArgumentPromotionPass());
503
504   // The IPO passes may leave cruft around.  Clean up after them.
505   PM.add(createInstructionCombiningPass());
506   addExtensionsToPM(EP_Peephole, PM);
507   PM.add(createJumpThreadingPass());
508
509   // Break up allocas
510   if (UseNewSROA)
511     PM.add(createSROAPass());
512   else
513     PM.add(createScalarReplAggregatesPass());
514
515   // Run a few AA driven optimizations here and now, to cleanup the code.
516   PM.add(createFunctionAttrsPass()); // Add nocapture.
517   PM.add(createGlobalsModRefPass()); // IP alias analysis.
518
519   PM.add(createLICMPass());                 // Hoist loop invariants.
520   if (EnableMLSM)
521     PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
522   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
523   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
524
525   // Nuke dead stores.
526   PM.add(createDeadStoreEliminationPass());
527
528   // More loops are countable; try to optimize them.
529   PM.add(createIndVarSimplifyPass());
530   PM.add(createLoopDeletionPass());
531   if (EnableLoopInterchange)
532     PM.add(createLoopInterchangePass());
533
534   PM.add(createLoopVectorizePass(true, LoopVectorize));
535
536   // More scalar chains could be vectorized due to more alias information
537   if (RunSLPAfterLoopVectorization)
538     if (SLPVectorize)
539       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
540
541   // After vectorization, assume intrinsics may tell us more about pointer
542   // alignments.
543   PM.add(createAlignmentFromAssumptionsPass());
544
545   if (LoadCombine)
546     PM.add(createLoadCombinePass());
547
548   // Cleanup and simplify the code after the scalar optimizations.
549   PM.add(createInstructionCombiningPass());
550   addExtensionsToPM(EP_Peephole, PM);
551
552   PM.add(createJumpThreadingPass());
553 }
554
555 void PassManagerBuilder::addLateLTOOptimizationPasses(
556     legacy::PassManagerBase &PM) {
557   // Delete basic blocks, which optimization passes may have killed.
558   PM.add(createCFGSimplificationPass());
559
560   // Drop bodies of available externally objects to improve GlobalDCE.
561   PM.add(createEliminateAvailableExternallyPass());
562
563   // Now that we have optimized the program, discard unreachable functions.
564   PM.add(createGlobalDCEPass());
565
566   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
567   // currently it damages debug info.
568   if (MergeFunctions)
569     PM.add(createMergeFunctionsPass());
570 }
571
572 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
573   if (LibraryInfo)
574     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
575
576   if (VerifyInput)
577     PM.add(createVerifierPass());
578
579   if (OptLevel > 1)
580     addLTOOptimizationPasses(PM);
581
582   // Lower bit sets to globals. This pass supports Clang's control flow
583   // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
584   // is enabled. The pass does nothing if CFI is disabled.
585   PM.add(createLowerBitSetsPass());
586
587   if (OptLevel != 0)
588     addLateLTOOptimizationPasses(PM);
589
590   if (VerifyOutput)
591     PM.add(createVerifierPass());
592 }
593
594 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
595     return reinterpret_cast<PassManagerBuilder*>(P);
596 }
597
598 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
599   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
600 }
601
602 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
603   PassManagerBuilder *PMB = new PassManagerBuilder();
604   return wrap(PMB);
605 }
606
607 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
608   PassManagerBuilder *Builder = unwrap(PMB);
609   delete Builder;
610 }
611
612 void
613 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
614                                   unsigned OptLevel) {
615   PassManagerBuilder *Builder = unwrap(PMB);
616   Builder->OptLevel = OptLevel;
617 }
618
619 void
620 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
621                                    unsigned SizeLevel) {
622   PassManagerBuilder *Builder = unwrap(PMB);
623   Builder->SizeLevel = SizeLevel;
624 }
625
626 void
627 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
628                                             LLVMBool Value) {
629   PassManagerBuilder *Builder = unwrap(PMB);
630   Builder->DisableUnitAtATime = Value;
631 }
632
633 void
634 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
635                                             LLVMBool Value) {
636   PassManagerBuilder *Builder = unwrap(PMB);
637   Builder->DisableUnrollLoops = Value;
638 }
639
640 void
641 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
642                                                  LLVMBool Value) {
643   // NOTE: The simplify-libcalls pass has been removed.
644 }
645
646 void
647 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
648                                               unsigned Threshold) {
649   PassManagerBuilder *Builder = unwrap(PMB);
650   Builder->Inliner = createFunctionInliningPass(Threshold);
651 }
652
653 void
654 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
655                                                   LLVMPassManagerRef PM) {
656   PassManagerBuilder *Builder = unwrap(PMB);
657   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
658   Builder->populateFunctionPassManager(*FPM);
659 }
660
661 void
662 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
663                                                 LLVMPassManagerRef PM) {
664   PassManagerBuilder *Builder = unwrap(PMB);
665   legacy::PassManagerBase *MPM = unwrap(PM);
666   Builder->populateModulePassManager(*MPM);
667 }
668
669 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
670                                                   LLVMPassManagerRef PM,
671                                                   LLVMBool Internalize,
672                                                   LLVMBool RunInliner) {
673   PassManagerBuilder *Builder = unwrap(PMB);
674   legacy::PassManagerBase *LPM = unwrap(PM);
675
676   // A small backwards compatibility hack. populateLTOPassManager used to take
677   // an RunInliner option.
678   if (RunInliner && !Builder->Inliner)
679     Builder->Inliner = createFunctionInliningPass();
680
681   Builder->populateLTOPassManager(*LPM);
682 }