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