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