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