1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the PassManagerBuilder class, which is used to set up a
10 // "standard" optimization sequence suitable for languages like C and C++.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
15 #include "llvm-c/Transforms/PassManagerBuilder.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/BasicAliasAnalysis.h"
18 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/InlineCost.h"
22 #include "llvm/Analysis/Passes.h"
23 #include "llvm/Analysis/ScopedNoAliasAA.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/LegacyPassManager.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
34 #include "llvm/Transforms/IPO/FunctionAttrs.h"
35 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
36 #include "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Transforms/Scalar/GVN.h"
40 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
41 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
42 #include "llvm/Transforms/Utils.h"
43 #include "llvm/Transforms/Vectorize.h"
44 
45 using namespace llvm;
46 
47 static cl::opt<bool>
48     RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
49                        cl::ZeroOrMore, cl::desc("Run Partial inlinining pass"));
50 
51 static cl::opt<bool>
52     RunLoopVectorization("vectorize-loops", cl::Hidden,
53                          cl::desc("Run the Loop vectorization passes"));
54 
55 static cl::opt<bool>
56 RunSLPVectorization("vectorize-slp", cl::Hidden,
57                     cl::desc("Run the SLP vectorization passes"));
58 
59 static cl::opt<bool>
60 UseGVNAfterVectorization("use-gvn-after-vectorization",
61   cl::init(false), cl::Hidden,
62   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
63 
64 static cl::opt<bool> ExtraVectorizerPasses(
65     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
66     cl::desc("Run cleanup optimization passes after vectorization."));
67 
68 static cl::opt<bool>
69 RunLoopRerolling("reroll-loops", cl::Hidden,
70                  cl::desc("Run the loop rerolling pass"));
71 
72 static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
73                                cl::desc("Run the NewGVN 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 // Experimental option to use CFL-AA
82 enum class CFLAAType { None, Steensgaard, Andersen, Both };
83 static cl::opt<CFLAAType>
84     UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden,
85              cl::desc("Enable the new, experimental CFL alias analysis"),
86              cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
87                         clEnumValN(CFLAAType::Steensgaard, "steens",
88                                    "Enable unification-based CFL-AA"),
89                         clEnumValN(CFLAAType::Andersen, "anders",
90                                    "Enable inclusion-based CFL-AA"),
91                         clEnumValN(CFLAAType::Both, "both",
92                                    "Enable both variants of CFL-AA")));
93 
94 static cl::opt<bool> EnableLoopInterchange(
95     "enable-loopinterchange", cl::init(false), cl::Hidden,
96     cl::desc("Enable the new, experimental LoopInterchange Pass"));
97 
98 static cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam",
99                                         cl::init(false), cl::Hidden,
100                                         cl::desc("Enable Unroll And Jam Pass"));
101 
102 static cl::opt<bool>
103     EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
104                             cl::desc("Enable preparation for ThinLTO."));
105 
106 static cl::opt<bool>
107     EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden,
108                          cl::desc("Enable performing ThinLTO."));
109 
110 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false), cl::Hidden,
111     cl::desc("Enable hot-cold splitting pass"));
112 
113 static cl::opt<bool> UseLoopVersioningLICM(
114     "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
115     cl::desc("Enable the experimental Loop Versioning LICM pass"));
116 
117 static cl::opt<bool>
118     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
119                       cl::desc("Disable pre-instrumentation inliner"));
120 
121 static cl::opt<int> PreInlineThreshold(
122     "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
123     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
124              "(default = 75)"));
125 
126 static cl::opt<bool> EnableEarlyCSEMemSSA(
127     "enable-earlycse-memssa", cl::init(true), cl::Hidden,
128     cl::desc("Enable the EarlyCSE w/ MemorySSA pass (default = on)"));
129 
130 static cl::opt<bool> EnableGVNHoist(
131     "enable-gvn-hoist", cl::init(false), cl::Hidden,
132     cl::desc("Enable the GVN hoisting pass (default = off)"));
133 
134 static cl::opt<bool>
135     DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
136                               cl::Hidden,
137                               cl::desc("Disable shrink-wrap library calls"));
138 
139 static cl::opt<bool> EnableSimpleLoopUnswitch(
140     "enable-simple-loop-unswitch", cl::init(false), cl::Hidden,
141     cl::desc("Enable the simple loop unswitch pass. Also enables independent "
142              "cleanup passes integrated into the loop pass manager pipeline."));
143 
144 static cl::opt<bool> EnableGVNSink(
145     "enable-gvn-sink", cl::init(false), cl::Hidden,
146     cl::desc("Enable the GVN sinking pass (default = off)"));
147 
148 static cl::opt<bool>
149     EnableCHR("enable-chr", cl::init(true), cl::Hidden,
150               cl::desc("Enable control height reduction optimization (CHR)"));
151 
152 cl::opt<bool> FlattenedProfileUsed(
153     "flattened-profile-used", cl::init(false), cl::Hidden,
154     cl::desc("Indicate the sample profile being used is flattened, i.e., "
155              "no inline hierachy exists in the profile. "));
156 
157 cl::opt<bool> EnableOrderFileInstrumentation(
158     "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
159     cl::desc("Enable order file instrumentation (default = off)"));
160 
161 cl::opt<bool> ForgetSCEVInLoopUnroll(
162     "forget-scev-loop-unroll", cl::init(false), cl::Hidden,
163     cl::desc("Forget everything in SCEV when doing LoopUnroll, instead of just"
164              " the current top-most loop. This is somtimes preferred to reduce"
165              " compile time."));
166 
167 PassManagerBuilder::PassManagerBuilder() {
168     OptLevel = 2;
169     SizeLevel = 0;
170     LibraryInfo = nullptr;
171     Inliner = nullptr;
172     DisableUnrollLoops = false;
173     SLPVectorize = RunSLPVectorization;
174     LoopVectorize = RunLoopVectorization;
175     RerollLoops = RunLoopRerolling;
176     NewGVN = RunNewGVN;
177     DisableGVNLoadPRE = false;
178     ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
179     VerifyInput = false;
180     VerifyOutput = false;
181     MergeFunctions = false;
182     PrepareForLTO = false;
183     EnablePGOInstrGen = false;
184     EnablePGOCSInstrGen = false;
185     EnablePGOCSInstrUse = false;
186     PGOInstrGen = "";
187     PGOInstrUse = "";
188     PGOSampleUse = "";
189     PrepareForThinLTO = EnablePrepareForThinLTO;
190     PerformThinLTO = EnablePerformThinLTO;
191     DivergentTarget = false;
192 }
193 
194 PassManagerBuilder::~PassManagerBuilder() {
195   delete LibraryInfo;
196   delete Inliner;
197 }
198 
199 /// Set of global extensions, automatically added as part of the standard set.
200 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
201    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
202 
203 /// Check if GlobalExtensions is constructed and not empty.
204 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger
205 /// the construction of the object.
206 static bool GlobalExtensionsNotEmpty() {
207   return GlobalExtensions.isConstructed() && !GlobalExtensions->empty();
208 }
209 
210 void PassManagerBuilder::addGlobalExtension(
211     PassManagerBuilder::ExtensionPointTy Ty,
212     PassManagerBuilder::ExtensionFn Fn) {
213   GlobalExtensions->push_back(std::make_pair(Ty, std::move(Fn)));
214 }
215 
216 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
217   Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
218 }
219 
220 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
221                                            legacy::PassManagerBase &PM) const {
222   if (GlobalExtensionsNotEmpty()) {
223     for (auto &Ext : *GlobalExtensions) {
224       if (Ext.first == ETy)
225         Ext.second(*this, PM);
226     }
227   }
228   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
229     if (Extensions[i].first == ETy)
230       Extensions[i].second(*this, PM);
231 }
232 
233 void PassManagerBuilder::addInitialAliasAnalysisPasses(
234     legacy::PassManagerBase &PM) const {
235   switch (UseCFLAA) {
236   case CFLAAType::Steensgaard:
237     PM.add(createCFLSteensAAWrapperPass());
238     break;
239   case CFLAAType::Andersen:
240     PM.add(createCFLAndersAAWrapperPass());
241     break;
242   case CFLAAType::Both:
243     PM.add(createCFLSteensAAWrapperPass());
244     PM.add(createCFLAndersAAWrapperPass());
245     break;
246   default:
247     break;
248   }
249 
250   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
251   // BasicAliasAnalysis wins if they disagree. This is intended to help
252   // support "obvious" type-punning idioms.
253   PM.add(createTypeBasedAAWrapperPass());
254   PM.add(createScopedNoAliasAAWrapperPass());
255 }
256 
257 void PassManagerBuilder::addInstructionCombiningPass(
258     legacy::PassManagerBase &PM) const {
259   bool ExpensiveCombines = OptLevel > 2;
260   PM.add(createInstructionCombiningPass(ExpensiveCombines));
261 }
262 
263 void PassManagerBuilder::populateFunctionPassManager(
264     legacy::FunctionPassManager &FPM) {
265   addExtensionsToPM(EP_EarlyAsPossible, FPM);
266   FPM.add(createEntryExitInstrumenterPass());
267 
268   // Add LibraryInfo if we have some.
269   if (LibraryInfo)
270     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
271 
272   if (OptLevel == 0) return;
273 
274   addInitialAliasAnalysisPasses(FPM);
275 
276   FPM.add(createCFGSimplificationPass());
277   FPM.add(createSROAPass());
278   FPM.add(createEarlyCSEPass());
279   FPM.add(createLowerExpectIntrinsicPass());
280 }
281 
282 // Do PGO instrumentation generation or use pass as the option specified.
283 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM,
284                                            bool IsCS = false) {
285   if (IsCS) {
286     if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse)
287       return;
288   } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty())
289     return;
290 
291   // Perform the preinline and cleanup passes for O1 and above.
292   // And avoid doing them if optimizing for size.
293   // We will not do this inline for context sensitive PGO (when IsCS is true).
294   if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner &&
295       PGOSampleUse.empty() && !IsCS) {
296     // Create preinline pass. We construct an InlineParams object and specify
297     // the threshold here to avoid the command line options of the regular
298     // inliner to influence pre-inlining. The only fields of InlineParams we
299     // care about are DefaultThreshold and HintThreshold.
300     InlineParams IP;
301     IP.DefaultThreshold = PreInlineThreshold;
302     // FIXME: The hint threshold has the same value used by the regular inliner.
303     // This should probably be lowered after performance testing.
304     IP.HintThreshold = 325;
305 
306     MPM.add(createFunctionInliningPass(IP));
307     MPM.add(createSROAPass());
308     MPM.add(createEarlyCSEPass());             // Catch trivial redundancies
309     MPM.add(createCFGSimplificationPass());    // Merge & remove BBs
310     MPM.add(createInstructionCombiningPass()); // Combine silly seq's
311     addExtensionsToPM(EP_Peephole, MPM);
312   }
313   if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) {
314     MPM.add(createPGOInstrumentationGenLegacyPass(IsCS));
315     // Add the profile lowering pass.
316     InstrProfOptions Options;
317     if (!PGOInstrGen.empty())
318       Options.InstrProfileOutput = PGOInstrGen;
319     Options.DoCounterPromotion = true;
320     Options.UseBFIInPromotion = IsCS;
321     MPM.add(createLoopRotatePass());
322     MPM.add(createInstrProfilingLegacyPass(Options, IsCS));
323   }
324   if (!PGOInstrUse.empty())
325     MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS));
326   // Indirect call promotion that promotes intra-module targets only.
327   // For ThinLTO this is done earlier due to interactions with globalopt
328   // for imported functions. We don't run this at -O0.
329   if (OptLevel > 0 && !IsCS)
330     MPM.add(
331         createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
332 }
333 void PassManagerBuilder::addFunctionSimplificationPasses(
334     legacy::PassManagerBase &MPM) {
335   // Start of function pass.
336   // Break up aggregate allocas, using SSAUpdater.
337   MPM.add(createSROAPass());
338   MPM.add(createEarlyCSEPass(EnableEarlyCSEMemSSA)); // Catch trivial redundancies
339   if (EnableGVNHoist)
340     MPM.add(createGVNHoistPass());
341   if (EnableGVNSink) {
342     MPM.add(createGVNSinkPass());
343     MPM.add(createCFGSimplificationPass());
344   }
345 
346   // Speculative execution if the target has divergent branches; otherwise nop.
347   MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
348   MPM.add(createJumpThreadingPass());         // Thread jumps.
349   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
350   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
351   // Combine silly seq's
352   if (OptLevel > 2)
353     MPM.add(createAggressiveInstCombinerPass());
354   addInstructionCombiningPass(MPM);
355   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
356     MPM.add(createLibCallsShrinkWrapPass());
357   addExtensionsToPM(EP_Peephole, MPM);
358 
359   // Optimize memory intrinsic calls based on the profiled size information.
360   if (SizeLevel == 0)
361     MPM.add(createPGOMemOPSizeOptLegacyPass());
362 
363   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
364   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
365   MPM.add(createReassociatePass());           // Reassociate expressions
366 
367   // Begin the loop pass pipeline.
368   if (EnableSimpleLoopUnswitch) {
369     // The simple loop unswitch pass relies on separate cleanup passes. Schedule
370     // them first so when we re-process a loop they run before other loop
371     // passes.
372     MPM.add(createLoopInstSimplifyPass());
373     MPM.add(createLoopSimplifyCFGPass());
374   }
375   // Rotate Loop - disable header duplication at -Oz
376   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
377   MPM.add(createLICMPass());                  // Hoist loop invariants
378   if (EnableSimpleLoopUnswitch)
379     MPM.add(createSimpleLoopUnswitchLegacyPass());
380   else
381     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
382   // FIXME: We break the loop pass pipeline here in order to do full
383   // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the
384   // need for this.
385   MPM.add(createCFGSimplificationPass());
386   addInstructionCombiningPass(MPM);
387   // We resume loop passes creating a second loop pipeline here.
388   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
389   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
390   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
391   MPM.add(createLoopDeletionPass());          // Delete dead loops
392 
393   if (EnableLoopInterchange)
394     MPM.add(createLoopInterchangePass()); // Interchange loops
395 
396   // Unroll small loops
397   MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
398                                      ForgetAllSCEVInLoopUnroll));
399   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
400   // This ends the loop pass pipelines.
401 
402   if (OptLevel > 1) {
403     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
404     MPM.add(NewGVN ? createNewGVNPass()
405                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
406   }
407   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
408   MPM.add(createSCCPPass());                  // Constant prop with SCCP
409 
410   // Delete dead bit computations (instcombine runs after to fold away the dead
411   // computations, and then ADCE will run later to exploit any new DCE
412   // opportunities that creates).
413   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
414 
415   // Run instcombine after redundancy elimination to exploit opportunities
416   // opened up by them.
417   addInstructionCombiningPass(MPM);
418   addExtensionsToPM(EP_Peephole, MPM);
419   MPM.add(createJumpThreadingPass());         // Thread jumps
420   MPM.add(createCorrelatedValuePropagationPass());
421   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
422   MPM.add(createLICMPass());
423 
424   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
425 
426   if (RerollLoops)
427     MPM.add(createLoopRerollPass());
428   if (!RunSLPAfterLoopVectorization && SLPVectorize)
429     MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
430 
431   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
432   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
433   // Clean up after everything.
434   addInstructionCombiningPass(MPM);
435   addExtensionsToPM(EP_Peephole, MPM);
436 
437   if (EnableCHR && OptLevel >= 3 &&
438       (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen))
439     MPM.add(createControlHeightReductionLegacyPass());
440 }
441 
442 void PassManagerBuilder::populateModulePassManager(
443     legacy::PassManagerBase &MPM) {
444   // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link
445   // is handled separately, so just check this is not the ThinLTO post-link.
446   bool DefaultOrPreLinkPipeline = !PerformThinLTO;
447 
448   if (!PGOSampleUse.empty()) {
449     MPM.add(createPruneEHPass());
450     // In ThinLTO mode, when flattened profile is used, all the available
451     // profile information will be annotated in PreLink phase so there is
452     // no need to load the profile again in PostLink.
453     if (!(FlattenedProfileUsed && PerformThinLTO))
454       MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
455   }
456 
457   // Allow forcing function attributes as a debugging and tuning aid.
458   MPM.add(createForceFunctionAttrsLegacyPass());
459 
460   // If all optimizations are disabled, just run the always-inline pass and,
461   // if enabled, the function merging pass.
462   if (OptLevel == 0) {
463     addPGOInstrPasses(MPM);
464     if (Inliner) {
465       MPM.add(Inliner);
466       Inliner = nullptr;
467     }
468 
469     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
470     // creates a CGSCC pass manager, but we don't want to add extensions into
471     // that pass manager. To prevent this we insert a no-op module pass to reset
472     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
473     // builds. The function merging pass is
474     if (MergeFunctions)
475       MPM.add(createMergeFunctionsPass());
476     else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
477       MPM.add(createBarrierNoopPass());
478 
479     if (PerformThinLTO) {
480       // Drop available_externally and unreferenced globals. This is necessary
481       // with ThinLTO in order to avoid leaving undefined references to dead
482       // globals in the object file.
483       MPM.add(createEliminateAvailableExternallyPass());
484       MPM.add(createGlobalDCEPass());
485     }
486 
487     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
488 
489     if (PrepareForLTO || PrepareForThinLTO) {
490       MPM.add(createCanonicalizeAliasesPass());
491       // Rename anon globals to be able to export them in the summary.
492       // This has to be done after we add the extensions to the pass manager
493       // as there could be passes (e.g. Adddress sanitizer) which introduce
494       // new unnamed globals.
495       MPM.add(createNameAnonGlobalPass());
496     }
497     return;
498   }
499 
500   // Add LibraryInfo if we have some.
501   if (LibraryInfo)
502     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
503 
504   addInitialAliasAnalysisPasses(MPM);
505 
506   // For ThinLTO there are two passes of indirect call promotion. The
507   // first is during the compile phase when PerformThinLTO=false and
508   // intra-module indirect call targets are promoted. The second is during
509   // the ThinLTO backend when PerformThinLTO=true, when we promote imported
510   // inter-module indirect calls. For that we perform indirect call promotion
511   // earlier in the pass pipeline, here before globalopt. Otherwise imported
512   // available_externally functions look unreferenced and are removed.
513   if (PerformThinLTO)
514     MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
515                                                      !PGOSampleUse.empty()));
516 
517   // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
518   // as it will change the CFG too much to make the 2nd profile annotation
519   // in backend more difficult.
520   bool PrepareForThinLTOUsingPGOSampleProfile =
521       PrepareForThinLTO && !PGOSampleUse.empty();
522   if (PrepareForThinLTOUsingPGOSampleProfile)
523     DisableUnrollLoops = true;
524 
525   // Infer attributes about declarations if possible.
526   MPM.add(createInferFunctionAttrsLegacyPass());
527 
528   addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
529 
530   if (OptLevel > 2)
531     MPM.add(createCallSiteSplittingPass());
532 
533   MPM.add(createIPSCCPPass());          // IP SCCP
534   MPM.add(createCalledValuePropagationPass());
535   MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
536   // Promote any localized global vars.
537   MPM.add(createPromoteMemoryToRegisterPass());
538 
539   MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
540 
541   addInstructionCombiningPass(MPM); // Clean up after IPCP & DAE
542   addExtensionsToPM(EP_Peephole, MPM);
543   MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
544 
545   // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
546   // call promotion as it will change the CFG too much to make the 2nd
547   // profile annotation in backend more difficult.
548   // PGO instrumentation is added during the compile phase for ThinLTO, do
549   // not run it a second time
550   if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile)
551     addPGOInstrPasses(MPM);
552 
553   // Create profile COMDAT variables. Lld linker wants to see all variables
554   // before the LTO/ThinLTO link since it needs to resolve symbols/comdats.
555   if (!PerformThinLTO && EnablePGOCSInstrGen)
556     MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen));
557 
558   // We add a module alias analysis pass here. In part due to bugs in the
559   // analysis infrastructure this "works" in that the analysis stays alive
560   // for the entire SCC pass run below.
561   MPM.add(createGlobalsAAWrapperPass());
562 
563   // Start of CallGraph SCC passes.
564   MPM.add(createPruneEHPass()); // Remove dead EH info
565   bool RunInliner = false;
566   if (Inliner) {
567     MPM.add(Inliner);
568     Inliner = nullptr;
569     RunInliner = true;
570   }
571 
572   MPM.add(createPostOrderFunctionAttrsLegacyPass());
573   if (OptLevel > 2)
574     MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
575 
576   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
577   addFunctionSimplificationPasses(MPM);
578 
579   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
580   // pass manager that we are specifically trying to avoid. To prevent this
581   // we must insert a no-op module pass to reset the pass manager.
582   MPM.add(createBarrierNoopPass());
583 
584   if (RunPartialInlining)
585     MPM.add(createPartialInliningPass());
586 
587   if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO)
588     // Remove avail extern fns and globals definitions if we aren't
589     // compiling an object file for later LTO. For LTO we want to preserve
590     // these so they are eligible for inlining at link-time. Note if they
591     // are unreferenced they will be removed by GlobalDCE later, so
592     // this only impacts referenced available externally globals.
593     // Eventually they will be suppressed during codegen, but eliminating
594     // here enables more opportunity for GlobalDCE as it may make
595     // globals referenced by available external functions dead
596     // and saves running remaining passes on the eliminated functions.
597     MPM.add(createEliminateAvailableExternallyPass());
598 
599   // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass
600   // for LTO and ThinLTO -- The actual pass will be called after all inlines
601   // are performed.
602   // Need to do this after COMDAT variables have been eliminated,
603   // (i.e. after EliminateAvailableExternallyPass).
604   if (!(PrepareForLTO || PrepareForThinLTO))
605     addPGOInstrPasses(MPM, /* IsCS */ true);
606 
607   if (EnableOrderFileInstrumentation)
608     MPM.add(createInstrOrderFilePass());
609 
610   MPM.add(createReversePostOrderFunctionAttrsPass());
611 
612   // The inliner performs some kind of dead code elimination as it goes,
613   // but there are cases that are not really caught by it. We might
614   // at some point consider teaching the inliner about them, but it
615   // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
616   // benefits generally outweight the cost, making the whole pipeline
617   // faster.
618   if (RunInliner) {
619     MPM.add(createGlobalOptimizerPass());
620     MPM.add(createGlobalDCEPass());
621   }
622 
623   // If we are planning to perform ThinLTO later, let's not bloat the code with
624   // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
625   // during ThinLTO and perform the rest of the optimizations afterward.
626   if (PrepareForThinLTO) {
627     // Ensure we perform any last passes, but do so before renaming anonymous
628     // globals in case the passes add any.
629     addExtensionsToPM(EP_OptimizerLast, MPM);
630     MPM.add(createCanonicalizeAliasesPass());
631     // Rename anon globals to be able to export them in the summary.
632     MPM.add(createNameAnonGlobalPass());
633     return;
634   }
635 
636   if (PerformThinLTO)
637     // Optimize globals now when performing ThinLTO, this enables more
638     // optimizations later.
639     MPM.add(createGlobalOptimizerPass());
640 
641   // Scheduling LoopVersioningLICM when inlining is over, because after that
642   // we may see more accurate aliasing. Reason to run this late is that too
643   // early versioning may prevent further inlining due to increase of code
644   // size. By placing it just after inlining other optimizations which runs
645   // later might get benefit of no-alias assumption in clone loop.
646   if (UseLoopVersioningLICM) {
647     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
648     MPM.add(createLICMPass());                  // Hoist loop invariants
649   }
650 
651   // We add a fresh GlobalsModRef run at this point. This is particularly
652   // useful as the above will have inlined, DCE'ed, and function-attr
653   // propagated everything. We should at this point have a reasonably minimal
654   // and richly annotated call graph. By computing aliasing and mod/ref
655   // information for all local globals here, the late loop passes and notably
656   // the vectorizer will be able to use them to help recognize vectorizable
657   // memory operations.
658   //
659   // Note that this relies on a bug in the pass manager which preserves
660   // a module analysis into a function pass pipeline (and throughout it) so
661   // long as the first function pass doesn't invalidate the module analysis.
662   // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
663   // this to work. Fortunately, it is trivial to preserve AliasAnalysis
664   // (doing nothing preserves it as it is required to be conservatively
665   // correct in the face of IR changes).
666   MPM.add(createGlobalsAAWrapperPass());
667 
668   MPM.add(createFloat2IntPass());
669 
670   addExtensionsToPM(EP_VectorizerStart, MPM);
671 
672   // Re-rotate loops in all our loop nests. These may have fallout out of
673   // rotated form due to GVN or other transformations, and the vectorizer relies
674   // on the rotated form. Disable header duplication at -Oz.
675   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
676 
677   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
678   // into separate loop that would otherwise inhibit vectorization.  This is
679   // currently only performed for loops marked with the metadata
680   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
681   MPM.add(createLoopDistributePass());
682 
683   MPM.add(createLoopVectorizePass(DisableUnrollLoops, !LoopVectorize));
684 
685   // Eliminate loads by forwarding stores from the previous iteration to loads
686   // of the current iteration.
687   MPM.add(createLoopLoadEliminationPass());
688 
689   // FIXME: Because of #pragma vectorize enable, the passes below are always
690   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
691   // on -O1 and no #pragma is found). Would be good to have these two passes
692   // as function calls, so that we can only pass them when the vectorizer
693   // changed the code.
694   addInstructionCombiningPass(MPM);
695   if (OptLevel > 1 && ExtraVectorizerPasses) {
696     // At higher optimization levels, try to clean up any runtime overlap and
697     // alignment checks inserted by the vectorizer. We want to track correllated
698     // runtime checks for two inner loops in the same outer loop, fold any
699     // common computations, hoist loop-invariant aspects out of any outer loop,
700     // and unswitch the runtime checks if possible. Once hoisted, we may have
701     // dead (or speculatable) control flows or more combining opportunities.
702     MPM.add(createEarlyCSEPass());
703     MPM.add(createCorrelatedValuePropagationPass());
704     addInstructionCombiningPass(MPM);
705     MPM.add(createLICMPass());
706     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
707     MPM.add(createCFGSimplificationPass());
708     addInstructionCombiningPass(MPM);
709   }
710 
711   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
712   // GVN, loop transforms, and others have already run, so it's now better to
713   // convert to more optimized IR using more aggressive simplify CFG options.
714   // The extra sinking transform can create larger basic blocks, so do this
715   // before SLP vectorization.
716   MPM.add(createCFGSimplificationPass(1, true, true, false, true));
717 
718   if (RunSLPAfterLoopVectorization && SLPVectorize) {
719     MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
720     if (OptLevel > 1 && ExtraVectorizerPasses) {
721       MPM.add(createEarlyCSEPass());
722     }
723   }
724 
725   addExtensionsToPM(EP_Peephole, MPM);
726   addInstructionCombiningPass(MPM);
727 
728   if (EnableUnrollAndJam && !DisableUnrollLoops) {
729     // Unroll and Jam. We do this before unroll but need to be in a separate
730     // loop pass manager in order for the outer loop to be processed by
731     // unroll and jam before the inner loop is unrolled.
732     MPM.add(createLoopUnrollAndJamPass(OptLevel));
733   }
734 
735   // Unroll small loops
736   MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
737                                ForgetAllSCEVInLoopUnroll));
738 
739   if (!DisableUnrollLoops) {
740     // LoopUnroll may generate some redundency to cleanup.
741     addInstructionCombiningPass(MPM);
742 
743     // Runtime unrolling will introduce runtime check in loop prologue. If the
744     // unrolled loop is a inner loop, then the prologue will be inside the
745     // outer loop. LICM pass can help to promote the runtime check out if the
746     // checked value is loop invariant.
747     MPM.add(createLICMPass());
748   }
749 
750   MPM.add(createWarnMissedTransformationsPass());
751 
752   // After vectorization and unrolling, assume intrinsics may tell us more
753   // about pointer alignments.
754   MPM.add(createAlignmentFromAssumptionsPass());
755 
756   // FIXME: We shouldn't bother with this anymore.
757   MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
758 
759   // GlobalOpt already deletes dead functions and globals, at -O2 try a
760   // late pass of GlobalDCE.  It is capable of deleting dead cycles.
761   if (OptLevel > 1) {
762     MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
763     MPM.add(createConstantMergePass());     // Merge dup global constants
764   }
765 
766   // See comment in the new PM for justification of scheduling splitting at
767   // this stage (\ref buildModuleSimplificationPipeline).
768   if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO))
769     MPM.add(createHotColdSplittingPass());
770 
771   if (MergeFunctions)
772     MPM.add(createMergeFunctionsPass());
773 
774   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
775   // canonicalization pass that enables other optimizations. As a result,
776   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
777   // result too early.
778   MPM.add(createLoopSinkPass());
779   // Get rid of LCSSA nodes.
780   MPM.add(createInstSimplifyLegacyPass());
781 
782   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
783   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
784   // flattening of blocks.
785   MPM.add(createDivRemPairsPass());
786 
787   // LoopSink (and other loop passes since the last simplifyCFG) might have
788   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
789   MPM.add(createCFGSimplificationPass());
790 
791   addExtensionsToPM(EP_OptimizerLast, MPM);
792 
793   if (PrepareForLTO) {
794     MPM.add(createCanonicalizeAliasesPass());
795     // Rename anon globals to be able to handle them in the summary
796     MPM.add(createNameAnonGlobalPass());
797   }
798 }
799 
800 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
801   // Load sample profile before running the LTO optimization pipeline.
802   if (!PGOSampleUse.empty()) {
803     PM.add(createPruneEHPass());
804     PM.add(createSampleProfileLoaderPass(PGOSampleUse));
805   }
806 
807   // Remove unused virtual tables to improve the quality of code generated by
808   // whole-program devirtualization and bitset lowering.
809   PM.add(createGlobalDCEPass());
810 
811   // Provide AliasAnalysis services for optimizations.
812   addInitialAliasAnalysisPasses(PM);
813 
814   // Allow forcing function attributes as a debugging and tuning aid.
815   PM.add(createForceFunctionAttrsLegacyPass());
816 
817   // Infer attributes about declarations if possible.
818   PM.add(createInferFunctionAttrsLegacyPass());
819 
820   if (OptLevel > 1) {
821     // Split call-site with more constrained arguments.
822     PM.add(createCallSiteSplittingPass());
823 
824     // Indirect call promotion. This should promote all the targets that are
825     // left by the earlier promotion pass that promotes intra-module targets.
826     // This two-step promotion is to save the compile time. For LTO, it should
827     // produce the same result as if we only do promotion here.
828     PM.add(
829         createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
830 
831     // Propagate constants at call sites into the functions they call.  This
832     // opens opportunities for globalopt (and inlining) by substituting function
833     // pointers passed as arguments to direct uses of functions.
834     PM.add(createIPSCCPPass());
835 
836     // Attach metadata to indirect call sites indicating the set of functions
837     // they may target at run-time. This should follow IPSCCP.
838     PM.add(createCalledValuePropagationPass());
839   }
840 
841   // Infer attributes about definitions. The readnone attribute in particular is
842   // required for virtual constant propagation.
843   PM.add(createPostOrderFunctionAttrsLegacyPass());
844   PM.add(createReversePostOrderFunctionAttrsPass());
845 
846   // Split globals using inrange annotations on GEP indices. This can help
847   // improve the quality of generated code when virtual constant propagation or
848   // control flow integrity are enabled.
849   PM.add(createGlobalSplitPass());
850 
851   // Apply whole-program devirtualization and virtual constant propagation.
852   PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
853 
854   // That's all we need at opt level 1.
855   if (OptLevel == 1)
856     return;
857 
858   // Now that we internalized some globals, see if we can hack on them!
859   PM.add(createGlobalOptimizerPass());
860   // Promote any localized global vars.
861   PM.add(createPromoteMemoryToRegisterPass());
862 
863   // Linking modules together can lead to duplicated global constants, only
864   // keep one copy of each constant.
865   PM.add(createConstantMergePass());
866 
867   // Remove unused arguments from functions.
868   PM.add(createDeadArgEliminationPass());
869 
870   // Reduce the code after globalopt and ipsccp.  Both can open up significant
871   // simplification opportunities, and both can propagate functions through
872   // function pointers.  When this happens, we often have to resolve varargs
873   // calls, etc, so let instcombine do this.
874   if (OptLevel > 2)
875     PM.add(createAggressiveInstCombinerPass());
876   addInstructionCombiningPass(PM);
877   addExtensionsToPM(EP_Peephole, PM);
878 
879   // Inline small functions
880   bool RunInliner = Inliner;
881   if (RunInliner) {
882     PM.add(Inliner);
883     Inliner = nullptr;
884   }
885 
886   PM.add(createPruneEHPass());   // Remove dead EH info.
887 
888   // CSFDO instrumentation and use pass.
889   addPGOInstrPasses(PM, /* IsCS */ true);
890 
891   // Optimize globals again if we ran the inliner.
892   if (RunInliner)
893     PM.add(createGlobalOptimizerPass());
894   PM.add(createGlobalDCEPass()); // Remove dead functions.
895 
896   // If we didn't decide to inline a function, check to see if we can
897   // transform it to pass arguments by value instead of by reference.
898   PM.add(createArgumentPromotionPass());
899 
900   // The IPO passes may leave cruft around.  Clean up after them.
901   addInstructionCombiningPass(PM);
902   addExtensionsToPM(EP_Peephole, PM);
903   PM.add(createJumpThreadingPass());
904 
905   // Break up allocas
906   PM.add(createSROAPass());
907 
908   // LTO provides additional opportunities for tailcall elimination due to
909   // link-time inlining, and visibility of nocapture attribute.
910   PM.add(createTailCallEliminationPass());
911 
912   // Run a few AA driven optimizations here and now, to cleanup the code.
913   PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
914   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
915 
916   PM.add(createLICMPass());                 // Hoist loop invariants.
917   PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
918   PM.add(NewGVN ? createNewGVNPass()
919                 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
920   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
921 
922   // Nuke dead stores.
923   PM.add(createDeadStoreEliminationPass());
924 
925   // More loops are countable; try to optimize them.
926   PM.add(createIndVarSimplifyPass());
927   PM.add(createLoopDeletionPass());
928   if (EnableLoopInterchange)
929     PM.add(createLoopInterchangePass());
930 
931   // Unroll small loops
932   PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
933                                     ForgetAllSCEVInLoopUnroll));
934   PM.add(createLoopVectorizePass(true, !LoopVectorize));
935   // The vectorizer may have significantly shortened a loop body; unroll again.
936   PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
937                               ForgetAllSCEVInLoopUnroll));
938 
939   PM.add(createWarnMissedTransformationsPass());
940 
941   // Now that we've optimized loops (in particular loop induction variables),
942   // we may have exposed more scalar opportunities. Run parts of the scalar
943   // optimizer again at this point.
944   addInstructionCombiningPass(PM); // Initial cleanup
945   PM.add(createCFGSimplificationPass()); // if-convert
946   PM.add(createSCCPPass()); // Propagate exposed constants
947   addInstructionCombiningPass(PM); // Clean up again
948   PM.add(createBitTrackingDCEPass());
949 
950   // More scalar chains could be vectorized due to more alias information
951   if (RunSLPAfterLoopVectorization)
952     if (SLPVectorize)
953       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
954 
955   // After vectorization, assume intrinsics may tell us more about pointer
956   // alignments.
957   PM.add(createAlignmentFromAssumptionsPass());
958 
959   // Cleanup and simplify the code after the scalar optimizations.
960   addInstructionCombiningPass(PM);
961   addExtensionsToPM(EP_Peephole, PM);
962 
963   PM.add(createJumpThreadingPass());
964 }
965 
966 void PassManagerBuilder::addLateLTOOptimizationPasses(
967     legacy::PassManagerBase &PM) {
968   // See comment in the new PM for justification of scheduling splitting at
969   // this stage (\ref buildLTODefaultPipeline).
970   if (EnableHotColdSplit)
971     PM.add(createHotColdSplittingPass());
972 
973   // Delete basic blocks, which optimization passes may have killed.
974   PM.add(createCFGSimplificationPass());
975 
976   // Drop bodies of available externally objects to improve GlobalDCE.
977   PM.add(createEliminateAvailableExternallyPass());
978 
979   // Now that we have optimized the program, discard unreachable functions.
980   PM.add(createGlobalDCEPass());
981 
982   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
983   // currently it damages debug info.
984   if (MergeFunctions)
985     PM.add(createMergeFunctionsPass());
986 }
987 
988 void PassManagerBuilder::populateThinLTOPassManager(
989     legacy::PassManagerBase &PM) {
990   PerformThinLTO = true;
991   if (LibraryInfo)
992     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
993 
994   if (VerifyInput)
995     PM.add(createVerifierPass());
996 
997   if (ImportSummary) {
998     // These passes import type identifier resolutions for whole-program
999     // devirtualization and CFI. They must run early because other passes may
1000     // disturb the specific instruction patterns that these passes look for,
1001     // creating dependencies on resolutions that may not appear in the summary.
1002     //
1003     // For example, GVN may transform the pattern assume(type.test) appearing in
1004     // two basic blocks into assume(phi(type.test, type.test)), which would
1005     // transform a dependency on a WPD resolution into a dependency on a type
1006     // identifier resolution for CFI.
1007     //
1008     // Also, WPD has access to more precise information than ICP and can
1009     // devirtualize more effectively, so it should operate on the IR first.
1010     PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
1011     PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
1012   }
1013 
1014   populateModulePassManager(PM);
1015 
1016   if (VerifyOutput)
1017     PM.add(createVerifierPass());
1018   PerformThinLTO = false;
1019 }
1020 
1021 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
1022   if (LibraryInfo)
1023     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1024 
1025   if (VerifyInput)
1026     PM.add(createVerifierPass());
1027 
1028   if (OptLevel != 0)
1029     addLTOOptimizationPasses(PM);
1030   else {
1031     // The whole-program-devirt pass needs to run at -O0 because only it knows
1032     // about the llvm.type.checked.load intrinsic: it needs to both lower the
1033     // intrinsic itself and handle it in the summary.
1034     PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
1035   }
1036 
1037   // Create a function that performs CFI checks for cross-DSO calls with targets
1038   // in the current module.
1039   PM.add(createCrossDSOCFIPass());
1040 
1041   // Lower type metadata and the type.test intrinsic. This pass supports Clang's
1042   // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
1043   // link time if CFI is enabled. The pass does nothing if CFI is disabled.
1044   PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
1045 
1046   if (OptLevel != 0)
1047     addLateLTOOptimizationPasses(PM);
1048 
1049   if (VerifyOutput)
1050     PM.add(createVerifierPass());
1051 }
1052 
1053 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
1054     return reinterpret_cast<PassManagerBuilder*>(P);
1055 }
1056 
1057 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
1058   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
1059 }
1060 
1061 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
1062   PassManagerBuilder *PMB = new PassManagerBuilder();
1063   return wrap(PMB);
1064 }
1065 
1066 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
1067   PassManagerBuilder *Builder = unwrap(PMB);
1068   delete Builder;
1069 }
1070 
1071 void
1072 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
1073                                   unsigned OptLevel) {
1074   PassManagerBuilder *Builder = unwrap(PMB);
1075   Builder->OptLevel = OptLevel;
1076 }
1077 
1078 void
1079 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
1080                                    unsigned SizeLevel) {
1081   PassManagerBuilder *Builder = unwrap(PMB);
1082   Builder->SizeLevel = SizeLevel;
1083 }
1084 
1085 void
1086 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
1087                                             LLVMBool Value) {
1088   // NOTE: The DisableUnitAtATime switch has been removed.
1089 }
1090 
1091 void
1092 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
1093                                             LLVMBool Value) {
1094   PassManagerBuilder *Builder = unwrap(PMB);
1095   Builder->DisableUnrollLoops = Value;
1096 }
1097 
1098 void
1099 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
1100                                                  LLVMBool Value) {
1101   // NOTE: The simplify-libcalls pass has been removed.
1102 }
1103 
1104 void
1105 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
1106                                               unsigned Threshold) {
1107   PassManagerBuilder *Builder = unwrap(PMB);
1108   Builder->Inliner = createFunctionInliningPass(Threshold);
1109 }
1110 
1111 void
1112 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
1113                                                   LLVMPassManagerRef PM) {
1114   PassManagerBuilder *Builder = unwrap(PMB);
1115   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
1116   Builder->populateFunctionPassManager(*FPM);
1117 }
1118 
1119 void
1120 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
1121                                                 LLVMPassManagerRef PM) {
1122   PassManagerBuilder *Builder = unwrap(PMB);
1123   legacy::PassManagerBase *MPM = unwrap(PM);
1124   Builder->populateModulePassManager(*MPM);
1125 }
1126 
1127 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1128                                                   LLVMPassManagerRef PM,
1129                                                   LLVMBool Internalize,
1130                                                   LLVMBool RunInliner) {
1131   PassManagerBuilder *Builder = unwrap(PMB);
1132   legacy::PassManagerBase *LPM = unwrap(PM);
1133 
1134   // A small backwards compatibility hack. populateLTOPassManager used to take
1135   // an RunInliner option.
1136   if (RunInliner && !Builder->Inliner)
1137     Builder->Inliner = createFunctionInliningPass();
1138 
1139   Builder->populateLTOPassManager(*LPM);
1140 }
1141