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