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