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