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