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