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