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 
16 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
17 #include "llvm-c/Transforms/PassManagerBuilder.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/Passes.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Transforms/Vectorize.h"
30 
31 using namespace llvm;
32 
33 static cl::opt<bool>
34 RunLoopVectorization("vectorize-loops", cl::Hidden,
35                      cl::desc("Run the Loop vectorization passes"));
36 
37 static cl::opt<bool>
38 RunSLPVectorization("vectorize-slp", cl::Hidden,
39                     cl::desc("Run the SLP vectorization passes"));
40 
41 static cl::opt<bool>
42 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
43                     cl::desc("Run the BB vectorization passes"));
44 
45 static cl::opt<bool>
46 UseGVNAfterVectorization("use-gvn-after-vectorization",
47   cl::init(false), cl::Hidden,
48   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
49 
50 static cl::opt<bool> ExtraVectorizerPasses(
51     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
52     cl::desc("Run cleanup optimization passes after vectorization."));
53 
54 static cl::opt<bool> UseNewSROA("use-new-sroa",
55   cl::init(true), cl::Hidden,
56   cl::desc("Enable the new, experimental SROA pass"));
57 
58 static cl::opt<bool>
59 RunLoopRerolling("reroll-loops", cl::Hidden,
60                  cl::desc("Run the loop rerolling pass"));
61 
62 static cl::opt<bool>
63 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
64              cl::desc("Run the float2int (float demotion) pass"));
65 
66 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
67                                     cl::Hidden,
68                                     cl::desc("Run the load combining pass"));
69 
70 static cl::opt<bool>
71 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
72   cl::init(true), cl::Hidden,
73   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
74            "vectorizer instead of before"));
75 
76 static cl::opt<bool> UseCFLAA("use-cfl-aa",
77   cl::init(false), cl::Hidden,
78   cl::desc("Enable the new, experimental CFL alias analysis"));
79 
80 static cl::opt<bool>
81 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
82            cl::desc("Enable motion of merged load and store"));
83 
84 static cl::opt<bool> EnableLoopInterchange(
85     "enable-loopinterchange", cl::init(false), cl::Hidden,
86     cl::desc("Enable the new, experimental LoopInterchange Pass"));
87 
PassManagerBuilder()88 PassManagerBuilder::PassManagerBuilder() {
89     OptLevel = 2;
90     SizeLevel = 0;
91     LibraryInfo = nullptr;
92     Inliner = nullptr;
93     DisableTailCalls = false;
94     DisableUnitAtATime = false;
95     DisableUnrollLoops = false;
96     BBVectorize = RunBBVectorization;
97     SLPVectorize = RunSLPVectorization;
98     LoopVectorize = RunLoopVectorization;
99     RerollLoops = RunLoopRerolling;
100     LoadCombine = RunLoadCombine;
101     DisableGVNLoadPRE = false;
102     VerifyInput = false;
103     VerifyOutput = false;
104     MergeFunctions = false;
105 }
106 
~PassManagerBuilder()107 PassManagerBuilder::~PassManagerBuilder() {
108   delete LibraryInfo;
109   delete Inliner;
110 }
111 
112 /// Set of global extensions, automatically added as part of the standard set.
113 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
114    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
115 
addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,PassManagerBuilder::ExtensionFn Fn)116 void PassManagerBuilder::addGlobalExtension(
117     PassManagerBuilder::ExtensionPointTy Ty,
118     PassManagerBuilder::ExtensionFn Fn) {
119   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
120 }
121 
addExtension(ExtensionPointTy Ty,ExtensionFn Fn)122 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
123   Extensions.push_back(std::make_pair(Ty, Fn));
124 }
125 
addExtensionsToPM(ExtensionPointTy ETy,legacy::PassManagerBase & PM) const126 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
127                                            legacy::PassManagerBase &PM) const {
128   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
129     if ((*GlobalExtensions)[i].first == ETy)
130       (*GlobalExtensions)[i].second(*this, PM);
131   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
132     if (Extensions[i].first == ETy)
133       Extensions[i].second(*this, PM);
134 }
135 
addInitialAliasAnalysisPasses(legacy::PassManagerBase & PM) const136 void PassManagerBuilder::addInitialAliasAnalysisPasses(
137     legacy::PassManagerBase &PM) const {
138   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
139   // BasicAliasAnalysis wins if they disagree. This is intended to help
140   // support "obvious" type-punning idioms.
141   if (UseCFLAA)
142     PM.add(createCFLAliasAnalysisPass());
143   PM.add(createTypeBasedAliasAnalysisPass());
144   PM.add(createScopedNoAliasAAPass());
145   PM.add(createBasicAliasAnalysisPass());
146 }
147 
populateFunctionPassManager(legacy::FunctionPassManager & FPM)148 void PassManagerBuilder::populateFunctionPassManager(
149     legacy::FunctionPassManager &FPM) {
150   addExtensionsToPM(EP_EarlyAsPossible, FPM);
151 
152   // Add LibraryInfo if we have some.
153   if (LibraryInfo)
154     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
155 
156   if (OptLevel == 0) return;
157 
158   addInitialAliasAnalysisPasses(FPM);
159 
160   FPM.add(createCFGSimplificationPass());
161   if (UseNewSROA)
162     FPM.add(createSROAPass());
163   else
164     FPM.add(createScalarReplAggregatesPass());
165   FPM.add(createEarlyCSEPass());
166   FPM.add(createLowerExpectIntrinsicPass());
167 }
168 
populateModulePassManager(legacy::PassManagerBase & MPM)169 void PassManagerBuilder::populateModulePassManager(
170     legacy::PassManagerBase &MPM) {
171   // If all optimizations are disabled, just run the always-inline pass and,
172   // if enabled, the function merging pass.
173   if (OptLevel == 0) {
174     if (Inliner) {
175       MPM.add(Inliner);
176       Inliner = nullptr;
177     }
178 
179     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
180     // creates a CGSCC pass manager, but we don't want to add extensions into
181     // that pass manager. To prevent this we insert a no-op module pass to reset
182     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
183     // builds. The function merging pass is
184     if (MergeFunctions)
185       MPM.add(createMergeFunctionsPass());
186     else if (!GlobalExtensions->empty() || !Extensions.empty())
187       MPM.add(createBarrierNoopPass());
188 
189     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
190     return;
191   }
192 
193   // Add LibraryInfo if we have some.
194   if (LibraryInfo)
195     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
196 
197   addInitialAliasAnalysisPasses(MPM);
198 
199   if (!DisableUnitAtATime) {
200     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
201 
202     MPM.add(createIPSCCPPass());              // IP SCCP
203     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
204 
205     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
206 
207     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
208     addExtensionsToPM(EP_Peephole, MPM);
209     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
210   }
211 
212   // Start of CallGraph SCC passes.
213   if (!DisableUnitAtATime)
214     MPM.add(createPruneEHPass());             // Remove dead EH info
215   if (Inliner) {
216     MPM.add(Inliner);
217     Inliner = nullptr;
218   }
219   if (!DisableUnitAtATime)
220     MPM.add(createFunctionAttrsPass());       // Set readonly/readnone attrs
221   if (OptLevel > 2)
222     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
223 
224   // Start of function pass.
225   // Break up aggregate allocas, using SSAUpdater.
226   if (UseNewSROA)
227     MPM.add(createSROAPass(/*RequiresDomTree*/ false));
228   else
229     MPM.add(createScalarReplAggregatesPass(-1, false));
230   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
231   MPM.add(createJumpThreadingPass());         // Thread jumps.
232   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
233   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
234   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
235   addExtensionsToPM(EP_Peephole, MPM);
236 
237   if (!DisableTailCalls)
238     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
239   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
240   MPM.add(createReassociatePass());           // Reassociate expressions
241   // Rotate Loop - disable header duplication at -Oz
242   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
243   MPM.add(createLICMPass());                  // Hoist loop invariants
244   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
245   MPM.add(createInstructionCombiningPass());
246   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
247   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
248   MPM.add(createLoopDeletionPass());          // Delete dead loops
249   if (EnableLoopInterchange)
250     MPM.add(createLoopInterchangePass()); // Interchange loops
251 
252   if (!DisableUnrollLoops)
253     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
254   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
255 
256   if (OptLevel > 1) {
257     if (EnableMLSM)
258       MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
259     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
260   }
261   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
262   MPM.add(createSCCPPass());                  // Constant prop with SCCP
263 
264   // Delete dead bit computations (instcombine runs after to fold away the dead
265   // computations, and then ADCE will run later to exploit any new DCE
266   // opportunities that creates).
267   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
268 
269   // Run instcombine after redundancy elimination to exploit opportunities
270   // opened up by them.
271   MPM.add(createInstructionCombiningPass());
272   addExtensionsToPM(EP_Peephole, MPM);
273   MPM.add(createJumpThreadingPass());         // Thread jumps
274   MPM.add(createCorrelatedValuePropagationPass());
275   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
276   MPM.add(createLICMPass());
277 
278   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
279 
280   if (RerollLoops)
281     MPM.add(createLoopRerollPass());
282   if (!RunSLPAfterLoopVectorization) {
283     if (SLPVectorize)
284       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
285 
286     if (BBVectorize) {
287       MPM.add(createBBVectorizePass());
288       MPM.add(createInstructionCombiningPass());
289       addExtensionsToPM(EP_Peephole, MPM);
290       if (OptLevel > 1 && UseGVNAfterVectorization)
291         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
292       else
293         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
294 
295       // BBVectorize may have significantly shortened a loop body; unroll again.
296       if (!DisableUnrollLoops)
297         MPM.add(createLoopUnrollPass());
298     }
299   }
300 
301   if (LoadCombine)
302     MPM.add(createLoadCombinePass());
303 
304   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
305   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
306   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
307   addExtensionsToPM(EP_Peephole, MPM);
308 
309   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
310   // pass manager that we are specifically trying to avoid. To prevent this
311   // we must insert a no-op module pass to reset the pass manager.
312   MPM.add(createBarrierNoopPass());
313 
314   if (RunFloat2Int)
315     MPM.add(createFloat2IntPass());
316 
317   // Re-rotate loops in all our loop nests. These may have fallout out of
318   // rotated form due to GVN or other transformations, and the vectorizer relies
319   // on the rotated form.
320   MPM.add(createLoopRotatePass());
321 
322   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
323   // FIXME: Because of #pragma vectorize enable, the passes below are always
324   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
325   // on -O1 and no #pragma is found). Would be good to have these two passes
326   // as function calls, so that we can only pass them when the vectorizer
327   // changed the code.
328   MPM.add(createInstructionCombiningPass());
329   if (OptLevel > 1 && ExtraVectorizerPasses) {
330     // At higher optimization levels, try to clean up any runtime overlap and
331     // alignment checks inserted by the vectorizer. We want to track correllated
332     // runtime checks for two inner loops in the same outer loop, fold any
333     // common computations, hoist loop-invariant aspects out of any outer loop,
334     // and unswitch the runtime checks if possible. Once hoisted, we may have
335     // dead (or speculatable) control flows or more combining opportunities.
336     MPM.add(createEarlyCSEPass());
337     MPM.add(createCorrelatedValuePropagationPass());
338     MPM.add(createInstructionCombiningPass());
339     MPM.add(createLICMPass());
340     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
341     MPM.add(createCFGSimplificationPass());
342     MPM.add(createInstructionCombiningPass());
343   }
344 
345   if (RunSLPAfterLoopVectorization) {
346     if (SLPVectorize) {
347       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
348       if (OptLevel > 1 && ExtraVectorizerPasses) {
349         MPM.add(createEarlyCSEPass());
350       }
351     }
352 
353     if (BBVectorize) {
354       MPM.add(createBBVectorizePass());
355       MPM.add(createInstructionCombiningPass());
356       addExtensionsToPM(EP_Peephole, MPM);
357       if (OptLevel > 1 && UseGVNAfterVectorization)
358         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
359       else
360         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
361 
362       // BBVectorize may have significantly shortened a loop body; unroll again.
363       if (!DisableUnrollLoops)
364         MPM.add(createLoopUnrollPass());
365     }
366   }
367 
368   addExtensionsToPM(EP_Peephole, MPM);
369   MPM.add(createCFGSimplificationPass());
370   MPM.add(createInstructionCombiningPass());
371 
372   if (!DisableUnrollLoops) {
373     MPM.add(createLoopUnrollPass());    // Unroll small loops
374 
375     // This is a barrier pass to avoid combine LICM pass and loop unroll pass
376     // within same loop pass manager.
377     MPM.add(createInstructionSimplifierPass());
378 
379     // Runtime unrolling will introduce runtime check in loop prologue. If the
380     // unrolled loop is a inner loop, then the prologue will be inside the
381     // outer loop. LICM pass can help to promote the runtime check out if the
382     // checked value is loop invariant.
383     MPM.add(createLICMPass());
384   }
385 
386   // After vectorization and unrolling, assume intrinsics may tell us more
387   // about pointer alignments.
388   MPM.add(createAlignmentFromAssumptionsPass());
389 
390   if (!DisableUnitAtATime) {
391     // FIXME: We shouldn't bother with this anymore.
392     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
393 
394     // GlobalOpt already deletes dead functions and globals, at -O2 try a
395     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
396     if (OptLevel > 1) {
397       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
398       MPM.add(createConstantMergePass());     // Merge dup global constants
399     }
400   }
401 
402   if (MergeFunctions)
403     MPM.add(createMergeFunctionsPass());
404 
405   addExtensionsToPM(EP_OptimizerLast, MPM);
406 }
407 
addLTOOptimizationPasses(legacy::PassManagerBase & PM)408 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
409   // Provide AliasAnalysis services for optimizations.
410   addInitialAliasAnalysisPasses(PM);
411 
412   // Propagate constants at call sites into the functions they call.  This
413   // opens opportunities for globalopt (and inlining) by substituting function
414   // pointers passed as arguments to direct uses of functions.
415   PM.add(createIPSCCPPass());
416 
417   // Now that we internalized some globals, see if we can hack on them!
418   PM.add(createGlobalOptimizerPass());
419 
420   // Linking modules together can lead to duplicated global constants, only
421   // keep one copy of each constant.
422   PM.add(createConstantMergePass());
423 
424   // Remove unused arguments from functions.
425   PM.add(createDeadArgEliminationPass());
426 
427   // Reduce the code after globalopt and ipsccp.  Both can open up significant
428   // simplification opportunities, and both can propagate functions through
429   // function pointers.  When this happens, we often have to resolve varargs
430   // calls, etc, so let instcombine do this.
431   PM.add(createInstructionCombiningPass());
432   addExtensionsToPM(EP_Peephole, PM);
433 
434   // Inline small functions
435   bool RunInliner = Inliner;
436   if (RunInliner) {
437     PM.add(Inliner);
438     Inliner = nullptr;
439   }
440 
441   PM.add(createPruneEHPass());   // Remove dead EH info.
442 
443   // Optimize globals again if we ran the inliner.
444   if (RunInliner)
445     PM.add(createGlobalOptimizerPass());
446   PM.add(createGlobalDCEPass()); // Remove dead functions.
447 
448   // If we didn't decide to inline a function, check to see if we can
449   // transform it to pass arguments by value instead of by reference.
450   PM.add(createArgumentPromotionPass());
451 
452   // The IPO passes may leave cruft around.  Clean up after them.
453   PM.add(createInstructionCombiningPass());
454   addExtensionsToPM(EP_Peephole, PM);
455   PM.add(createJumpThreadingPass());
456 
457   // Break up allocas
458   if (UseNewSROA)
459     PM.add(createSROAPass());
460   else
461     PM.add(createScalarReplAggregatesPass());
462 
463   // Run a few AA driven optimizations here and now, to cleanup the code.
464   PM.add(createFunctionAttrsPass()); // Add nocapture.
465   PM.add(createGlobalsModRefPass()); // IP alias analysis.
466 
467   PM.add(createLICMPass());                 // Hoist loop invariants.
468   if (EnableMLSM)
469     PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
470   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
471   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
472 
473   // Nuke dead stores.
474   PM.add(createDeadStoreEliminationPass());
475 
476   // More loops are countable; try to optimize them.
477   PM.add(createIndVarSimplifyPass());
478   PM.add(createLoopDeletionPass());
479   if (EnableLoopInterchange)
480     PM.add(createLoopInterchangePass());
481 
482   PM.add(createLoopVectorizePass(true, LoopVectorize));
483 
484   // More scalar chains could be vectorized due to more alias information
485   if (RunSLPAfterLoopVectorization)
486     if (SLPVectorize)
487       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
488 
489   // After vectorization, assume intrinsics may tell us more about pointer
490   // alignments.
491   PM.add(createAlignmentFromAssumptionsPass());
492 
493   if (LoadCombine)
494     PM.add(createLoadCombinePass());
495 
496   // Cleanup and simplify the code after the scalar optimizations.
497   PM.add(createInstructionCombiningPass());
498   addExtensionsToPM(EP_Peephole, PM);
499 
500   PM.add(createJumpThreadingPass());
501 }
502 
addLateLTOOptimizationPasses(legacy::PassManagerBase & PM)503 void PassManagerBuilder::addLateLTOOptimizationPasses(
504     legacy::PassManagerBase &PM) {
505   // Delete basic blocks, which optimization passes may have killed.
506   PM.add(createCFGSimplificationPass());
507 
508   // Now that we have optimized the program, discard unreachable functions.
509   PM.add(createGlobalDCEPass());
510 
511   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
512   // currently it damages debug info.
513   if (MergeFunctions)
514     PM.add(createMergeFunctionsPass());
515 }
516 
populateLTOPassManager(legacy::PassManagerBase & PM)517 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
518   if (LibraryInfo)
519     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
520 
521   if (VerifyInput)
522     PM.add(createVerifierPass());
523 
524   if (OptLevel > 1)
525     addLTOOptimizationPasses(PM);
526 
527   // Lower bit sets to globals. This pass supports Clang's control flow
528   // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
529   // is enabled. The pass does nothing if CFI is disabled.
530   PM.add(createLowerBitSetsPass());
531 
532   if (OptLevel != 0)
533     addLateLTOOptimizationPasses(PM);
534 
535   if (VerifyOutput)
536     PM.add(createVerifierPass());
537 }
538 
unwrap(LLVMPassManagerBuilderRef P)539 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
540     return reinterpret_cast<PassManagerBuilder*>(P);
541 }
542 
wrap(PassManagerBuilder * P)543 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
544   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
545 }
546 
LLVMPassManagerBuilderCreate()547 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
548   PassManagerBuilder *PMB = new PassManagerBuilder();
549   return wrap(PMB);
550 }
551 
LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB)552 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
553   PassManagerBuilder *Builder = unwrap(PMB);
554   delete Builder;
555 }
556 
557 void
LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,unsigned OptLevel)558 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
559                                   unsigned OptLevel) {
560   PassManagerBuilder *Builder = unwrap(PMB);
561   Builder->OptLevel = OptLevel;
562 }
563 
564 void
LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,unsigned SizeLevel)565 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
566                                    unsigned SizeLevel) {
567   PassManagerBuilder *Builder = unwrap(PMB);
568   Builder->SizeLevel = SizeLevel;
569 }
570 
571 void
LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,LLVMBool Value)572 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
573                                             LLVMBool Value) {
574   PassManagerBuilder *Builder = unwrap(PMB);
575   Builder->DisableUnitAtATime = Value;
576 }
577 
578 void
LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,LLVMBool Value)579 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
580                                             LLVMBool Value) {
581   PassManagerBuilder *Builder = unwrap(PMB);
582   Builder->DisableUnrollLoops = Value;
583 }
584 
585 void
LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,LLVMBool Value)586 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
587                                                  LLVMBool Value) {
588   // NOTE: The simplify-libcalls pass has been removed.
589 }
590 
591 void
LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,unsigned Threshold)592 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
593                                               unsigned Threshold) {
594   PassManagerBuilder *Builder = unwrap(PMB);
595   Builder->Inliner = createFunctionInliningPass(Threshold);
596 }
597 
598 void
LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,LLVMPassManagerRef PM)599 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
600                                                   LLVMPassManagerRef PM) {
601   PassManagerBuilder *Builder = unwrap(PMB);
602   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
603   Builder->populateFunctionPassManager(*FPM);
604 }
605 
606 void
LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,LLVMPassManagerRef PM)607 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
608                                                 LLVMPassManagerRef PM) {
609   PassManagerBuilder *Builder = unwrap(PMB);
610   legacy::PassManagerBase *MPM = unwrap(PM);
611   Builder->populateModulePassManager(*MPM);
612 }
613 
LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,LLVMPassManagerRef PM,LLVMBool Internalize,LLVMBool RunInliner)614 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
615                                                   LLVMPassManagerRef PM,
616                                                   LLVMBool Internalize,
617                                                   LLVMBool RunInliner) {
618   PassManagerBuilder *Builder = unwrap(PMB);
619   legacy::PassManagerBase *LPM = unwrap(PM);
620 
621   // A small backwards compatibility hack. populateLTOPassManager used to take
622   // an RunInliner option.
623   if (RunInliner && !Builder->Inliner)
624     Builder->Inliner = createFunctionInliningPass();
625 
626   Builder->populateLTOPassManager(*LPM);
627 }
628