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