1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the PassManagerBuilder class, which is used to set up a
10 // "standard" optimization sequence suitable for languages like C and C++.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
15 #include "llvm-c/Transforms/PassManagerBuilder.h"
16 #include "llvm/ADT/STLExtras.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/Verifier.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Target/CGPassBuilderOption.h"
33 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/IPO/Attributor.h"
36 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
37 #include "llvm/Transforms/IPO/FunctionAttrs.h"
38 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
39 #include "llvm/Transforms/InstCombine/InstCombine.h"
40 #include "llvm/Transforms/Instrumentation.h"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/Transforms/Scalar/GVN.h"
43 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
44 #include "llvm/Transforms/Scalar/LICM.h"
45 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
46 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
47 #include "llvm/Transforms/Utils.h"
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
50 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
51 #include "llvm/Transforms/Vectorize/VectorCombine.h"
52 
53 using namespace llvm;
54 
55 namespace llvm {
56 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::init(false),
57                                  cl::Hidden, cl::ZeroOrMore,
58                                  cl::desc("Run Partial inlinining pass"));
59 
60 static cl::opt<bool>
61 UseGVNAfterVectorization("use-gvn-after-vectorization",
62   cl::init(false), cl::Hidden,
63   cl::desc("Run GVN instead of Early CSE after vectorization passes"));
64 
65 cl::opt<bool> ExtraVectorizerPasses(
66     "extra-vectorizer-passes", cl::init(false), cl::Hidden,
67     cl::desc("Run cleanup optimization passes after vectorization."));
68 
69 static cl::opt<bool>
70 RunLoopRerolling("reroll-loops", cl::Hidden,
71                  cl::desc("Run the loop rerolling pass"));
72 
73 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
74                         cl::desc("Run the NewGVN pass"));
75 
76 // Experimental option to use CFL-AA
77 static cl::opt<::CFLAAType>
78     UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden,
79              cl::desc("Enable the new, experimental CFL alias analysis"),
80              cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"),
81                         clEnumValN(::CFLAAType::Steensgaard, "steens",
82                                    "Enable unification-based CFL-AA"),
83                         clEnumValN(::CFLAAType::Andersen, "anders",
84                                    "Enable inclusion-based CFL-AA"),
85                         clEnumValN(::CFLAAType::Both, "both",
86                                    "Enable both variants of CFL-AA")));
87 
88 cl::opt<bool> EnableLoopInterchange(
89     "enable-loopinterchange", cl::init(false), cl::Hidden,
90     cl::desc("Enable the experimental LoopInterchange Pass"));
91 
92 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false),
93                                  cl::Hidden,
94                                  cl::desc("Enable Unroll And Jam Pass"));
95 
96 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false),
97                                 cl::Hidden,
98                                 cl::desc("Enable the LoopFlatten Pass"));
99 
100 static cl::opt<bool>
101     EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
102                             cl::desc("Enable preparation for ThinLTO."));
103 
104 static cl::opt<bool>
105     EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden,
106                          cl::desc("Enable performing ThinLTO."));
107 
108 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false),
109     cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass"));
110 
111 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden,
112     cl::desc("Enable ir outliner pass"));
113 
114 static cl::opt<bool> UseLoopVersioningLICM(
115     "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
116     cl::desc("Enable the experimental Loop Versioning LICM pass"));
117 
118 cl::opt<bool>
119     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
120                       cl::desc("Disable pre-instrumentation inliner"));
121 
122 cl::opt<int> PreInlineThreshold(
123     "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
124     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
125              "(default = 75)"));
126 
127 cl::opt<bool>
128     EnableGVNHoist("enable-gvn-hoist", cl::init(false), cl::ZeroOrMore,
129                    cl::desc("Enable the GVN hoisting pass (default = off)"));
130 
131 static cl::opt<bool>
132     DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
133                               cl::Hidden,
134                               cl::desc("Disable shrink-wrap library calls"));
135 
136 static cl::opt<bool> EnableSimpleLoopUnswitch(
137     "enable-simple-loop-unswitch", cl::init(false), cl::Hidden,
138     cl::desc("Enable the simple loop unswitch pass. Also enables independent "
139              "cleanup passes integrated into the loop pass manager pipeline."));
140 
141 cl::opt<bool>
142     EnableGVNSink("enable-gvn-sink", cl::init(false), cl::ZeroOrMore,
143                   cl::desc("Enable the GVN sinking pass (default = off)"));
144 
145 // This option is used in simplifying testing SampleFDO optimizations for
146 // profile loading.
147 cl::opt<bool>
148     EnableCHR("enable-chr", cl::init(true), cl::Hidden,
149               cl::desc("Enable control height reduction optimization (CHR)"));
150 
151 cl::opt<bool> FlattenedProfileUsed(
152     "flattened-profile-used", cl::init(false), cl::Hidden,
153     cl::desc("Indicate the sample profile being used is flattened, i.e., "
154              "no inline hierachy exists in the profile. "));
155 
156 cl::opt<bool> EnableOrderFileInstrumentation(
157     "enable-order-file-instrumentation", cl::init(false), cl::Hidden,
158     cl::desc("Enable order file instrumentation (default = off)"));
159 
160 cl::opt<bool> EnableMatrix(
161     "enable-matrix", cl::init(false), cl::Hidden,
162     cl::desc("Enable lowering of the matrix intrinsics"));
163 
164 cl::opt<bool> EnableConstraintElimination(
165     "enable-constraint-elimination", cl::init(false), cl::Hidden,
166     cl::desc(
167         "Enable pass to eliminate conditions based on linear constraints."));
168 
169 cl::opt<AttributorRunOption> AttributorRun(
170     "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE),
171     cl::desc("Enable the attributor inter-procedural deduction pass."),
172     cl::values(clEnumValN(AttributorRunOption::ALL, "all",
173                           "enable all attributor runs"),
174                clEnumValN(AttributorRunOption::MODULE, "module",
175                           "enable module-wide attributor runs"),
176                clEnumValN(AttributorRunOption::CGSCC, "cgscc",
177                           "enable call graph SCC attributor runs"),
178                clEnumValN(AttributorRunOption::NONE, "none",
179                           "disable attributor runs")));
180 
181 extern cl::opt<bool> EnableKnowledgeRetention;
182 } // namespace llvm
183 
184 PassManagerBuilder::PassManagerBuilder() {
185     OptLevel = 2;
186     SizeLevel = 0;
187     LibraryInfo = nullptr;
188     Inliner = nullptr;
189     DisableUnrollLoops = false;
190     SLPVectorize = false;
191     LoopVectorize = true;
192     LoopsInterleaved = true;
193     RerollLoops = RunLoopRerolling;
194     NewGVN = RunNewGVN;
195     LicmMssaOptCap = SetLicmMssaOptCap;
196     LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
197     DisableGVNLoadPRE = false;
198     ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
199     VerifyInput = false;
200     VerifyOutput = false;
201     MergeFunctions = false;
202     PrepareForLTO = false;
203     EnablePGOInstrGen = false;
204     EnablePGOCSInstrGen = false;
205     EnablePGOCSInstrUse = false;
206     PGOInstrGen = "";
207     PGOInstrUse = "";
208     PGOSampleUse = "";
209     PrepareForThinLTO = EnablePrepareForThinLTO;
210     PerformThinLTO = EnablePerformThinLTO;
211     DivergentTarget = false;
212     CallGraphProfile = true;
213 }
214 
215 PassManagerBuilder::~PassManagerBuilder() {
216   delete LibraryInfo;
217   delete Inliner;
218 }
219 
220 /// Set of global extensions, automatically added as part of the standard set.
221 static ManagedStatic<
222     SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy,
223                            PassManagerBuilder::ExtensionFn,
224                            PassManagerBuilder::GlobalExtensionID>,
225                 8>>
226     GlobalExtensions;
227 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter;
228 
229 /// Check if GlobalExtensions is constructed and not empty.
230 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger
231 /// the construction of the object.
232 static bool GlobalExtensionsNotEmpty() {
233   return GlobalExtensions.isConstructed() && !GlobalExtensions->empty();
234 }
235 
236 PassManagerBuilder::GlobalExtensionID
237 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty,
238                                        PassManagerBuilder::ExtensionFn Fn) {
239   auto ExtensionID = GlobalExtensionsCounter++;
240   GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID));
241   return ExtensionID;
242 }
243 
244 void PassManagerBuilder::removeGlobalExtension(
245     PassManagerBuilder::GlobalExtensionID ExtensionID) {
246   // RegisterStandardPasses may try to call this function after GlobalExtensions
247   // has already been destroyed; doing so should not generate an error.
248   if (!GlobalExtensions.isConstructed())
249     return;
250 
251   auto GlobalExtension =
252       llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) {
253         return std::get<2>(elem) == ExtensionID;
254       });
255   assert(GlobalExtension != GlobalExtensions->end() &&
256          "The extension ID to be removed should always be valid.");
257 
258   GlobalExtensions->erase(GlobalExtension);
259 }
260 
261 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
262   Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
263 }
264 
265 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
266                                            legacy::PassManagerBase &PM) const {
267   if (GlobalExtensionsNotEmpty()) {
268     for (auto &Ext : *GlobalExtensions) {
269       if (std::get<0>(Ext) == ETy)
270         std::get<1>(Ext)(*this, PM);
271     }
272   }
273   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
274     if (Extensions[i].first == ETy)
275       Extensions[i].second(*this, PM);
276 }
277 
278 void PassManagerBuilder::addInitialAliasAnalysisPasses(
279     legacy::PassManagerBase &PM) const {
280   switch (UseCFLAA) {
281   case ::CFLAAType::Steensgaard:
282     PM.add(createCFLSteensAAWrapperPass());
283     break;
284   case ::CFLAAType::Andersen:
285     PM.add(createCFLAndersAAWrapperPass());
286     break;
287   case ::CFLAAType::Both:
288     PM.add(createCFLSteensAAWrapperPass());
289     PM.add(createCFLAndersAAWrapperPass());
290     break;
291   default:
292     break;
293   }
294 
295   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
296   // BasicAliasAnalysis wins if they disagree. This is intended to help
297   // support "obvious" type-punning idioms.
298   PM.add(createTypeBasedAAWrapperPass());
299   PM.add(createScopedNoAliasAAWrapperPass());
300 }
301 
302 void PassManagerBuilder::populateFunctionPassManager(
303     legacy::FunctionPassManager &FPM) {
304   addExtensionsToPM(EP_EarlyAsPossible, FPM);
305 
306   // Add LibraryInfo if we have some.
307   if (LibraryInfo)
308     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
309 
310   // The backends do not handle matrix intrinsics currently.
311   // Make sure they are also lowered in O0.
312   // FIXME: A lightweight version of the pass should run in the backend
313   //        pipeline on demand.
314   if (EnableMatrix && OptLevel == 0)
315     FPM.add(createLowerMatrixIntrinsicsMinimalPass());
316 
317   if (OptLevel == 0) return;
318 
319   addInitialAliasAnalysisPasses(FPM);
320 
321   // Lower llvm.expect to metadata before attempting transforms.
322   // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
323   FPM.add(createLowerExpectIntrinsicPass());
324   FPM.add(createCFGSimplificationPass());
325   FPM.add(createSROAPass());
326   FPM.add(createEarlyCSEPass());
327 }
328 
329 // Do PGO instrumentation generation or use pass as the option specified.
330 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM,
331                                            bool IsCS = false) {
332   if (IsCS) {
333     if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse)
334       return;
335   } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty())
336     return;
337 
338   // Perform the preinline and cleanup passes for O1 and above.
339   // We will not do this inline for context sensitive PGO (when IsCS is true).
340   if (OptLevel > 0 && !DisablePreInliner && PGOSampleUse.empty() && !IsCS) {
341     // Create preinline pass. We construct an InlineParams object and specify
342     // the threshold here to avoid the command line options of the regular
343     // inliner to influence pre-inlining. The only fields of InlineParams we
344     // care about are DefaultThreshold and HintThreshold.
345     InlineParams IP;
346     IP.DefaultThreshold = PreInlineThreshold;
347     // FIXME: The hint threshold has the same value used by the regular inliner
348     // when not optimzing for size. This should probably be lowered after
349     // performance testing.
350     // Use PreInlineThreshold for both -Os and -Oz. Not running preinliner makes
351     // the instrumented binary unusably large. Even if PreInlineThreshold is not
352     // correct thresold for -Oz, it is better than not running preinliner.
353     IP.HintThreshold = SizeLevel > 0 ? PreInlineThreshold : 325;
354 
355     MPM.add(createFunctionInliningPass(IP));
356     MPM.add(createSROAPass());
357     MPM.add(createEarlyCSEPass());             // Catch trivial redundancies
358     MPM.add(createCFGSimplificationPass());    // Merge & remove BBs
359     MPM.add(createInstructionCombiningPass()); // Combine silly seq's
360     addExtensionsToPM(EP_Peephole, MPM);
361   }
362   if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) {
363     MPM.add(createPGOInstrumentationGenLegacyPass(IsCS));
364     // Add the profile lowering pass.
365     InstrProfOptions Options;
366     if (!PGOInstrGen.empty())
367       Options.InstrProfileOutput = PGOInstrGen;
368     Options.DoCounterPromotion = true;
369     Options.UseBFIInPromotion = IsCS;
370     MPM.add(createLoopRotatePass());
371     MPM.add(createInstrProfilingLegacyPass(Options, IsCS));
372   }
373   if (!PGOInstrUse.empty())
374     MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS));
375   // Indirect call promotion that promotes intra-module targets only.
376   // For ThinLTO this is done earlier due to interactions with globalopt
377   // for imported functions. We don't run this at -O0.
378   if (OptLevel > 0 && !IsCS)
379     MPM.add(
380         createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
381 }
382 void PassManagerBuilder::addFunctionSimplificationPasses(
383     legacy::PassManagerBase &MPM) {
384   // Start of function pass.
385   // Break up aggregate allocas, using SSAUpdater.
386   assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!");
387   MPM.add(createSROAPass());
388   MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies
389   if (EnableKnowledgeRetention)
390     MPM.add(createAssumeSimplifyPass());
391 
392   if (OptLevel > 1) {
393     if (EnableGVNHoist)
394       MPM.add(createGVNHoistPass());
395     if (EnableGVNSink) {
396       MPM.add(createGVNSinkPass());
397       MPM.add(createCFGSimplificationPass());
398     }
399   }
400 
401   if (EnableConstraintElimination)
402     MPM.add(createConstraintEliminationPass());
403 
404   if (OptLevel > 1) {
405     // Speculative execution if the target has divergent branches; otherwise nop.
406     MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
407 
408     MPM.add(createJumpThreadingPass());         // Thread jumps.
409     MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
410   }
411   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
412   // Combine silly seq's
413   if (OptLevel > 2)
414     MPM.add(createAggressiveInstCombinerPass());
415   MPM.add(createInstructionCombiningPass());
416   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
417     MPM.add(createLibCallsShrinkWrapPass());
418   addExtensionsToPM(EP_Peephole, MPM);
419 
420   // Optimize memory intrinsic calls based on the profiled size information.
421   if (SizeLevel == 0)
422     MPM.add(createPGOMemOPSizeOptLegacyPass());
423 
424   // TODO: Investigate the cost/benefit of tail call elimination on debugging.
425   if (OptLevel > 1)
426     MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
427   MPM.add(createCFGSimplificationPass());      // Merge & remove BBs
428   MPM.add(createReassociatePass());           // Reassociate expressions
429 
430   // Begin the loop pass pipeline.
431   if (EnableSimpleLoopUnswitch) {
432     // The simple loop unswitch pass relies on separate cleanup passes. Schedule
433     // them first so when we re-process a loop they run before other loop
434     // passes.
435     MPM.add(createLoopInstSimplifyPass());
436     MPM.add(createLoopSimplifyCFGPass());
437   }
438   // Try to remove as much code from the loop header as possible,
439   // to reduce amount of IR that will have to be duplicated.
440   // TODO: Investigate promotion cap for O1.
441   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
442   // Rotate Loop - disable header duplication at -Oz
443   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO));
444   // TODO: Investigate promotion cap for O1.
445   MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
446   if (EnableSimpleLoopUnswitch)
447     MPM.add(createSimpleLoopUnswitchLegacyPass());
448   else
449     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
450   // FIXME: We break the loop pass pipeline here in order to do full
451   // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the
452   // need for this.
453   MPM.add(createCFGSimplificationPass());
454   MPM.add(createInstructionCombiningPass());
455   // We resume loop passes creating a second loop pipeline here.
456   if (EnableLoopFlatten) {
457     MPM.add(createLoopFlattenPass()); // Flatten loops
458     MPM.add(createLoopSimplifyCFGPass());
459   }
460   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
461   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
462   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
463   MPM.add(createLoopDeletionPass());          // Delete dead loops
464 
465   if (EnableLoopInterchange)
466     MPM.add(createLoopInterchangePass()); // Interchange loops
467 
468   // Unroll small loops and perform peeling.
469   MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
470                                      ForgetAllSCEVInLoopUnroll));
471   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
472   // This ends the loop pass pipelines.
473 
474   // Break up allocas that may now be splittable after loop unrolling.
475   MPM.add(createSROAPass());
476 
477   if (OptLevel > 1) {
478     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
479     MPM.add(NewGVN ? createNewGVNPass()
480                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
481   }
482   MPM.add(createSCCPPass());                  // Constant prop with SCCP
483 
484   if (EnableConstraintElimination)
485     MPM.add(createConstraintEliminationPass());
486 
487   // Delete dead bit computations (instcombine runs after to fold away the dead
488   // computations, and then ADCE will run later to exploit any new DCE
489   // opportunities that creates).
490   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
491 
492   // Run instcombine after redundancy elimination to exploit opportunities
493   // opened up by them.
494   MPM.add(createInstructionCombiningPass());
495   addExtensionsToPM(EP_Peephole, MPM);
496   if (OptLevel > 1) {
497     MPM.add(createJumpThreadingPass());         // Thread jumps
498     MPM.add(createCorrelatedValuePropagationPass());
499   }
500   MPM.add(createAggressiveDCEPass()); // Delete dead instructions
501 
502   MPM.add(createMemCpyOptPass());               // Remove memcpy / form memset
503   // TODO: Investigate if this is too expensive at O1.
504   if (OptLevel > 1) {
505     MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
506     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
507   }
508 
509   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
510 
511   if (RerollLoops)
512     MPM.add(createLoopRerollPass());
513 
514   // Merge & remove BBs and sink & hoist common instructions.
515   MPM.add(createCFGSimplificationPass(
516       SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true)));
517   // Clean up after everything.
518   MPM.add(createInstructionCombiningPass());
519   addExtensionsToPM(EP_Peephole, MPM);
520 
521   if (EnableCHR && OptLevel >= 3 &&
522       (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen))
523     MPM.add(createControlHeightReductionLegacyPass());
524 }
525 
526 /// FIXME: Should LTO cause any differences to this set of passes?
527 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM,
528                                          bool IsLTO) {
529   PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize));
530 
531   if (IsLTO) {
532     // The vectorizer may have significantly shortened a loop body; unroll
533     // again. Unroll small loops to hide loop backedge latency and saturate any
534     // parallel execution resources of an out-of-order processor. We also then
535     // need to clean up redundancies and loop invariant code.
536     // FIXME: It would be really good to use a loop-integrated instruction
537     // combiner for cleanup here so that the unrolling and LICM can be pipelined
538     // across the loop nests.
539     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
540     if (EnableUnrollAndJam && !DisableUnrollLoops)
541       PM.add(createLoopUnrollAndJamPass(OptLevel));
542     PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
543                                 ForgetAllSCEVInLoopUnroll));
544     PM.add(createWarnMissedTransformationsPass());
545   }
546 
547   if (!IsLTO) {
548     // Eliminate loads by forwarding stores from the previous iteration to loads
549     // of the current iteration.
550     PM.add(createLoopLoadEliminationPass());
551   }
552   // Cleanup after the loop optimization passes.
553   PM.add(createInstructionCombiningPass());
554 
555   if (OptLevel > 1 && ExtraVectorizerPasses) {
556     // At higher optimization levels, try to clean up any runtime overlap and
557     // alignment checks inserted by the vectorizer. We want to track correlated
558     // runtime checks for two inner loops in the same outer loop, fold any
559     // common computations, hoist loop-invariant aspects out of any outer loop,
560     // and unswitch the runtime checks if possible. Once hoisted, we may have
561     // dead (or speculatable) control flows or more combining opportunities.
562     PM.add(createEarlyCSEPass());
563     PM.add(createCorrelatedValuePropagationPass());
564     PM.add(createInstructionCombiningPass());
565     PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
566     PM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
567     PM.add(createCFGSimplificationPass());
568     PM.add(createInstructionCombiningPass());
569   }
570 
571   // Now that we've formed fast to execute loop structures, we do further
572   // optimizations. These are run afterward as they might block doing complex
573   // analyses and transforms such as what are needed for loop vectorization.
574 
575   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
576   // GVN, loop transforms, and others have already run, so it's now better to
577   // convert to more optimized IR using more aggressive simplify CFG options.
578   // The extra sinking transform can create larger basic blocks, so do this
579   // before SLP vectorization.
580   PM.add(createCFGSimplificationPass(SimplifyCFGOptions()
581                                          .forwardSwitchCondToPhi(true)
582                                          .convertSwitchToLookupTable(true)
583                                          .needCanonicalLoops(false)
584                                          .hoistCommonInsts(true)
585                                          .sinkCommonInsts(true)));
586 
587   if (IsLTO) {
588     PM.add(createSCCPPass()); // Propagate exposed constants
589     PM.add(createInstructionCombiningPass()); // Clean up again
590     PM.add(createBitTrackingDCEPass());
591   }
592 
593   // Optimize parallel scalar instruction chains into SIMD instructions.
594   if (SLPVectorize) {
595     PM.add(createSLPVectorizerPass());
596     if (OptLevel > 1 && ExtraVectorizerPasses)
597       PM.add(createEarlyCSEPass());
598   }
599 
600   // Enhance/cleanup vector code.
601   PM.add(createVectorCombinePass());
602 
603   if (IsLTO) {
604     // After vectorization, assume intrinsics may tell us more about pointer
605     // alignments.
606     PM.add(createAlignmentFromAssumptionsPass());
607   }
608   addExtensionsToPM(EP_Peephole, PM);
609   PM.add(createInstructionCombiningPass());
610 
611   if (!IsLTO) {
612     // The vectorizer may have significantly shortened a loop body; unroll
613     // again. Unroll small loops to hide loop backedge latency and saturate any
614     // parallel execution resources of an out-of-order processor. We also then
615     // need to clean up redundancies and loop invariant code.
616     // FIXME: It would be really good to use a loop-integrated instruction
617     // combiner for cleanup here so that the unrolling and LICM can be pipelined
618     // across the loop nests.
619     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
620     if (EnableUnrollAndJam && !DisableUnrollLoops)
621       PM.add(createLoopUnrollAndJamPass(OptLevel));
622     PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops,
623                                 ForgetAllSCEVInLoopUnroll));
624     if (!DisableUnrollLoops)
625       PM.add(createInstructionCombiningPass());
626   }
627 }
628 
629 void PassManagerBuilder::populateModulePassManager(
630     legacy::PassManagerBase &MPM) {
631   // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link
632   // is handled separately, so just check this is not the ThinLTO post-link.
633   bool DefaultOrPreLinkPipeline = !PerformThinLTO;
634 
635   MPM.add(createAnnotation2MetadataLegacyPass());
636 
637   if (!PGOSampleUse.empty()) {
638     MPM.add(createPruneEHPass());
639     // In ThinLTO mode, when flattened profile is used, all the available
640     // profile information will be annotated in PreLink phase so there is
641     // no need to load the profile again in PostLink.
642     if (!(FlattenedProfileUsed && PerformThinLTO))
643       MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
644   }
645 
646   // Allow forcing function attributes as a debugging and tuning aid.
647   MPM.add(createForceFunctionAttrsLegacyPass());
648 
649   // If all optimizations are disabled, just run the always-inline pass and,
650   // if enabled, the function merging pass.
651   if (OptLevel == 0) {
652     addPGOInstrPasses(MPM);
653     if (Inliner) {
654       MPM.add(Inliner);
655       Inliner = nullptr;
656     }
657 
658     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
659     // creates a CGSCC pass manager, but we don't want to add extensions into
660     // that pass manager. To prevent this we insert a no-op module pass to reset
661     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
662     // builds. The function merging pass is
663     if (MergeFunctions)
664       MPM.add(createMergeFunctionsPass());
665     else if (GlobalExtensionsNotEmpty() || !Extensions.empty())
666       MPM.add(createBarrierNoopPass());
667 
668     if (PerformThinLTO) {
669       MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
670       // Drop available_externally and unreferenced globals. This is necessary
671       // with ThinLTO in order to avoid leaving undefined references to dead
672       // globals in the object file.
673       MPM.add(createEliminateAvailableExternallyPass());
674       MPM.add(createGlobalDCEPass());
675     }
676 
677     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
678 
679     if (PrepareForLTO || PrepareForThinLTO) {
680       MPM.add(createCanonicalizeAliasesPass());
681       // Rename anon globals to be able to export them in the summary.
682       // This has to be done after we add the extensions to the pass manager
683       // as there could be passes (e.g. Adddress sanitizer) which introduce
684       // new unnamed globals.
685       MPM.add(createNameAnonGlobalPass());
686     }
687 
688     MPM.add(createAnnotationRemarksLegacyPass());
689     return;
690   }
691 
692   // Add LibraryInfo if we have some.
693   if (LibraryInfo)
694     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
695 
696   addInitialAliasAnalysisPasses(MPM);
697 
698   // For ThinLTO there are two passes of indirect call promotion. The
699   // first is during the compile phase when PerformThinLTO=false and
700   // intra-module indirect call targets are promoted. The second is during
701   // the ThinLTO backend when PerformThinLTO=true, when we promote imported
702   // inter-module indirect calls. For that we perform indirect call promotion
703   // earlier in the pass pipeline, here before globalopt. Otherwise imported
704   // available_externally functions look unreferenced and are removed.
705   if (PerformThinLTO) {
706     MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
707                                                      !PGOSampleUse.empty()));
708     MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
709   }
710 
711   // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
712   // as it will change the CFG too much to make the 2nd profile annotation
713   // in backend more difficult.
714   bool PrepareForThinLTOUsingPGOSampleProfile =
715       PrepareForThinLTO && !PGOSampleUse.empty();
716   if (PrepareForThinLTOUsingPGOSampleProfile)
717     DisableUnrollLoops = true;
718 
719   // Infer attributes about declarations if possible.
720   MPM.add(createInferFunctionAttrsLegacyPass());
721 
722   // Infer attributes on declarations, call sites, arguments, etc.
723   if (AttributorRun & AttributorRunOption::MODULE)
724     MPM.add(createAttributorLegacyPass());
725 
726   addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
727 
728   if (OptLevel > 2)
729     MPM.add(createCallSiteSplittingPass());
730 
731   MPM.add(createIPSCCPPass());          // IP SCCP
732   MPM.add(createCalledValuePropagationPass());
733 
734   MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
735   // Promote any localized global vars.
736   MPM.add(createPromoteMemoryToRegisterPass());
737 
738   MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
739 
740   MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
741   addExtensionsToPM(EP_Peephole, MPM);
742   MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
743 
744   // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
745   // call promotion as it will change the CFG too much to make the 2nd
746   // profile annotation in backend more difficult.
747   // PGO instrumentation is added during the compile phase for ThinLTO, do
748   // not run it a second time
749   if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile)
750     addPGOInstrPasses(MPM);
751 
752   // Create profile COMDAT variables. Lld linker wants to see all variables
753   // before the LTO/ThinLTO link since it needs to resolve symbols/comdats.
754   if (!PerformThinLTO && EnablePGOCSInstrGen)
755     MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen));
756 
757   // We add a module alias analysis pass here. In part due to bugs in the
758   // analysis infrastructure this "works" in that the analysis stays alive
759   // for the entire SCC pass run below.
760   MPM.add(createGlobalsAAWrapperPass());
761 
762   // Start of CallGraph SCC passes.
763   MPM.add(createPruneEHPass()); // Remove dead EH info
764   bool RunInliner = false;
765   if (Inliner) {
766     MPM.add(Inliner);
767     Inliner = nullptr;
768     RunInliner = true;
769   }
770 
771   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
772   if (AttributorRun & AttributorRunOption::CGSCC)
773     MPM.add(createAttributorCGSCCLegacyPass());
774 
775   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
776   // there are no OpenMP runtime calls present in the module.
777   if (OptLevel > 1)
778     MPM.add(createOpenMPOptCGSCCLegacyPass());
779 
780   MPM.add(createPostOrderFunctionAttrsLegacyPass());
781   if (OptLevel > 2)
782     MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
783 
784   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
785   addFunctionSimplificationPasses(MPM);
786 
787   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
788   // pass manager that we are specifically trying to avoid. To prevent this
789   // we must insert a no-op module pass to reset the pass manager.
790   MPM.add(createBarrierNoopPass());
791 
792   if (RunPartialInlining)
793     MPM.add(createPartialInliningPass());
794 
795   if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO)
796     // Remove avail extern fns and globals definitions if we aren't
797     // compiling an object file for later LTO. For LTO we want to preserve
798     // these so they are eligible for inlining at link-time. Note if they
799     // are unreferenced they will be removed by GlobalDCE later, so
800     // this only impacts referenced available externally globals.
801     // Eventually they will be suppressed during codegen, but eliminating
802     // here enables more opportunity for GlobalDCE as it may make
803     // globals referenced by available external functions dead
804     // and saves running remaining passes on the eliminated functions.
805     MPM.add(createEliminateAvailableExternallyPass());
806 
807   // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass
808   // for LTO and ThinLTO -- The actual pass will be called after all inlines
809   // are performed.
810   // Need to do this after COMDAT variables have been eliminated,
811   // (i.e. after EliminateAvailableExternallyPass).
812   if (!(PrepareForLTO || PrepareForThinLTO))
813     addPGOInstrPasses(MPM, /* IsCS */ true);
814 
815   if (EnableOrderFileInstrumentation)
816     MPM.add(createInstrOrderFilePass());
817 
818   MPM.add(createReversePostOrderFunctionAttrsPass());
819 
820   // The inliner performs some kind of dead code elimination as it goes,
821   // but there are cases that are not really caught by it. We might
822   // at some point consider teaching the inliner about them, but it
823   // is OK for now to run GlobalOpt + GlobalDCE in tandem as their
824   // benefits generally outweight the cost, making the whole pipeline
825   // faster.
826   if (RunInliner) {
827     MPM.add(createGlobalOptimizerPass());
828     MPM.add(createGlobalDCEPass());
829   }
830 
831   // If we are planning to perform ThinLTO later, let's not bloat the code with
832   // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
833   // during ThinLTO and perform the rest of the optimizations afterward.
834   if (PrepareForThinLTO) {
835     // Ensure we perform any last passes, but do so before renaming anonymous
836     // globals in case the passes add any.
837     addExtensionsToPM(EP_OptimizerLast, MPM);
838     MPM.add(createCanonicalizeAliasesPass());
839     // Rename anon globals to be able to export them in the summary.
840     MPM.add(createNameAnonGlobalPass());
841     return;
842   }
843 
844   if (PerformThinLTO)
845     // Optimize globals now when performing ThinLTO, this enables more
846     // optimizations later.
847     MPM.add(createGlobalOptimizerPass());
848 
849   // Scheduling LoopVersioningLICM when inlining is over, because after that
850   // we may see more accurate aliasing. Reason to run this late is that too
851   // early versioning may prevent further inlining due to increase of code
852   // size. By placing it just after inlining other optimizations which runs
853   // later might get benefit of no-alias assumption in clone loop.
854   if (UseLoopVersioningLICM) {
855     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
856     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
857   }
858 
859   // We add a fresh GlobalsModRef run at this point. This is particularly
860   // useful as the above will have inlined, DCE'ed, and function-attr
861   // propagated everything. We should at this point have a reasonably minimal
862   // and richly annotated call graph. By computing aliasing and mod/ref
863   // information for all local globals here, the late loop passes and notably
864   // the vectorizer will be able to use them to help recognize vectorizable
865   // memory operations.
866   //
867   // Note that this relies on a bug in the pass manager which preserves
868   // a module analysis into a function pass pipeline (and throughout it) so
869   // long as the first function pass doesn't invalidate the module analysis.
870   // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
871   // this to work. Fortunately, it is trivial to preserve AliasAnalysis
872   // (doing nothing preserves it as it is required to be conservatively
873   // correct in the face of IR changes).
874   MPM.add(createGlobalsAAWrapperPass());
875 
876   MPM.add(createFloat2IntPass());
877   MPM.add(createLowerConstantIntrinsicsPass());
878 
879   if (EnableMatrix) {
880     MPM.add(createLowerMatrixIntrinsicsPass());
881     // CSE the pointer arithmetic of the column vectors.  This allows alias
882     // analysis to establish no-aliasing between loads and stores of different
883     // columns of the same matrix.
884     MPM.add(createEarlyCSEPass(false));
885   }
886 
887   addExtensionsToPM(EP_VectorizerStart, MPM);
888 
889   // Re-rotate loops in all our loop nests. These may have fallout out of
890   // rotated form due to GVN or other transformations, and the vectorizer relies
891   // on the rotated form. Disable header duplication at -Oz.
892   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO));
893 
894   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
895   // into separate loop that would otherwise inhibit vectorization.  This is
896   // currently only performed for loops marked with the metadata
897   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
898   MPM.add(createLoopDistributePass());
899 
900   addVectorPasses(MPM, /* IsLTO */ false);
901 
902   if (!DisableUnrollLoops) {
903     // Runtime unrolling will introduce runtime check in loop prologue. If the
904     // unrolled loop is a inner loop, then the prologue will be inside the
905     // outer loop. LICM pass can help to promote the runtime check out if the
906     // checked value is loop invariant.
907     MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
908   }
909 
910   MPM.add(createWarnMissedTransformationsPass());
911 
912   // After vectorization and unrolling, assume intrinsics may tell us more
913   // about pointer alignments.
914   MPM.add(createAlignmentFromAssumptionsPass());
915 
916   // FIXME: We shouldn't bother with this anymore.
917   MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
918 
919   // GlobalOpt already deletes dead functions and globals, at -O2 try a
920   // late pass of GlobalDCE.  It is capable of deleting dead cycles.
921   if (OptLevel > 1) {
922     MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
923     MPM.add(createConstantMergePass());     // Merge dup global constants
924   }
925 
926   // See comment in the new PM for justification of scheduling splitting at
927   // this stage (\ref buildModuleSimplificationPipeline).
928   if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO))
929     MPM.add(createHotColdSplittingPass());
930 
931   if (EnableIROutliner)
932     MPM.add(createIROutlinerPass());
933 
934   if (MergeFunctions)
935     MPM.add(createMergeFunctionsPass());
936 
937   // Add Module flag "CG Profile" based on Branch Frequency Information.
938   if (CallGraphProfile)
939     MPM.add(createCGProfileLegacyPass());
940 
941   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
942   // canonicalization pass that enables other optimizations. As a result,
943   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
944   // result too early.
945   MPM.add(createLoopSinkPass());
946   // Get rid of LCSSA nodes.
947   MPM.add(createInstSimplifyLegacyPass());
948 
949   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
950   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
951   // flattening of blocks.
952   MPM.add(createDivRemPairsPass());
953 
954   // LoopSink (and other loop passes since the last simplifyCFG) might have
955   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
956   MPM.add(createCFGSimplificationPass());
957 
958   addExtensionsToPM(EP_OptimizerLast, MPM);
959 
960   if (PrepareForLTO) {
961     MPM.add(createCanonicalizeAliasesPass());
962     // Rename anon globals to be able to handle them in the summary
963     MPM.add(createNameAnonGlobalPass());
964   }
965 
966   MPM.add(createAnnotationRemarksLegacyPass());
967 }
968 
969 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
970   // Load sample profile before running the LTO optimization pipeline.
971   if (!PGOSampleUse.empty()) {
972     PM.add(createPruneEHPass());
973     PM.add(createSampleProfileLoaderPass(PGOSampleUse));
974   }
975 
976   // Remove unused virtual tables to improve the quality of code generated by
977   // whole-program devirtualization and bitset lowering.
978   PM.add(createGlobalDCEPass());
979 
980   // Provide AliasAnalysis services for optimizations.
981   addInitialAliasAnalysisPasses(PM);
982 
983   // Allow forcing function attributes as a debugging and tuning aid.
984   PM.add(createForceFunctionAttrsLegacyPass());
985 
986   // Infer attributes about declarations if possible.
987   PM.add(createInferFunctionAttrsLegacyPass());
988 
989   if (OptLevel > 1) {
990     // Split call-site with more constrained arguments.
991     PM.add(createCallSiteSplittingPass());
992 
993     // Indirect call promotion. This should promote all the targets that are
994     // left by the earlier promotion pass that promotes intra-module targets.
995     // This two-step promotion is to save the compile time. For LTO, it should
996     // produce the same result as if we only do promotion here.
997     PM.add(
998         createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
999 
1000     // Propagate constants at call sites into the functions they call.  This
1001     // opens opportunities for globalopt (and inlining) by substituting function
1002     // pointers passed as arguments to direct uses of functions.
1003     PM.add(createIPSCCPPass());
1004 
1005     // Attach metadata to indirect call sites indicating the set of functions
1006     // they may target at run-time. This should follow IPSCCP.
1007     PM.add(createCalledValuePropagationPass());
1008 
1009     // Infer attributes on declarations, call sites, arguments, etc.
1010     if (AttributorRun & AttributorRunOption::MODULE)
1011       PM.add(createAttributorLegacyPass());
1012   }
1013 
1014   // Infer attributes about definitions. The readnone attribute in particular is
1015   // required for virtual constant propagation.
1016   PM.add(createPostOrderFunctionAttrsLegacyPass());
1017   PM.add(createReversePostOrderFunctionAttrsPass());
1018 
1019   // Split globals using inrange annotations on GEP indices. This can help
1020   // improve the quality of generated code when virtual constant propagation or
1021   // control flow integrity are enabled.
1022   PM.add(createGlobalSplitPass());
1023 
1024   // Apply whole-program devirtualization and virtual constant propagation.
1025   PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
1026 
1027   // That's all we need at opt level 1.
1028   if (OptLevel == 1)
1029     return;
1030 
1031   // Now that we internalized some globals, see if we can hack on them!
1032   PM.add(createGlobalOptimizerPass());
1033   // Promote any localized global vars.
1034   PM.add(createPromoteMemoryToRegisterPass());
1035 
1036   // Linking modules together can lead to duplicated global constants, only
1037   // keep one copy of each constant.
1038   PM.add(createConstantMergePass());
1039 
1040   // Remove unused arguments from functions.
1041   PM.add(createDeadArgEliminationPass());
1042 
1043   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1044   // simplification opportunities, and both can propagate functions through
1045   // function pointers.  When this happens, we often have to resolve varargs
1046   // calls, etc, so let instcombine do this.
1047   if (OptLevel > 2)
1048     PM.add(createAggressiveInstCombinerPass());
1049   PM.add(createInstructionCombiningPass());
1050   addExtensionsToPM(EP_Peephole, PM);
1051 
1052   // Inline small functions
1053   bool RunInliner = Inliner;
1054   if (RunInliner) {
1055     PM.add(Inliner);
1056     Inliner = nullptr;
1057   }
1058 
1059   PM.add(createPruneEHPass());   // Remove dead EH info.
1060 
1061   // CSFDO instrumentation and use pass.
1062   addPGOInstrPasses(PM, /* IsCS */ true);
1063 
1064   // Infer attributes on declarations, call sites, arguments, etc. for an SCC.
1065   if (AttributorRun & AttributorRunOption::CGSCC)
1066     PM.add(createAttributorCGSCCLegacyPass());
1067 
1068   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
1069   // there are no OpenMP runtime calls present in the module.
1070   if (OptLevel > 1)
1071     PM.add(createOpenMPOptCGSCCLegacyPass());
1072 
1073   // Optimize globals again if we ran the inliner.
1074   if (RunInliner)
1075     PM.add(createGlobalOptimizerPass());
1076   PM.add(createGlobalDCEPass()); // Remove dead functions.
1077 
1078   // If we didn't decide to inline a function, check to see if we can
1079   // transform it to pass arguments by value instead of by reference.
1080   PM.add(createArgumentPromotionPass());
1081 
1082   // The IPO passes may leave cruft around.  Clean up after them.
1083   PM.add(createInstructionCombiningPass());
1084   addExtensionsToPM(EP_Peephole, PM);
1085   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1086 
1087   // Break up allocas
1088   PM.add(createSROAPass());
1089 
1090   // LTO provides additional opportunities for tailcall elimination due to
1091   // link-time inlining, and visibility of nocapture attribute.
1092   if (OptLevel > 1)
1093     PM.add(createTailCallEliminationPass());
1094 
1095   // Infer attributes on declarations, call sites, arguments, etc.
1096   PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
1097   // Run a few AA driven optimizations here and now, to cleanup the code.
1098   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
1099 
1100   PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap));
1101   PM.add(NewGVN ? createNewGVNPass()
1102                 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
1103   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
1104 
1105   // Nuke dead stores.
1106   PM.add(createDeadStoreEliminationPass());
1107   PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
1108 
1109   // More loops are countable; try to optimize them.
1110   if (EnableLoopFlatten)
1111     PM.add(createLoopFlattenPass());
1112   PM.add(createIndVarSimplifyPass());
1113   PM.add(createLoopDeletionPass());
1114   if (EnableLoopInterchange)
1115     PM.add(createLoopInterchangePass());
1116 
1117   if (EnableConstraintElimination)
1118     PM.add(createConstraintEliminationPass());
1119 
1120   // Unroll small loops and perform peeling.
1121   PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops,
1122                                     ForgetAllSCEVInLoopUnroll));
1123   PM.add(createLoopDistributePass());
1124 
1125   addVectorPasses(PM, /* IsLTO */ true);
1126 
1127   addExtensionsToPM(EP_Peephole, PM);
1128 
1129   PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true));
1130 }
1131 
1132 void PassManagerBuilder::addLateLTOOptimizationPasses(
1133     legacy::PassManagerBase &PM) {
1134   // See comment in the new PM for justification of scheduling splitting at
1135   // this stage (\ref buildLTODefaultPipeline).
1136   if (EnableHotColdSplit)
1137     PM.add(createHotColdSplittingPass());
1138 
1139   // Delete basic blocks, which optimization passes may have killed.
1140   PM.add(
1141       createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true)));
1142 
1143   // Drop bodies of available externally objects to improve GlobalDCE.
1144   PM.add(createEliminateAvailableExternallyPass());
1145 
1146   // Now that we have optimized the program, discard unreachable functions.
1147   PM.add(createGlobalDCEPass());
1148 
1149   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
1150   // currently it damages debug info.
1151   if (MergeFunctions)
1152     PM.add(createMergeFunctionsPass());
1153 }
1154 
1155 void PassManagerBuilder::populateThinLTOPassManager(
1156     legacy::PassManagerBase &PM) {
1157   PerformThinLTO = true;
1158   if (LibraryInfo)
1159     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1160 
1161   if (VerifyInput)
1162     PM.add(createVerifierPass());
1163 
1164   if (ImportSummary) {
1165     // This pass imports type identifier resolutions for whole-program
1166     // devirtualization and CFI. It must run early because other passes may
1167     // disturb the specific instruction patterns that these passes look for,
1168     // creating dependencies on resolutions that may not appear in the summary.
1169     //
1170     // For example, GVN may transform the pattern assume(type.test) appearing in
1171     // two basic blocks into assume(phi(type.test, type.test)), which would
1172     // transform a dependency on a WPD resolution into a dependency on a type
1173     // identifier resolution for CFI.
1174     //
1175     // Also, WPD has access to more precise information than ICP and can
1176     // devirtualize more effectively, so it should operate on the IR first.
1177     PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
1178     PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
1179   }
1180 
1181   populateModulePassManager(PM);
1182 
1183   if (VerifyOutput)
1184     PM.add(createVerifierPass());
1185   PerformThinLTO = false;
1186 }
1187 
1188 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
1189   if (LibraryInfo)
1190     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
1191 
1192   if (VerifyInput)
1193     PM.add(createVerifierPass());
1194 
1195   addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM);
1196 
1197   if (OptLevel != 0)
1198     addLTOOptimizationPasses(PM);
1199   else {
1200     // The whole-program-devirt pass needs to run at -O0 because only it knows
1201     // about the llvm.type.checked.load intrinsic: it needs to both lower the
1202     // intrinsic itself and handle it in the summary.
1203     PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
1204   }
1205 
1206   // Create a function that performs CFI checks for cross-DSO calls with targets
1207   // in the current module.
1208   PM.add(createCrossDSOCFIPass());
1209 
1210   // Lower type metadata and the type.test intrinsic. This pass supports Clang's
1211   // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
1212   // link time if CFI is enabled. The pass does nothing if CFI is disabled.
1213   PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
1214   // Run a second time to clean up any type tests left behind by WPD for use
1215   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1216   PM.add(createLowerTypeTestsPass(nullptr, nullptr, true));
1217 
1218   if (OptLevel != 0)
1219     addLateLTOOptimizationPasses(PM);
1220 
1221   addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM);
1222 
1223   PM.add(createAnnotationRemarksLegacyPass());
1224 
1225   if (VerifyOutput)
1226     PM.add(createVerifierPass());
1227 }
1228 
1229 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
1230   PassManagerBuilder *PMB = new PassManagerBuilder();
1231   return wrap(PMB);
1232 }
1233 
1234 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
1235   PassManagerBuilder *Builder = unwrap(PMB);
1236   delete Builder;
1237 }
1238 
1239 void
1240 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
1241                                   unsigned OptLevel) {
1242   PassManagerBuilder *Builder = unwrap(PMB);
1243   Builder->OptLevel = OptLevel;
1244 }
1245 
1246 void
1247 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
1248                                    unsigned SizeLevel) {
1249   PassManagerBuilder *Builder = unwrap(PMB);
1250   Builder->SizeLevel = SizeLevel;
1251 }
1252 
1253 void
1254 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
1255                                             LLVMBool Value) {
1256   // NOTE: The DisableUnitAtATime switch has been removed.
1257 }
1258 
1259 void
1260 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
1261                                             LLVMBool Value) {
1262   PassManagerBuilder *Builder = unwrap(PMB);
1263   Builder->DisableUnrollLoops = Value;
1264 }
1265 
1266 void
1267 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
1268                                                  LLVMBool Value) {
1269   // NOTE: The simplify-libcalls pass has been removed.
1270 }
1271 
1272 void
1273 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
1274                                               unsigned Threshold) {
1275   PassManagerBuilder *Builder = unwrap(PMB);
1276   Builder->Inliner = createFunctionInliningPass(Threshold);
1277 }
1278 
1279 void
1280 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
1281                                                   LLVMPassManagerRef PM) {
1282   PassManagerBuilder *Builder = unwrap(PMB);
1283   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
1284   Builder->populateFunctionPassManager(*FPM);
1285 }
1286 
1287 void
1288 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
1289                                                 LLVMPassManagerRef PM) {
1290   PassManagerBuilder *Builder = unwrap(PMB);
1291   legacy::PassManagerBase *MPM = unwrap(PM);
1292   Builder->populateModulePassManager(*MPM);
1293 }
1294 
1295 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1296                                                   LLVMPassManagerRef PM,
1297                                                   LLVMBool Internalize,
1298                                                   LLVMBool RunInliner) {
1299   PassManagerBuilder *Builder = unwrap(PMB);
1300   legacy::PassManagerBase *LPM = unwrap(PM);
1301 
1302   // A small backwards compatibility hack. populateLTOPassManager used to take
1303   // an RunInliner option.
1304   if (RunInliner && !Builder->Inliner)
1305     Builder->Inliner = createFunctionInliningPass();
1306 
1307   Builder->populateLTOPassManager(*LPM);
1308 }
1309