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/CFLAliasAnalysis.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/Passes.h"
22 #include "llvm/Analysis/ScopedNoAliasAA.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/FunctionInfo.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/Target/TargetMachine.h"
32 #include "llvm/Transforms/IPO.h"
33 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
34 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Vectorize.h"
37 #include "llvm/Transforms/Instrumentation.h"
38 
39 using namespace llvm;
40 
41 static cl::opt<bool>
42 RunLoopVectorization("vectorize-loops", cl::Hidden,
43                      cl::desc("Run the Loop vectorization passes"));
44 
45 static cl::opt<bool>
46 RunSLPVectorization("vectorize-slp", cl::Hidden,
47                     cl::desc("Run the SLP vectorization passes"));
48 
49 static cl::opt<bool>
50 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
51                     cl::desc("Run the BB vectorization passes"));
52 
53 static cl::opt<bool>
54 UseGVNAfterVectorization("use-gvn-after-vectorization",
55   cl::init(false), cl::Hidden,
56   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
57 
58 static cl::opt<bool> ExtraVectorizerPasses(
59     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
60     cl::desc("Run cleanup optimization passes after vectorization."));
61 
62 static cl::opt<bool> UseNewSROA("use-new-sroa",
63   cl::init(true), cl::Hidden,
64   cl::desc("Enable the new, experimental SROA pass"));
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>
71 RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
72              cl::desc("Run the float2int (float demotion) pass"));
73 
74 static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
75                                     cl::Hidden,
76                                     cl::desc("Run the load combining pass"));
77 
78 static cl::opt<bool>
79 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
80   cl::init(true), cl::Hidden,
81   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
82            "vectorizer instead of before"));
83 
84 static cl::opt<bool> UseCFLAA("use-cfl-aa",
85   cl::init(false), cl::Hidden,
86   cl::desc("Enable the new, experimental CFL alias analysis"));
87 
88 static cl::opt<bool>
89 EnableMLSM("mlsm", cl::init(true), cl::Hidden,
90            cl::desc("Enable motion of merged load and store"));
91 
92 static cl::opt<bool> EnableLoopInterchange(
93     "enable-loopinterchange", cl::init(false), cl::Hidden,
94     cl::desc("Enable the new, experimental LoopInterchange Pass"));
95 
96 static cl::opt<bool> EnableLoopDistribute(
97     "enable-loop-distribute", cl::init(false), cl::Hidden,
98     cl::desc("Enable the new, experimental LoopDistribution Pass"));
99 
100 static cl::opt<bool> EnableNonLTOGlobalsModRef(
101     "enable-non-lto-gmr", cl::init(true), cl::Hidden,
102     cl::desc(
103         "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline."));
104 
105 static cl::opt<bool> EnableLoopLoadElim(
106     "enable-loop-load-elim", cl::init(false), cl::Hidden,
107     cl::desc("Enable the new, experimental LoopLoadElimination Pass"));
108 
109 static cl::opt<std::string> RunPGOInstrGen(
110     "profile-generate", cl::init(""), cl::Hidden,
111     cl::desc("Enable generation phase of PGO instrumentation and specify the "
112              "path of profile data file"));
113 
114 static cl::opt<std::string> RunPGOInstrUse(
115     "profile-use", cl::init(""), cl::Hidden, cl::value_desc("filename"),
116     cl::desc("Enable use phase of PGO instrumentation and specify the path "
117              "of profile data file"));
118 
119 PassManagerBuilder::PassManagerBuilder() {
120     OptLevel = 2;
121     SizeLevel = 0;
122     LibraryInfo = nullptr;
123     Inliner = nullptr;
124     FunctionIndex = nullptr;
125     DisableUnitAtATime = false;
126     DisableUnrollLoops = false;
127     BBVectorize = RunBBVectorization;
128     SLPVectorize = RunSLPVectorization;
129     LoopVectorize = RunLoopVectorization;
130     RerollLoops = RunLoopRerolling;
131     LoadCombine = RunLoadCombine;
132     DisableGVNLoadPRE = false;
133     VerifyInput = false;
134     VerifyOutput = false;
135     MergeFunctions = false;
136     PrepareForLTO = false;
137     PGOInstrGen = RunPGOInstrGen;
138     PGOInstrUse = RunPGOInstrUse;
139 }
140 
141 PassManagerBuilder::~PassManagerBuilder() {
142   delete LibraryInfo;
143   delete Inliner;
144 }
145 
146 /// Set of global extensions, automatically added as part of the standard set.
147 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
148    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
149 
150 void PassManagerBuilder::addGlobalExtension(
151     PassManagerBuilder::ExtensionPointTy Ty,
152     PassManagerBuilder::ExtensionFn Fn) {
153   GlobalExtensions->push_back(std::make_pair(Ty, Fn));
154 }
155 
156 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
157   Extensions.push_back(std::make_pair(Ty, Fn));
158 }
159 
160 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
161                                            legacy::PassManagerBase &PM) const {
162   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
163     if ((*GlobalExtensions)[i].first == ETy)
164       (*GlobalExtensions)[i].second(*this, PM);
165   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
166     if (Extensions[i].first == ETy)
167       Extensions[i].second(*this, PM);
168 }
169 
170 void PassManagerBuilder::addInitialAliasAnalysisPasses(
171     legacy::PassManagerBase &PM) const {
172   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
173   // BasicAliasAnalysis wins if they disagree. This is intended to help
174   // support "obvious" type-punning idioms.
175   if (UseCFLAA)
176     PM.add(createCFLAAWrapperPass());
177   PM.add(createTypeBasedAAWrapperPass());
178   PM.add(createScopedNoAliasAAWrapperPass());
179 }
180 
181 void PassManagerBuilder::populateFunctionPassManager(
182     legacy::FunctionPassManager &FPM) {
183   addExtensionsToPM(EP_EarlyAsPossible, FPM);
184 
185   // Add LibraryInfo if we have some.
186   if (LibraryInfo)
187     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
188 
189   if (OptLevel == 0) return;
190 
191   addInitialAliasAnalysisPasses(FPM);
192 
193   FPM.add(createCFGSimplificationPass());
194   if (UseNewSROA)
195     FPM.add(createSROAPass());
196   else
197     FPM.add(createScalarReplAggregatesPass());
198   FPM.add(createEarlyCSEPass());
199   FPM.add(createLowerExpectIntrinsicPass());
200 }
201 
202 // Do PGO instrumentation generation or use pass as the option specified.
203 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM) {
204   if (!PGOInstrGen.empty()) {
205     MPM.add(createPGOInstrumentationGenPass());
206     // Add the profile lowering pass.
207     InstrProfOptions Options;
208     Options.InstrProfileOutput = PGOInstrGen;
209     MPM.add(createInstrProfilingPass(Options));
210   }
211   if (!PGOInstrUse.empty())
212     MPM.add(createPGOInstrumentationUsePass(PGOInstrUse));
213 }
214 
215 void PassManagerBuilder::populateModulePassManager(
216     legacy::PassManagerBase &MPM) {
217   // Allow forcing function attributes as a debugging and tuning aid.
218   MPM.add(createForceFunctionAttrsLegacyPass());
219 
220   // If all optimizations are disabled, just run the always-inline pass and,
221   // if enabled, the function merging pass.
222   if (OptLevel == 0) {
223     addPGOInstrPasses(MPM);
224     if (Inliner) {
225       MPM.add(Inliner);
226       Inliner = nullptr;
227     }
228 
229     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
230     // creates a CGSCC pass manager, but we don't want to add extensions into
231     // that pass manager. To prevent this we insert a no-op module pass to reset
232     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
233     // builds. The function merging pass is
234     if (MergeFunctions)
235       MPM.add(createMergeFunctionsPass());
236     else if (!GlobalExtensions->empty() || !Extensions.empty())
237       MPM.add(createBarrierNoopPass());
238 
239     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
240     return;
241   }
242 
243   // Add LibraryInfo if we have some.
244   if (LibraryInfo)
245     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
246 
247   addInitialAliasAnalysisPasses(MPM);
248 
249   if (!DisableUnitAtATime) {
250     // Infer attributes about declarations if possible.
251     MPM.add(createInferFunctionAttrsLegacyPass());
252 
253     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
254 
255     MPM.add(createIPSCCPPass());              // IP SCCP
256     MPM.add(createGlobalOptimizerPass());     // Optimize out global vars
257     // Promote any localized global vars
258     MPM.add(createPromoteMemoryToRegisterPass());
259 
260     MPM.add(createDeadArgEliminationPass());  // Dead argument elimination
261 
262     MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
263     addExtensionsToPM(EP_Peephole, MPM);
264     MPM.add(createCFGSimplificationPass());   // Clean up after IPCP & DAE
265   }
266 
267   addPGOInstrPasses(MPM);
268 
269   if (EnableNonLTOGlobalsModRef)
270     // We add a module alias analysis pass here. In part due to bugs in the
271     // analysis infrastructure this "works" in that the analysis stays alive
272     // for the entire SCC pass run below.
273     MPM.add(createGlobalsAAWrapperPass());
274 
275   // Start of CallGraph SCC passes.
276   if (!DisableUnitAtATime)
277     MPM.add(createPruneEHPass());             // Remove dead EH info
278   if (Inliner) {
279     MPM.add(Inliner);
280     Inliner = nullptr;
281   }
282   if (!DisableUnitAtATime)
283     MPM.add(createPostOrderFunctionAttrsPass());
284   if (OptLevel > 2)
285     MPM.add(createArgumentPromotionPass());   // Scalarize uninlined fn args
286 
287   // Start of function pass.
288   // Break up aggregate allocas, using SSAUpdater.
289   if (UseNewSROA)
290     MPM.add(createSROAPass());
291   else
292     MPM.add(createScalarReplAggregatesPass(-1, false));
293   MPM.add(createEarlyCSEPass());              // Catch trivial redundancies
294   MPM.add(createJumpThreadingPass());         // Thread jumps.
295   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
296   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
297   MPM.add(createInstructionCombiningPass());  // Combine silly seq's
298   addExtensionsToPM(EP_Peephole, MPM);
299 
300   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
301   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
302   MPM.add(createReassociatePass());           // Reassociate expressions
303   // Rotate Loop - disable header duplication at -Oz
304   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
305   MPM.add(createLICMPass());                  // Hoist loop invariants
306   MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
307   MPM.add(createCFGSimplificationPass());
308   MPM.add(createInstructionCombiningPass());
309   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
310   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
311   MPM.add(createLoopDeletionPass());          // Delete dead loops
312   if (EnableLoopInterchange) {
313     MPM.add(createLoopInterchangePass()); // Interchange loops
314     MPM.add(createCFGSimplificationPass());
315   }
316   if (!DisableUnrollLoops)
317     MPM.add(createSimpleLoopUnrollPass());    // Unroll small loops
318   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
319 
320   if (OptLevel > 1) {
321     if (EnableMLSM)
322       MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
323     MPM.add(createGVNPass(DisableGVNLoadPRE));  // Remove redundancies
324   }
325   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
326   MPM.add(createSCCPPass());                  // Constant prop with SCCP
327 
328   // Delete dead bit computations (instcombine runs after to fold away the dead
329   // computations, and then ADCE will run later to exploit any new DCE
330   // opportunities that creates).
331   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
332 
333   // Run instcombine after redundancy elimination to exploit opportunities
334   // opened up by them.
335   MPM.add(createInstructionCombiningPass());
336   addExtensionsToPM(EP_Peephole, MPM);
337   MPM.add(createJumpThreadingPass());         // Thread jumps
338   MPM.add(createCorrelatedValuePropagationPass());
339   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
340   MPM.add(createLICMPass());
341 
342   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
343 
344   if (RerollLoops)
345     MPM.add(createLoopRerollPass());
346   if (!RunSLPAfterLoopVectorization) {
347     if (SLPVectorize)
348       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
349 
350     if (BBVectorize) {
351       MPM.add(createBBVectorizePass());
352       MPM.add(createInstructionCombiningPass());
353       addExtensionsToPM(EP_Peephole, MPM);
354       if (OptLevel > 1 && UseGVNAfterVectorization)
355         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
356       else
357         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
358 
359       // BBVectorize may have significantly shortened a loop body; unroll again.
360       if (!DisableUnrollLoops)
361         MPM.add(createLoopUnrollPass());
362     }
363   }
364 
365   if (LoadCombine)
366     MPM.add(createLoadCombinePass());
367 
368   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
369   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
370   MPM.add(createInstructionCombiningPass());  // Clean up after everything.
371   addExtensionsToPM(EP_Peephole, MPM);
372 
373   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
374   // pass manager that we are specifically trying to avoid. To prevent this
375   // we must insert a no-op module pass to reset the pass manager.
376   MPM.add(createBarrierNoopPass());
377 
378   if (!DisableUnitAtATime)
379     MPM.add(createReversePostOrderFunctionAttrsPass());
380 
381   if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO) {
382     // Remove avail extern fns and globals definitions if we aren't
383     // compiling an object file for later LTO. For LTO we want to preserve
384     // these so they are eligible for inlining at link-time. Note if they
385     // are unreferenced they will be removed by GlobalDCE later, so
386     // this only impacts referenced available externally globals.
387     // Eventually they will be suppressed during codegen, but eliminating
388     // here enables more opportunity for GlobalDCE as it may make
389     // globals referenced by available external functions dead
390     // and saves running remaining passes on the eliminated functions.
391     MPM.add(createEliminateAvailableExternallyPass());
392   }
393 
394   if (EnableNonLTOGlobalsModRef)
395     // We add a fresh GlobalsModRef run at this point. This is particularly
396     // useful as the above will have inlined, DCE'ed, and function-attr
397     // propagated everything. We should at this point have a reasonably minimal
398     // and richly annotated call graph. By computing aliasing and mod/ref
399     // information for all local globals here, the late loop passes and notably
400     // the vectorizer will be able to use them to help recognize vectorizable
401     // memory operations.
402     //
403     // Note that this relies on a bug in the pass manager which preserves
404     // a module analysis into a function pass pipeline (and throughout it) so
405     // long as the first function pass doesn't invalidate the module analysis.
406     // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
407     // this to work. Fortunately, it is trivial to preserve AliasAnalysis
408     // (doing nothing preserves it as it is required to be conservatively
409     // correct in the face of IR changes).
410     MPM.add(createGlobalsAAWrapperPass());
411 
412   if (RunFloat2Int)
413     MPM.add(createFloat2IntPass());
414 
415   addExtensionsToPM(EP_VectorizerStart, MPM);
416 
417   // Re-rotate loops in all our loop nests. These may have fallout out of
418   // rotated form due to GVN or other transformations, and the vectorizer relies
419   // on the rotated form. Disable header duplication at -Oz.
420   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
421 
422   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
423   // into separate loop that would otherwise inhibit vectorization.
424   if (EnableLoopDistribute)
425     MPM.add(createLoopDistributePass());
426 
427   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
428 
429   // Eliminate loads by forwarding stores from the previous iteration to loads
430   // of the current iteration.
431   if (EnableLoopLoadElim)
432     MPM.add(createLoopLoadEliminationPass());
433 
434   // FIXME: Because of #pragma vectorize enable, the passes below are always
435   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
436   // on -O1 and no #pragma is found). Would be good to have these two passes
437   // as function calls, so that we can only pass them when the vectorizer
438   // changed the code.
439   MPM.add(createInstructionCombiningPass());
440   if (OptLevel > 1 && ExtraVectorizerPasses) {
441     // At higher optimization levels, try to clean up any runtime overlap and
442     // alignment checks inserted by the vectorizer. We want to track correllated
443     // runtime checks for two inner loops in the same outer loop, fold any
444     // common computations, hoist loop-invariant aspects out of any outer loop,
445     // and unswitch the runtime checks if possible. Once hoisted, we may have
446     // dead (or speculatable) control flows or more combining opportunities.
447     MPM.add(createEarlyCSEPass());
448     MPM.add(createCorrelatedValuePropagationPass());
449     MPM.add(createInstructionCombiningPass());
450     MPM.add(createLICMPass());
451     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
452     MPM.add(createCFGSimplificationPass());
453     MPM.add(createInstructionCombiningPass());
454   }
455 
456   if (RunSLPAfterLoopVectorization) {
457     if (SLPVectorize) {
458       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
459       if (OptLevel > 1 && ExtraVectorizerPasses) {
460         MPM.add(createEarlyCSEPass());
461       }
462     }
463 
464     if (BBVectorize) {
465       MPM.add(createBBVectorizePass());
466       MPM.add(createInstructionCombiningPass());
467       addExtensionsToPM(EP_Peephole, MPM);
468       if (OptLevel > 1 && UseGVNAfterVectorization)
469         MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
470       else
471         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
472 
473       // BBVectorize may have significantly shortened a loop body; unroll again.
474       if (!DisableUnrollLoops)
475         MPM.add(createLoopUnrollPass());
476     }
477   }
478 
479   addExtensionsToPM(EP_Peephole, MPM);
480   MPM.add(createCFGSimplificationPass());
481   MPM.add(createInstructionCombiningPass());
482 
483   if (!DisableUnrollLoops) {
484     MPM.add(createLoopUnrollPass());    // Unroll small loops
485 
486     // LoopUnroll may generate some redundency to cleanup.
487     MPM.add(createInstructionCombiningPass());
488 
489     // Runtime unrolling will introduce runtime check in loop prologue. If the
490     // unrolled loop is a inner loop, then the prologue will be inside the
491     // outer loop. LICM pass can help to promote the runtime check out if the
492     // checked value is loop invariant.
493     MPM.add(createLICMPass());
494   }
495 
496   // After vectorization and unrolling, assume intrinsics may tell us more
497   // about pointer alignments.
498   MPM.add(createAlignmentFromAssumptionsPass());
499 
500   if (!DisableUnitAtATime) {
501     // FIXME: We shouldn't bother with this anymore.
502     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
503 
504     // GlobalOpt already deletes dead functions and globals, at -O2 try a
505     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
506     if (OptLevel > 1) {
507       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
508       MPM.add(createConstantMergePass());     // Merge dup global constants
509     }
510   }
511 
512   if (MergeFunctions)
513     MPM.add(createMergeFunctionsPass());
514 
515   addExtensionsToPM(EP_OptimizerLast, MPM);
516 }
517 
518 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
519   // Provide AliasAnalysis services for optimizations.
520   addInitialAliasAnalysisPasses(PM);
521 
522   if (FunctionIndex)
523     PM.add(createFunctionImportPass(FunctionIndex));
524 
525   // Allow forcing function attributes as a debugging and tuning aid.
526   PM.add(createForceFunctionAttrsLegacyPass());
527 
528   // Infer attributes about declarations if possible.
529   PM.add(createInferFunctionAttrsLegacyPass());
530 
531   // Propagate constants at call sites into the functions they call.  This
532   // opens opportunities for globalopt (and inlining) by substituting function
533   // pointers passed as arguments to direct uses of functions.
534   PM.add(createIPSCCPPass());
535 
536   // Now that we internalized some globals, see if we can hack on them!
537   PM.add(createPostOrderFunctionAttrsPass());
538   PM.add(createReversePostOrderFunctionAttrsPass());
539   PM.add(createGlobalOptimizerPass());
540   // Promote any localized global vars.
541   PM.add(createPromoteMemoryToRegisterPass());
542 
543   // Linking modules together can lead to duplicated global constants, only
544   // keep one copy of each constant.
545   PM.add(createConstantMergePass());
546 
547   // Remove unused arguments from functions.
548   PM.add(createDeadArgEliminationPass());
549 
550   // Reduce the code after globalopt and ipsccp.  Both can open up significant
551   // simplification opportunities, and both can propagate functions through
552   // function pointers.  When this happens, we often have to resolve varargs
553   // calls, etc, so let instcombine do this.
554   PM.add(createInstructionCombiningPass());
555   addExtensionsToPM(EP_Peephole, PM);
556 
557   // Inline small functions
558   bool RunInliner = Inliner;
559   if (RunInliner) {
560     PM.add(Inliner);
561     Inliner = nullptr;
562   }
563 
564   PM.add(createPruneEHPass());   // Remove dead EH info.
565 
566   // Optimize globals again if we ran the inliner.
567   if (RunInliner)
568     PM.add(createGlobalOptimizerPass());
569   PM.add(createGlobalDCEPass()); // Remove dead functions.
570 
571   // If we didn't decide to inline a function, check to see if we can
572   // transform it to pass arguments by value instead of by reference.
573   PM.add(createArgumentPromotionPass());
574 
575   // The IPO passes may leave cruft around.  Clean up after them.
576   PM.add(createInstructionCombiningPass());
577   addExtensionsToPM(EP_Peephole, PM);
578   PM.add(createJumpThreadingPass());
579 
580   // Break up allocas
581   if (UseNewSROA)
582     PM.add(createSROAPass());
583   else
584     PM.add(createScalarReplAggregatesPass());
585 
586   // Run a few AA driven optimizations here and now, to cleanup the code.
587   PM.add(createPostOrderFunctionAttrsPass()); // Add nocapture.
588   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
589 
590   PM.add(createLICMPass());                 // Hoist loop invariants.
591   if (EnableMLSM)
592     PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
593   PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
594   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
595 
596   // Nuke dead stores.
597   PM.add(createDeadStoreEliminationPass());
598 
599   // More loops are countable; try to optimize them.
600   PM.add(createIndVarSimplifyPass());
601   PM.add(createLoopDeletionPass());
602   if (EnableLoopInterchange)
603     PM.add(createLoopInterchangePass());
604 
605   if (!DisableUnrollLoops)
606     PM.add(createSimpleLoopUnrollPass());   // Unroll small loops
607   PM.add(createLoopVectorizePass(true, LoopVectorize));
608   // The vectorizer may have significantly shortened a loop body; unroll again.
609   if (!DisableUnrollLoops)
610     PM.add(createLoopUnrollPass());
611 
612   // Now that we've optimized loops (in particular loop induction variables),
613   // we may have exposed more scalar opportunities. Run parts of the scalar
614   // optimizer again at this point.
615   PM.add(createInstructionCombiningPass()); // Initial cleanup
616   PM.add(createCFGSimplificationPass()); // if-convert
617   PM.add(createSCCPPass()); // Propagate exposed constants
618   PM.add(createInstructionCombiningPass()); // Clean up again
619   PM.add(createBitTrackingDCEPass());
620 
621   // More scalar chains could be vectorized due to more alias information
622   if (RunSLPAfterLoopVectorization)
623     if (SLPVectorize)
624       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
625 
626   // After vectorization, assume intrinsics may tell us more about pointer
627   // alignments.
628   PM.add(createAlignmentFromAssumptionsPass());
629 
630   if (LoadCombine)
631     PM.add(createLoadCombinePass());
632 
633   // Cleanup and simplify the code after the scalar optimizations.
634   PM.add(createInstructionCombiningPass());
635   addExtensionsToPM(EP_Peephole, PM);
636 
637   PM.add(createJumpThreadingPass());
638 }
639 
640 void PassManagerBuilder::addLateLTOOptimizationPasses(
641     legacy::PassManagerBase &PM) {
642   // Delete basic blocks, which optimization passes may have killed.
643   PM.add(createCFGSimplificationPass());
644 
645   // Drop bodies of available externally objects to improve GlobalDCE.
646   PM.add(createEliminateAvailableExternallyPass());
647 
648   // Now that we have optimized the program, discard unreachable functions.
649   PM.add(createGlobalDCEPass());
650 
651   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
652   // currently it damages debug info.
653   if (MergeFunctions)
654     PM.add(createMergeFunctionsPass());
655 }
656 
657 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
658   if (LibraryInfo)
659     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
660 
661   if (VerifyInput)
662     PM.add(createVerifierPass());
663 
664   if (OptLevel > 1)
665     addLTOOptimizationPasses(PM);
666 
667   // Create a function that performs CFI checks for cross-DSO calls with targets
668   // in the current module.
669   PM.add(createCrossDSOCFIPass());
670 
671   // Lower bit sets to globals. This pass supports Clang's control flow
672   // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
673   // is enabled. The pass does nothing if CFI is disabled.
674   PM.add(createLowerBitSetsPass());
675 
676   if (OptLevel != 0)
677     addLateLTOOptimizationPasses(PM);
678 
679   if (VerifyOutput)
680     PM.add(createVerifierPass());
681 }
682 
683 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
684     return reinterpret_cast<PassManagerBuilder*>(P);
685 }
686 
687 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
688   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
689 }
690 
691 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
692   PassManagerBuilder *PMB = new PassManagerBuilder();
693   return wrap(PMB);
694 }
695 
696 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
697   PassManagerBuilder *Builder = unwrap(PMB);
698   delete Builder;
699 }
700 
701 void
702 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
703                                   unsigned OptLevel) {
704   PassManagerBuilder *Builder = unwrap(PMB);
705   Builder->OptLevel = OptLevel;
706 }
707 
708 void
709 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
710                                    unsigned SizeLevel) {
711   PassManagerBuilder *Builder = unwrap(PMB);
712   Builder->SizeLevel = SizeLevel;
713 }
714 
715 void
716 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
717                                             LLVMBool Value) {
718   PassManagerBuilder *Builder = unwrap(PMB);
719   Builder->DisableUnitAtATime = Value;
720 }
721 
722 void
723 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
724                                             LLVMBool Value) {
725   PassManagerBuilder *Builder = unwrap(PMB);
726   Builder->DisableUnrollLoops = Value;
727 }
728 
729 void
730 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
731                                                  LLVMBool Value) {
732   // NOTE: The simplify-libcalls pass has been removed.
733 }
734 
735 void
736 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
737                                               unsigned Threshold) {
738   PassManagerBuilder *Builder = unwrap(PMB);
739   Builder->Inliner = createFunctionInliningPass(Threshold);
740 }
741 
742 void
743 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
744                                                   LLVMPassManagerRef PM) {
745   PassManagerBuilder *Builder = unwrap(PMB);
746   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
747   Builder->populateFunctionPassManager(*FPM);
748 }
749 
750 void
751 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
752                                                 LLVMPassManagerRef PM) {
753   PassManagerBuilder *Builder = unwrap(PMB);
754   legacy::PassManagerBase *MPM = unwrap(PM);
755   Builder->populateModulePassManager(*MPM);
756 }
757 
758 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
759                                                   LLVMPassManagerRef PM,
760                                                   LLVMBool Internalize,
761                                                   LLVMBool RunInliner) {
762   PassManagerBuilder *Builder = unwrap(PMB);
763   legacy::PassManagerBase *LPM = unwrap(PM);
764 
765   // A small backwards compatibility hack. populateLTOPassManager used to take
766   // an RunInliner option.
767   if (RunInliner && !Builder->Inliner)
768     Builder->Inliner = createFunctionInliningPass();
769 
770   Builder->populateLTOPassManager(*LPM);
771 }
772