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