1 //===- Construction of pass pipelines -------------------------------------===//
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 /// \file
9 ///
10 /// This file provides the implementation of the PassBuilder based on our
11 /// static pass registry as well as related functionality. It also provides
12 /// helpers to aid in analyzing, debugging, and testing passes and pass
13 /// pipelines.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/BasicAliasAnalysis.h"
19 #include "llvm/Analysis/CGSCCPassManager.h"
20 #include "llvm/Analysis/GlobalsModRef.h"
21 #include "llvm/Analysis/InlineAdvisor.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/Analysis/ProfileSummaryInfo.h"
24 #include "llvm/Analysis/ScopedNoAliasAA.h"
25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/Passes/OptimizationLevel.h"
28 #include "llvm/Passes/PassBuilder.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/PGOOptions.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
34 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
35 #include "llvm/Transforms/Coroutines/CoroConditionalWrapper.h"
36 #include "llvm/Transforms/Coroutines/CoroEarly.h"
37 #include "llvm/Transforms/Coroutines/CoroElide.h"
38 #include "llvm/Transforms/Coroutines/CoroSplit.h"
39 #include "llvm/Transforms/IPO/AlwaysInliner.h"
40 #include "llvm/Transforms/IPO/Annotation2Metadata.h"
41 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
42 #include "llvm/Transforms/IPO/Attributor.h"
43 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
44 #include "llvm/Transforms/IPO/ConstantMerge.h"
45 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
46 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
47 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
48 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
49 #include "llvm/Transforms/IPO/FunctionAttrs.h"
50 #include "llvm/Transforms/IPO/GlobalDCE.h"
51 #include "llvm/Transforms/IPO/GlobalOpt.h"
52 #include "llvm/Transforms/IPO/GlobalSplit.h"
53 #include "llvm/Transforms/IPO/HotColdSplitting.h"
54 #include "llvm/Transforms/IPO/IROutliner.h"
55 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
56 #include "llvm/Transforms/IPO/Inliner.h"
57 #include "llvm/Transforms/IPO/LowerTypeTests.h"
58 #include "llvm/Transforms/IPO/MergeFunctions.h"
59 #include "llvm/Transforms/IPO/ModuleInliner.h"
60 #include "llvm/Transforms/IPO/OpenMPOpt.h"
61 #include "llvm/Transforms/IPO/PartialInlining.h"
62 #include "llvm/Transforms/IPO/SCCP.h"
63 #include "llvm/Transforms/IPO/SampleProfile.h"
64 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
65 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
66 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
67 #include "llvm/Transforms/InstCombine/InstCombine.h"
68 #include "llvm/Transforms/Instrumentation/CGProfile.h"
69 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
70 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
71 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
72 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
73 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
74 #include "llvm/Transforms/Scalar/ADCE.h"
75 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
76 #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
77 #include "llvm/Transforms/Scalar/BDCE.h"
78 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
79 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
80 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
81 #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
82 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
83 #include "llvm/Transforms/Scalar/DivRemPairs.h"
84 #include "llvm/Transforms/Scalar/EarlyCSE.h"
85 #include "llvm/Transforms/Scalar/Float2Int.h"
86 #include "llvm/Transforms/Scalar/GVN.h"
87 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
88 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
89 #include "llvm/Transforms/Scalar/JumpThreading.h"
90 #include "llvm/Transforms/Scalar/LICM.h"
91 #include "llvm/Transforms/Scalar/LoopDeletion.h"
92 #include "llvm/Transforms/Scalar/LoopDistribute.h"
93 #include "llvm/Transforms/Scalar/LoopFlatten.h"
94 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
95 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
96 #include "llvm/Transforms/Scalar/LoopInterchange.h"
97 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
98 #include "llvm/Transforms/Scalar/LoopPassManager.h"
99 #include "llvm/Transforms/Scalar/LoopRotation.h"
100 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
101 #include "llvm/Transforms/Scalar/LoopSink.h"
102 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
103 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
104 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
105 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
106 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
107 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
108 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
109 #include "llvm/Transforms/Scalar/NewGVN.h"
110 #include "llvm/Transforms/Scalar/Reassociate.h"
111 #include "llvm/Transforms/Scalar/SCCP.h"
112 #include "llvm/Transforms/Scalar/SROA.h"
113 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
114 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
115 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
116 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
117 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
118 #include "llvm/Transforms/Utils/AddDiscriminators.h"
119 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
120 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
121 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
122 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
123 #include "llvm/Transforms/Utils/Mem2Reg.h"
124 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
125 #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
126 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
127 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
128 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
129 #include "llvm/Transforms/Vectorize/VectorCombine.h"
130 
131 using namespace llvm;
132 
133 static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
134     "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
135     cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
136     cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
137                           "Heuristics-based inliner version."),
138                clEnumValN(InliningAdvisorMode::Development, "development",
139                           "Use development mode (runtime-loadable model)."),
140                clEnumValN(InliningAdvisorMode::Release, "release",
141                           "Use release mode (AOT-compiled model).")));
142 
143 static cl::opt<bool> EnableSyntheticCounts(
144     "enable-npm-synthetic-counts", cl::Hidden,
145     cl::desc("Run synthetic function entry count generation "
146              "pass"));
147 
148 /// Flag to enable inline deferral during PGO.
149 static cl::opt<bool>
150     EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
151                             cl::Hidden,
152                             cl::desc("Enable inline deferral during PGO"));
153 
154 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::Hidden,
155                                        cl::desc("Enable memory profiler"));
156 
157 static cl::opt<bool> EnableModuleInliner("enable-module-inliner",
158                                          cl::init(false), cl::Hidden,
159                                          cl::desc("Enable module inliner"));
160 
161 static cl::opt<bool> PerformMandatoryInliningsFirst(
162     "mandatory-inlining-first", cl::init(true), cl::Hidden,
163     cl::desc("Perform mandatory inlinings module-wide, before performing "
164              "inlining."));
165 
166 static cl::opt<bool> EnableO3NonTrivialUnswitching(
167     "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden,
168     cl::desc("Enable non-trivial loop unswitching for -O3"));
169 
170 static cl::opt<bool> EnableEagerlyInvalidateAnalyses(
171     "eagerly-invalidate-analyses", cl::init(true), cl::Hidden,
172     cl::desc("Eagerly invalidate more analyses in default pipelines"));
173 
174 static cl::opt<bool> EnableNoRerunSimplificationPipeline(
175     "enable-no-rerun-simplification-pipeline", cl::init(false), cl::Hidden,
176     cl::desc(
177         "Prevent running the simplification pipeline on a function more "
178         "than once in the case that SCC mutations cause a function to be "
179         "visited multiple times as long as the function has not been changed"));
180 
181 static cl::opt<bool> EnableMergeFunctions(
182     "enable-merge-functions", cl::init(false), cl::Hidden,
183     cl::desc("Enable function merging as part of the optimization pipeline"));
184 
185 PipelineTuningOptions::PipelineTuningOptions() {
186   LoopInterleaving = true;
187   LoopVectorization = true;
188   SLPVectorization = false;
189   LoopUnrolling = true;
190   ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll;
191   LicmMssaOptCap = SetLicmMssaOptCap;
192   LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap;
193   CallGraphProfile = true;
194   MergeFunctions = EnableMergeFunctions;
195   EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses;
196 }
197 
198 namespace llvm {
199 
200 extern cl::opt<unsigned> MaxDevirtIterations;
201 extern cl::opt<bool> EnableConstraintElimination;
202 extern cl::opt<bool> EnableFunctionSpecialization;
203 extern cl::opt<bool> EnableGVNHoist;
204 extern cl::opt<bool> EnableGVNSink;
205 extern cl::opt<bool> EnableHotColdSplit;
206 extern cl::opt<bool> EnableIROutliner;
207 extern cl::opt<bool> EnableOrderFileInstrumentation;
208 extern cl::opt<bool> EnableCHR;
209 extern cl::opt<bool> EnableLoopInterchange;
210 extern cl::opt<bool> EnableUnrollAndJam;
211 extern cl::opt<bool> EnableLoopFlatten;
212 extern cl::opt<bool> EnableDFAJumpThreading;
213 extern cl::opt<bool> RunNewGVN;
214 extern cl::opt<bool> RunPartialInlining;
215 extern cl::opt<bool> ExtraVectorizerPasses;
216 
217 extern cl::opt<bool> FlattenedProfileUsed;
218 
219 extern cl::opt<AttributorRunOption> AttributorRun;
220 extern cl::opt<bool> EnableKnowledgeRetention;
221 
222 extern cl::opt<bool> EnableMatrix;
223 
224 extern cl::opt<bool> DisablePreInliner;
225 extern cl::opt<int> PreInlineThreshold;
226 } // namespace llvm
227 
228 void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM,
229                                             OptimizationLevel Level) {
230   for (auto &C : PeepholeEPCallbacks)
231     C(FPM, Level);
232 }
233 
234 // Helper to add AnnotationRemarksPass.
235 static void addAnnotationRemarksPass(ModulePassManager &MPM) {
236   MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
237 }
238 
239 // Helper to check if the current compilation phase is preparing for LTO
240 static bool isLTOPreLink(ThinOrFullLTOPhase Phase) {
241   return Phase == ThinOrFullLTOPhase::ThinLTOPreLink ||
242          Phase == ThinOrFullLTOPhase::FullLTOPreLink;
243 }
244 
245 // TODO: Investigate the cost/benefit of tail call elimination on debugging.
246 FunctionPassManager
247 PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level,
248                                                    ThinOrFullLTOPhase Phase) {
249 
250   FunctionPassManager FPM;
251 
252   // Form SSA out of local memory accesses after breaking apart aggregates into
253   // scalars.
254   FPM.addPass(SROAPass());
255 
256   // Catch trivial redundancies
257   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
258 
259   // Hoisting of scalars and load expressions.
260   FPM.addPass(
261       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
262   FPM.addPass(InstCombinePass());
263 
264   FPM.addPass(LibCallsShrinkWrapPass());
265 
266   invokePeepholeEPCallbacks(FPM, Level);
267 
268   FPM.addPass(
269       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
270 
271   // Form canonically associated expression trees, and simplify the trees using
272   // basic mathematical properties. For example, this will form (nearly)
273   // minimal multiplication trees.
274   FPM.addPass(ReassociatePass());
275 
276   // Add the primary loop simplification pipeline.
277   // FIXME: Currently this is split into two loop pass pipelines because we run
278   // some function passes in between them. These can and should be removed
279   // and/or replaced by scheduling the loop pass equivalents in the correct
280   // positions. But those equivalent passes aren't powerful enough yet.
281   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
282   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
283   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
284   // `LoopInstSimplify`.
285   LoopPassManager LPM1, LPM2;
286 
287   // Simplify the loop body. We do this initially to clean up after other loop
288   // passes run, either when iterating on a loop or on inner loops with
289   // implications on the outer loop.
290   LPM1.addPass(LoopInstSimplifyPass());
291   LPM1.addPass(LoopSimplifyCFGPass());
292 
293   // Try to remove as much code from the loop header as possible,
294   // to reduce amount of IR that will have to be duplicated. However,
295   // do not perform speculative hoisting the first time as LICM
296   // will destroy metadata that may not need to be destroyed if run
297   // after loop rotation.
298   // TODO: Investigate promotion cap for O1.
299   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
300                         /*AllowSpeculation=*/false));
301 
302   LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true,
303                               isLTOPreLink(Phase)));
304   // TODO: Investigate promotion cap for O1.
305   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
306                         /*AllowSpeculation=*/true));
307   LPM1.addPass(SimpleLoopUnswitchPass());
308   if (EnableLoopFlatten)
309     LPM1.addPass(LoopFlattenPass());
310 
311   LPM2.addPass(LoopIdiomRecognizePass());
312   LPM2.addPass(IndVarSimplifyPass());
313 
314   for (auto &C : LateLoopOptimizationsEPCallbacks)
315     C(LPM2, Level);
316 
317   LPM2.addPass(LoopDeletionPass());
318 
319   if (EnableLoopInterchange)
320     LPM2.addPass(LoopInterchangePass());
321 
322   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
323   // because it changes IR to makes profile annotation in back compile
324   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
325   // attributes so we need to make sure and allow the full unroll pass to pay
326   // attention to it.
327   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
328       PGOOpt->Action != PGOOptions::SampleUse)
329     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
330                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
331                                     PTO.ForgetAllSCEVInLoopUnroll));
332 
333   for (auto &C : LoopOptimizerEndEPCallbacks)
334     C(LPM2, Level);
335 
336   // We provide the opt remark emitter pass for LICM to use. We only need to do
337   // this once as it is immutable.
338   FPM.addPass(
339       RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
340   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
341                                               /*UseMemorySSA=*/true,
342                                               /*UseBlockFrequencyInfo=*/true));
343   FPM.addPass(
344       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
345   FPM.addPass(InstCombinePass());
346   // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA.
347   // *All* loop passes must preserve it, in order to be able to use it.
348   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
349                                               /*UseMemorySSA=*/false,
350                                               /*UseBlockFrequencyInfo=*/false));
351 
352   // Delete small array after loop unroll.
353   FPM.addPass(SROAPass());
354 
355   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
356   FPM.addPass(MemCpyOptPass());
357 
358   // Sparse conditional constant propagation.
359   // FIXME: It isn't clear why we do this *after* loop passes rather than
360   // before...
361   FPM.addPass(SCCPPass());
362 
363   // Delete dead bit computations (instcombine runs after to fold away the dead
364   // computations, and then ADCE will run later to exploit any new DCE
365   // opportunities that creates).
366   FPM.addPass(BDCEPass());
367 
368   // Run instcombine after redundancy and dead bit elimination to exploit
369   // opportunities opened up by them.
370   FPM.addPass(InstCombinePass());
371   invokePeepholeEPCallbacks(FPM, Level);
372 
373   FPM.addPass(CoroElidePass());
374 
375   for (auto &C : ScalarOptimizerLateEPCallbacks)
376     C(FPM, Level);
377 
378   // Finally, do an expensive DCE pass to catch all the dead code exposed by
379   // the simplifications and basic cleanup after all the simplifications.
380   // TODO: Investigate if this is too expensive.
381   FPM.addPass(ADCEPass());
382   FPM.addPass(
383       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
384   FPM.addPass(InstCombinePass());
385   invokePeepholeEPCallbacks(FPM, Level);
386 
387   return FPM;
388 }
389 
390 FunctionPassManager
391 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
392                                                  ThinOrFullLTOPhase Phase) {
393   assert(Level != OptimizationLevel::O0 && "Must request optimizations!");
394 
395   // The O1 pipeline has a separate pipeline creation function to simplify
396   // construction readability.
397   if (Level.getSpeedupLevel() == 1)
398     return buildO1FunctionSimplificationPipeline(Level, Phase);
399 
400   FunctionPassManager FPM;
401 
402   // Form SSA out of local memory accesses after breaking apart aggregates into
403   // scalars.
404   FPM.addPass(SROAPass());
405 
406   // Catch trivial redundancies
407   FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */));
408   if (EnableKnowledgeRetention)
409     FPM.addPass(AssumeSimplifyPass());
410 
411   // Hoisting of scalars and load expressions.
412   if (EnableGVNHoist)
413     FPM.addPass(GVNHoistPass());
414 
415   // Global value numbering based sinking.
416   if (EnableGVNSink) {
417     FPM.addPass(GVNSinkPass());
418     FPM.addPass(
419         SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
420   }
421 
422   if (EnableConstraintElimination)
423     FPM.addPass(ConstraintEliminationPass());
424 
425   // Speculative execution if the target has divergent branches; otherwise nop.
426   FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true));
427 
428   // Optimize based on known information about branches, and cleanup afterward.
429   FPM.addPass(JumpThreadingPass());
430   FPM.addPass(CorrelatedValuePropagationPass());
431 
432   FPM.addPass(
433       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
434   FPM.addPass(InstCombinePass());
435   if (Level == OptimizationLevel::O3)
436     FPM.addPass(AggressiveInstCombinePass());
437 
438   if (!Level.isOptimizingForSize())
439     FPM.addPass(LibCallsShrinkWrapPass());
440 
441   invokePeepholeEPCallbacks(FPM, Level);
442 
443   // For PGO use pipeline, try to optimize memory intrinsics such as memcpy
444   // using the size value profile. Don't perform this when optimizing for size.
445   if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse &&
446       !Level.isOptimizingForSize())
447     FPM.addPass(PGOMemOPSizeOpt());
448 
449   FPM.addPass(TailCallElimPass());
450   FPM.addPass(
451       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
452 
453   // Form canonically associated expression trees, and simplify the trees using
454   // basic mathematical properties. For example, this will form (nearly)
455   // minimal multiplication trees.
456   FPM.addPass(ReassociatePass());
457 
458   // Add the primary loop simplification pipeline.
459   // FIXME: Currently this is split into two loop pass pipelines because we run
460   // some function passes in between them. These can and should be removed
461   // and/or replaced by scheduling the loop pass equivalents in the correct
462   // positions. But those equivalent passes aren't powerful enough yet.
463   // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still
464   // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to
465   // fully replace `SimplifyCFGPass`, and the closest to the other we have is
466   // `LoopInstSimplify`.
467   LoopPassManager LPM1, LPM2;
468 
469   // Simplify the loop body. We do this initially to clean up after other loop
470   // passes run, either when iterating on a loop or on inner loops with
471   // implications on the outer loop.
472   LPM1.addPass(LoopInstSimplifyPass());
473   LPM1.addPass(LoopSimplifyCFGPass());
474 
475   // Try to remove as much code from the loop header as possible,
476   // to reduce amount of IR that will have to be duplicated. However,
477   // do not perform speculative hoisting the first time as LICM
478   // will destroy metadata that may not need to be destroyed if run
479   // after loop rotation.
480   // TODO: Investigate promotion cap for O1.
481   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
482                         /*AllowSpeculation=*/false));
483 
484   // Disable header duplication in loop rotation at -Oz.
485   LPM1.addPass(
486       LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase)));
487   // TODO: Investigate promotion cap for O1.
488   LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
489                         /*AllowSpeculation=*/true));
490   LPM1.addPass(
491       SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 &&
492                              EnableO3NonTrivialUnswitching));
493   if (EnableLoopFlatten)
494     LPM1.addPass(LoopFlattenPass());
495 
496   LPM2.addPass(LoopIdiomRecognizePass());
497   LPM2.addPass(IndVarSimplifyPass());
498 
499   for (auto &C : LateLoopOptimizationsEPCallbacks)
500     C(LPM2, Level);
501 
502   LPM2.addPass(LoopDeletionPass());
503 
504   if (EnableLoopInterchange)
505     LPM2.addPass(LoopInterchangePass());
506 
507   // Do not enable unrolling in PreLinkThinLTO phase during sample PGO
508   // because it changes IR to makes profile annotation in back compile
509   // inaccurate. The normal unroller doesn't pay attention to forced full unroll
510   // attributes so we need to make sure and allow the full unroll pass to pay
511   // attention to it.
512   if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt ||
513       PGOOpt->Action != PGOOptions::SampleUse)
514     LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
515                                     /* OnlyWhenForced= */ !PTO.LoopUnrolling,
516                                     PTO.ForgetAllSCEVInLoopUnroll));
517 
518   for (auto &C : LoopOptimizerEndEPCallbacks)
519     C(LPM2, Level);
520 
521   // We provide the opt remark emitter pass for LICM to use. We only need to do
522   // this once as it is immutable.
523   FPM.addPass(
524       RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
525   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1),
526                                               /*UseMemorySSA=*/true,
527                                               /*UseBlockFrequencyInfo=*/true));
528   FPM.addPass(
529       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
530   FPM.addPass(InstCombinePass());
531   // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass,
532   // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA.
533   // *All* loop passes must preserve it, in order to be able to use it.
534   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2),
535                                               /*UseMemorySSA=*/false,
536                                               /*UseBlockFrequencyInfo=*/false));
537 
538   // Delete small array after loop unroll.
539   FPM.addPass(SROAPass());
540 
541   // The matrix extension can introduce large vector operations early, which can
542   // benefit from running vector-combine early on.
543   if (EnableMatrix)
544     FPM.addPass(VectorCombinePass(/*ScalarizationOnly=*/true));
545 
546   // Eliminate redundancies.
547   FPM.addPass(MergedLoadStoreMotionPass());
548   if (RunNewGVN)
549     FPM.addPass(NewGVNPass());
550   else
551     FPM.addPass(GVNPass());
552 
553   // Sparse conditional constant propagation.
554   // FIXME: It isn't clear why we do this *after* loop passes rather than
555   // before...
556   FPM.addPass(SCCPPass());
557 
558   // Delete dead bit computations (instcombine runs after to fold away the dead
559   // computations, and then ADCE will run later to exploit any new DCE
560   // opportunities that creates).
561   FPM.addPass(BDCEPass());
562 
563   // Run instcombine after redundancy and dead bit elimination to exploit
564   // opportunities opened up by them.
565   FPM.addPass(InstCombinePass());
566   invokePeepholeEPCallbacks(FPM, Level);
567 
568   // Re-consider control flow based optimizations after redundancy elimination,
569   // redo DCE, etc.
570   if (EnableDFAJumpThreading && Level.getSizeLevel() == 0)
571     FPM.addPass(DFAJumpThreadingPass());
572 
573   FPM.addPass(JumpThreadingPass());
574   FPM.addPass(CorrelatedValuePropagationPass());
575 
576   // Finally, do an expensive DCE pass to catch all the dead code exposed by
577   // the simplifications and basic cleanup after all the simplifications.
578   // TODO: Investigate if this is too expensive.
579   FPM.addPass(ADCEPass());
580 
581   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
582   FPM.addPass(MemCpyOptPass());
583 
584   FPM.addPass(DSEPass());
585   FPM.addPass(createFunctionToLoopPassAdaptor(
586       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
587                /*AllowSpeculation=*/true),
588       /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
589 
590   FPM.addPass(CoroElidePass());
591 
592   for (auto &C : ScalarOptimizerLateEPCallbacks)
593     C(FPM, Level);
594 
595   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
596                                   .convertSwitchRangeToICmp(true)
597                                   .hoistCommonInsts(true)
598                                   .sinkCommonInsts(true)));
599   FPM.addPass(InstCombinePass());
600   invokePeepholeEPCallbacks(FPM, Level);
601 
602   if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt &&
603       (PGOOpt->Action == PGOOptions::IRUse ||
604        PGOOpt->Action == PGOOptions::SampleUse))
605     FPM.addPass(ControlHeightReductionPass());
606 
607   return FPM;
608 }
609 
610 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
611   MPM.addPass(CanonicalizeAliasesPass());
612   MPM.addPass(NameAnonGlobalPass());
613 }
614 
615 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM,
616                                     OptimizationLevel Level, bool RunProfileGen,
617                                     bool IsCS, std::string ProfileFile,
618                                     std::string ProfileRemappingFile) {
619   assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!");
620   if (!IsCS && !DisablePreInliner) {
621     InlineParams IP;
622 
623     IP.DefaultThreshold = PreInlineThreshold;
624 
625     // FIXME: The hint threshold has the same value used by the regular inliner
626     // when not optimzing for size. This should probably be lowered after
627     // performance testing.
628     // FIXME: this comment is cargo culted from the old pass manager, revisit).
629     IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325;
630     ModuleInlinerWrapperPass MIWP(IP);
631     CGSCCPassManager &CGPipeline = MIWP.getPM();
632 
633     FunctionPassManager FPM;
634     FPM.addPass(SROAPass());
635     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
636     FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(
637         true)));                    // Merge & remove basic blocks.
638     FPM.addPass(InstCombinePass()); // Combine silly sequences.
639     invokePeepholeEPCallbacks(FPM, Level);
640 
641     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
642         std::move(FPM), PTO.EagerlyInvalidateAnalyses));
643 
644     MPM.addPass(std::move(MIWP));
645 
646     // Delete anything that is now dead to make sure that we don't instrument
647     // dead code. Instrumentation can end up keeping dead code around and
648     // dramatically increase code size.
649     MPM.addPass(GlobalDCEPass());
650   }
651 
652   if (!RunProfileGen) {
653     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
654     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
655     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
656     // RequireAnalysisPass for PSI before subsequent non-module passes.
657     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
658     return;
659   }
660 
661   // Perform PGO instrumentation.
662   MPM.addPass(PGOInstrumentationGen(IsCS));
663 
664   // Disable header duplication in loop rotation at -Oz.
665   MPM.addPass(createModuleToFunctionPassAdaptor(
666       createFunctionToLoopPassAdaptor(
667           LoopRotatePass(Level != OptimizationLevel::Oz),
668           /*UseMemorySSA=*/false,
669           /*UseBlockFrequencyInfo=*/false),
670       PTO.EagerlyInvalidateAnalyses));
671 
672   // Add the profile lowering pass.
673   InstrProfOptions Options;
674   if (!ProfileFile.empty())
675     Options.InstrProfileOutput = ProfileFile;
676   // Do counter promotion at Level greater than O0.
677   Options.DoCounterPromotion = true;
678   Options.UseBFIInPromotion = IsCS;
679   MPM.addPass(InstrProfiling(Options, IsCS));
680 }
681 
682 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM,
683                                          bool RunProfileGen, bool IsCS,
684                                          std::string ProfileFile,
685                                          std::string ProfileRemappingFile) {
686   if (!RunProfileGen) {
687     assert(!ProfileFile.empty() && "Profile use expecting a profile file!");
688     MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS));
689     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
690     // RequireAnalysisPass for PSI before subsequent non-module passes.
691     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
692     return;
693   }
694 
695   // Perform PGO instrumentation.
696   MPM.addPass(PGOInstrumentationGen(IsCS));
697   // Add the profile lowering pass.
698   InstrProfOptions Options;
699   if (!ProfileFile.empty())
700     Options.InstrProfileOutput = ProfileFile;
701   // Do not do counter promotion at O0.
702   Options.DoCounterPromotion = false;
703   Options.UseBFIInPromotion = IsCS;
704   MPM.addPass(InstrProfiling(Options, IsCS));
705 }
706 
707 static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) {
708   return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel());
709 }
710 
711 ModuleInlinerWrapperPass
712 PassBuilder::buildInlinerPipeline(OptimizationLevel Level,
713                                   ThinOrFullLTOPhase Phase) {
714   InlineParams IP = getInlineParamsFromOptLevel(Level);
715   // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
716   // disable hot callsite inline (as much as possible [1]) because it makes
717   // profile annotation in the backend inaccurate.
718   //
719   // [1] Note the cost of a function could be below zero due to erased
720   // prologue / epilogue.
721   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
722       PGOOpt->Action == PGOOptions::SampleUse)
723     IP.HotCallSiteThreshold = 0;
724 
725   if (PGOOpt)
726     IP.EnableDeferral = EnablePGOInlineDeferral;
727 
728   ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst,
729                                 UseInlineAdvisor, MaxDevirtIterations);
730 
731   // Require the GlobalsAA analysis for the module so we can query it within
732   // the CGSCC pipeline.
733   MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
734   // Invalidate AAManager so it can be recreated and pick up the newly available
735   // GlobalsAA.
736   MIWP.addModulePass(
737       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
738 
739   // Require the ProfileSummaryAnalysis for the module so we can query it within
740   // the inliner pass.
741   MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
742 
743   // Now begin the main postorder CGSCC pipeline.
744   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
745   // manager and trying to emulate its precise behavior. Much of this doesn't
746   // make a lot of sense and we should revisit the core CGSCC structure.
747   CGSCCPassManager &MainCGPipeline = MIWP.getPM();
748 
749   // Note: historically, the PruneEH pass was run first to deduce nounwind and
750   // generally clean up exception handling overhead. It isn't clear this is
751   // valuable as the inliner doesn't currently care whether it is inlining an
752   // invoke or a call.
753 
754   if (AttributorRun & AttributorRunOption::CGSCC)
755     MainCGPipeline.addPass(AttributorCGSCCPass());
756 
757   // Now deduce any function attributes based in the current code.
758   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
759 
760   // When at O3 add argument promotion to the pass pipeline.
761   // FIXME: It isn't at all clear why this should be limited to O3.
762   if (Level == OptimizationLevel::O3)
763     MainCGPipeline.addPass(ArgumentPromotionPass());
764 
765   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
766   // there are no OpenMP runtime calls present in the module.
767   if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
768     MainCGPipeline.addPass(OpenMPOptCGSCCPass());
769 
770   for (auto &C : CGSCCOptimizerLateEPCallbacks)
771     C(MainCGPipeline, Level);
772 
773   // Lastly, add the core function simplification pipeline nested inside the
774   // CGSCC walk.
775   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
776       buildFunctionSimplificationPipeline(Level, Phase),
777       PTO.EagerlyInvalidateAnalyses, EnableNoRerunSimplificationPipeline));
778 
779   MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
780 
781   if (EnableNoRerunSimplificationPipeline)
782     MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
783         InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>()));
784 
785   return MIWP;
786 }
787 
788 ModulePassManager
789 PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level,
790                                         ThinOrFullLTOPhase Phase) {
791   ModulePassManager MPM;
792 
793   InlineParams IP = getInlineParamsFromOptLevel(Level);
794   // For PreLinkThinLTO + SamplePGO, set hot-caller threshold to 0 to
795   // disable hot callsite inline (as much as possible [1]) because it makes
796   // profile annotation in the backend inaccurate.
797   //
798   // [1] Note the cost of a function could be below zero due to erased
799   // prologue / epilogue.
800   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
801       PGOOpt->Action == PGOOptions::SampleUse)
802     IP.HotCallSiteThreshold = 0;
803 
804   if (PGOOpt)
805     IP.EnableDeferral = EnablePGOInlineDeferral;
806 
807   // The inline deferral logic is used to avoid losing some
808   // inlining chance in future. It is helpful in SCC inliner, in which
809   // inlining is processed in bottom-up order.
810   // While in module inliner, the inlining order is a priority-based order
811   // by default. The inline deferral is unnecessary there. So we disable the
812   // inline deferral logic in module inliner.
813   IP.EnableDeferral = false;
814 
815   MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor));
816 
817   MPM.addPass(createModuleToFunctionPassAdaptor(
818       buildFunctionSimplificationPipeline(Level, Phase),
819       PTO.EagerlyInvalidateAnalyses));
820 
821   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
822       CoroSplitPass(Level != OptimizationLevel::O0)));
823 
824   return MPM;
825 }
826 
827 ModulePassManager
828 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
829                                                ThinOrFullLTOPhase Phase) {
830   ModulePassManager MPM;
831 
832   // Place pseudo probe instrumentation as the first pass of the pipeline to
833   // minimize the impact of optimization changes.
834   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
835       Phase != ThinOrFullLTOPhase::ThinLTOPostLink)
836     MPM.addPass(SampleProfileProbePass(TM));
837 
838   bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
839 
840   // In ThinLTO mode, when flattened profile is used, all the available
841   // profile information will be annotated in PreLink phase so there is
842   // no need to load the profile again in PostLink.
843   bool LoadSampleProfile =
844       HasSampleProfile &&
845       !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink);
846 
847   // During the ThinLTO backend phase we perform early indirect call promotion
848   // here, before globalopt. Otherwise imported available_externally functions
849   // look unreferenced and are removed. If we are going to load the sample
850   // profile then defer until later.
851   // TODO: See if we can move later and consolidate with the location where
852   // we perform ICP when we are loading a sample profile.
853   // TODO: We pass HasSampleProfile (whether there was a sample profile file
854   // passed to the compile) to the SamplePGO flag of ICP. This is used to
855   // determine whether the new direct calls are annotated with prof metadata.
856   // Ideally this should be determined from whether the IR is annotated with
857   // sample profile, and not whether the a sample profile was provided on the
858   // command line. E.g. for flattened profiles where we will not be reloading
859   // the sample profile in the ThinLTO backend, we ideally shouldn't have to
860   // provide the sample profile file.
861   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
862     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
863 
864   // Do basic inference of function attributes from known properties of system
865   // libraries and other oracles.
866   MPM.addPass(InferFunctionAttrsPass());
867   MPM.addPass(CoroEarlyPass());
868 
869   // Create an early function pass manager to cleanup the output of the
870   // frontend.
871   FunctionPassManager EarlyFPM;
872   // Lower llvm.expect to metadata before attempting transforms.
873   // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
874   EarlyFPM.addPass(LowerExpectIntrinsicPass());
875   EarlyFPM.addPass(SimplifyCFGPass());
876   EarlyFPM.addPass(SROAPass());
877   EarlyFPM.addPass(EarlyCSEPass());
878   if (Level == OptimizationLevel::O3)
879     EarlyFPM.addPass(CallSiteSplittingPass());
880 
881   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
882   // to convert bitcast to direct calls so that they can be inlined during the
883   // profile annotation prepration step.
884   // More details about SamplePGO design can be found in:
885   // https://research.google.com/pubs/pub45290.html
886   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
887   if (LoadSampleProfile)
888     EarlyFPM.addPass(InstCombinePass());
889   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM),
890                                                 PTO.EagerlyInvalidateAnalyses));
891 
892   if (LoadSampleProfile) {
893     // Annotate sample profile right after early FPM to ensure freshness of
894     // the debug info.
895     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
896                                         PGOOpt->ProfileRemappingFile, Phase));
897     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
898     // RequireAnalysisPass for PSI before subsequent non-module passes.
899     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
900     // Do not invoke ICP in the LTOPrelink phase as it makes it hard
901     // for the profile annotation to be accurate in the LTO backend.
902     if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink &&
903         Phase != ThinOrFullLTOPhase::FullLTOPreLink)
904       // We perform early indirect call promotion here, before globalopt.
905       // This is important for the ThinLTO backend phase because otherwise
906       // imported available_externally functions look unreferenced and are
907       // removed.
908       MPM.addPass(
909           PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
910   }
911 
912   // Try to perform OpenMP specific optimizations on the module. This is a
913   // (quick!) no-op if there are no OpenMP runtime calls present in the module.
914   if (Level != OptimizationLevel::O0)
915     MPM.addPass(OpenMPOptPass());
916 
917   if (AttributorRun & AttributorRunOption::MODULE)
918     MPM.addPass(AttributorPass());
919 
920   // Lower type metadata and the type.test intrinsic in the ThinLTO
921   // post link pipeline after ICP. This is to enable usage of the type
922   // tests in ICP sequences.
923   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink)
924     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
925 
926   for (auto &C : PipelineEarlySimplificationEPCallbacks)
927     C(MPM, Level);
928 
929   // Specialize functions with IPSCCP.
930   if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
931     MPM.addPass(FunctionSpecializationPass());
932 
933   // Interprocedural constant propagation now that basic cleanup has occurred
934   // and prior to optimizing globals.
935   // FIXME: This position in the pipeline hasn't been carefully considered in
936   // years, it should be re-analyzed.
937   MPM.addPass(IPSCCPPass());
938 
939   // Attach metadata to indirect call sites indicating the set of functions
940   // they may target at run-time. This should follow IPSCCP.
941   MPM.addPass(CalledValuePropagationPass());
942 
943   // Optimize globals to try and fold them into constants.
944   MPM.addPass(GlobalOptPass());
945 
946   // Promote any localized globals to SSA registers.
947   // FIXME: Should this instead by a run of SROA?
948   // FIXME: We should probably run instcombine and simplifycfg afterward to
949   // delete control flows that are dead once globals have been folded to
950   // constants.
951   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
952 
953   // Remove any dead arguments exposed by cleanups and constant folding
954   // globals.
955   MPM.addPass(DeadArgumentEliminationPass());
956 
957   // Create a small function pass pipeline to cleanup after all the global
958   // optimizations.
959   FunctionPassManager GlobalCleanupPM;
960   GlobalCleanupPM.addPass(InstCombinePass());
961   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
962 
963   GlobalCleanupPM.addPass(
964       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
965   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
966                                                 PTO.EagerlyInvalidateAnalyses));
967 
968   // Add all the requested passes for instrumentation PGO, if requested.
969   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
970       (PGOOpt->Action == PGOOptions::IRInstr ||
971        PGOOpt->Action == PGOOptions::IRUse)) {
972     addPGOInstrPasses(MPM, Level,
973                       /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
974                       /* IsCS */ false, PGOOpt->ProfileFile,
975                       PGOOpt->ProfileRemappingFile);
976     MPM.addPass(PGOIndirectCallPromotion(false, false));
977   }
978   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
979       PGOOpt->CSAction == PGOOptions::CSIRInstr)
980     MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
981 
982   // Synthesize function entry counts for non-PGO compilation.
983   if (EnableSyntheticCounts && !PGOOpt)
984     MPM.addPass(SyntheticCountsPropagation());
985 
986   if (EnableModuleInliner)
987     MPM.addPass(buildModuleInlinerPipeline(Level, Phase));
988   else
989     MPM.addPass(buildInlinerPipeline(Level, Phase));
990 
991   MPM.addPass(CoroCleanupPass());
992 
993   if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) {
994     MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
995     MPM.addPass(ModuleMemProfilerPass());
996   }
997 
998   return MPM;
999 }
1000 
1001 /// TODO: Should LTO cause any differences to this set of passes?
1002 void PassBuilder::addVectorPasses(OptimizationLevel Level,
1003                                   FunctionPassManager &FPM, bool IsFullLTO) {
1004   FPM.addPass(LoopVectorizePass(
1005       LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
1006 
1007   if (IsFullLTO) {
1008     // The vectorizer may have significantly shortened a loop body; unroll
1009     // again. Unroll small loops to hide loop backedge latency and saturate any
1010     // parallel execution resources of an out-of-order processor. We also then
1011     // need to clean up redundancies and loop invariant code.
1012     // FIXME: It would be really good to use a loop-integrated instruction
1013     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1014     // across the loop nests.
1015     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1016     if (EnableUnrollAndJam && PTO.LoopUnrolling)
1017       FPM.addPass(createFunctionToLoopPassAdaptor(
1018           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1019     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1020         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1021         PTO.ForgetAllSCEVInLoopUnroll)));
1022     FPM.addPass(WarnMissedTransformationsPass());
1023   }
1024 
1025   if (!IsFullLTO) {
1026     // Eliminate loads by forwarding stores from the previous iteration to loads
1027     // of the current iteration.
1028     FPM.addPass(LoopLoadEliminationPass());
1029   }
1030   // Cleanup after the loop optimization passes.
1031   FPM.addPass(InstCombinePass());
1032 
1033   if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1034     ExtraVectorPassManager ExtraPasses;
1035     // At higher optimization levels, try to clean up any runtime overlap and
1036     // alignment checks inserted by the vectorizer. We want to track correlated
1037     // runtime checks for two inner loops in the same outer loop, fold any
1038     // common computations, hoist loop-invariant aspects out of any outer loop,
1039     // and unswitch the runtime checks if possible. Once hoisted, we may have
1040     // dead (or speculatable) control flows or more combining opportunities.
1041     ExtraPasses.addPass(EarlyCSEPass());
1042     ExtraPasses.addPass(CorrelatedValuePropagationPass());
1043     ExtraPasses.addPass(InstCombinePass());
1044     LoopPassManager LPM;
1045     LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1046                          /*AllowSpeculation=*/true));
1047     LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1048                                        OptimizationLevel::O3));
1049     ExtraPasses.addPass(
1050         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1051     ExtraPasses.addPass(
1052         createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true,
1053                                         /*UseBlockFrequencyInfo=*/true));
1054     ExtraPasses.addPass(
1055         SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1056     ExtraPasses.addPass(InstCombinePass());
1057     FPM.addPass(std::move(ExtraPasses));
1058   }
1059 
1060   // Now that we've formed fast to execute loop structures, we do further
1061   // optimizations. These are run afterward as they might block doing complex
1062   // analyses and transforms such as what are needed for loop vectorization.
1063 
1064   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1065   // GVN, loop transforms, and others have already run, so it's now better to
1066   // convert to more optimized IR using more aggressive simplify CFG options.
1067   // The extra sinking transform can create larger basic blocks, so do this
1068   // before SLP vectorization.
1069   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1070                                   .forwardSwitchCondToPhi(true)
1071                                   .convertSwitchRangeToICmp(true)
1072                                   .convertSwitchToLookupTable(true)
1073                                   .needCanonicalLoops(false)
1074                                   .hoistCommonInsts(true)
1075                                   .sinkCommonInsts(true)));
1076 
1077   if (IsFullLTO) {
1078     FPM.addPass(SCCPPass());
1079     FPM.addPass(InstCombinePass());
1080     FPM.addPass(BDCEPass());
1081   }
1082 
1083   // Optimize parallel scalar instruction chains into SIMD instructions.
1084   if (PTO.SLPVectorization) {
1085     FPM.addPass(SLPVectorizerPass());
1086     if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1087       FPM.addPass(EarlyCSEPass());
1088     }
1089   }
1090   // Enhance/cleanup vector code.
1091   FPM.addPass(VectorCombinePass());
1092 
1093   if (!IsFullLTO) {
1094     FPM.addPass(InstCombinePass());
1095     // Unroll small loops to hide loop backedge latency and saturate any
1096     // parallel execution resources of an out-of-order processor. We also then
1097     // need to clean up redundancies and loop invariant code.
1098     // FIXME: It would be really good to use a loop-integrated instruction
1099     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1100     // across the loop nests.
1101     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1102     if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1103       FPM.addPass(createFunctionToLoopPassAdaptor(
1104           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1105     }
1106     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1107         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1108         PTO.ForgetAllSCEVInLoopUnroll)));
1109     FPM.addPass(WarnMissedTransformationsPass());
1110     FPM.addPass(InstCombinePass());
1111     FPM.addPass(
1112         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1113     FPM.addPass(createFunctionToLoopPassAdaptor(
1114         LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1115                  /*AllowSpeculation=*/true),
1116         /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
1117   }
1118 
1119   // Now that we've vectorized and unrolled loops, we may have more refined
1120   // alignment information, try to re-derive it here.
1121   FPM.addPass(AlignmentFromAssumptionsPass());
1122 
1123   if (IsFullLTO)
1124     FPM.addPass(InstCombinePass());
1125 }
1126 
1127 ModulePassManager
1128 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
1129                                              bool LTOPreLink) {
1130   ModulePassManager MPM;
1131 
1132   // Optimize globals now that the module is fully simplified.
1133   MPM.addPass(GlobalOptPass());
1134   MPM.addPass(GlobalDCEPass());
1135 
1136   // Run partial inlining pass to partially inline functions that have
1137   // large bodies.
1138   if (RunPartialInlining)
1139     MPM.addPass(PartialInlinerPass());
1140 
1141   // Remove avail extern fns and globals definitions since we aren't compiling
1142   // an object file for later LTO. For LTO we want to preserve these so they
1143   // are eligible for inlining at link-time. Note if they are unreferenced they
1144   // will be removed by GlobalDCE later, so this only impacts referenced
1145   // available externally globals. Eventually they will be suppressed during
1146   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1147   // may make globals referenced by available external functions dead and saves
1148   // running remaining passes on the eliminated functions. These should be
1149   // preserved during prelinking for link-time inlining decisions.
1150   if (!LTOPreLink)
1151     MPM.addPass(EliminateAvailableExternallyPass());
1152 
1153   if (EnableOrderFileInstrumentation)
1154     MPM.addPass(InstrOrderFilePass());
1155 
1156   // Do RPO function attribute inference across the module to forward-propagate
1157   // attributes where applicable.
1158   // FIXME: Is this really an optimization rather than a canonicalization?
1159   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1160 
1161   // Do a post inline PGO instrumentation and use pass. This is a context
1162   // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1163   // cross-module inline has not been done yet. The context sensitive
1164   // instrumentation is after all the inlines are done.
1165   if (!LTOPreLink && PGOOpt) {
1166     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1167       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1168                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1169                         PGOOpt->ProfileRemappingFile);
1170     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1171       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1172                         /* IsCS */ true, PGOOpt->ProfileFile,
1173                         PGOOpt->ProfileRemappingFile);
1174   }
1175 
1176   // Re-compute GlobalsAA here prior to function passes. This is particularly
1177   // useful as the above will have inlined, DCE'ed, and function-attr
1178   // propagated everything. We should at this point have a reasonably minimal
1179   // and richly annotated call graph. By computing aliasing and mod/ref
1180   // information for all local globals here, the late loop passes and notably
1181   // the vectorizer will be able to use them to help recognize vectorizable
1182   // memory operations.
1183   MPM.addPass(RecomputeGlobalsAAPass());
1184 
1185   for (auto &C : OptimizerEarlyEPCallbacks)
1186     C(MPM, Level);
1187 
1188   FunctionPassManager OptimizePM;
1189   OptimizePM.addPass(Float2IntPass());
1190   OptimizePM.addPass(LowerConstantIntrinsicsPass());
1191 
1192   if (EnableMatrix) {
1193     OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1194     OptimizePM.addPass(EarlyCSEPass());
1195   }
1196 
1197   // FIXME: We need to run some loop optimizations to re-rotate loops after
1198   // simplifycfg and others undo their rotation.
1199 
1200   // Optimize the loop execution. These passes operate on entire loop nests
1201   // rather than on each loop in an inside-out manner, and so they are actually
1202   // function passes.
1203 
1204   for (auto &C : VectorizerStartEPCallbacks)
1205     C(OptimizePM, Level);
1206 
1207   LoopPassManager LPM;
1208   // First rotate loops that may have been un-rotated by prior passes.
1209   // Disable header duplication at -Oz.
1210   LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink));
1211   // Some loops may have become dead by now. Try to delete them.
1212   // FIXME: see discussion in https://reviews.llvm.org/D112851,
1213   //        this may need to be revisited once we run GVN before loop deletion
1214   //        in the simplification pipeline.
1215   LPM.addPass(LoopDeletionPass());
1216   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
1217       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false));
1218 
1219   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
1220   // into separate loop that would otherwise inhibit vectorization.  This is
1221   // currently only performed for loops marked with the metadata
1222   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1223   OptimizePM.addPass(LoopDistributePass());
1224 
1225   // Populates the VFABI attribute with the scalar-to-vector mappings
1226   // from the TargetLibraryInfo.
1227   OptimizePM.addPass(InjectTLIMappings());
1228 
1229   addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
1230 
1231   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1232   // canonicalization pass that enables other optimizations. As a result,
1233   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1234   // result too early.
1235   OptimizePM.addPass(LoopSinkPass());
1236 
1237   // And finally clean up LCSSA form before generating code.
1238   OptimizePM.addPass(InstSimplifyPass());
1239 
1240   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1241   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1242   // flattening of blocks.
1243   OptimizePM.addPass(DivRemPairsPass());
1244 
1245   // LoopSink (and other loop passes since the last simplifyCFG) might have
1246   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1247   OptimizePM.addPass(
1248       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1249 
1250   // Add the core optimizing pipeline.
1251   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1252                                                 PTO.EagerlyInvalidateAnalyses));
1253 
1254   for (auto &C : OptimizerLastEPCallbacks)
1255     C(MPM, Level);
1256 
1257   // Split out cold code. Splitting is done late to avoid hiding context from
1258   // other optimizations and inadvertently regressing performance. The tradeoff
1259   // is that this has a higher code size cost than splitting early.
1260   if (EnableHotColdSplit && !LTOPreLink)
1261     MPM.addPass(HotColdSplittingPass());
1262 
1263   // Search the code for similar regions of code. If enough similar regions can
1264   // be found where extracting the regions into their own function will decrease
1265   // the size of the program, we extract the regions, a deduplicate the
1266   // structurally similar regions.
1267   if (EnableIROutliner)
1268     MPM.addPass(IROutlinerPass());
1269 
1270   // Merge functions if requested.
1271   if (PTO.MergeFunctions)
1272     MPM.addPass(MergeFunctionsPass());
1273 
1274   if (PTO.CallGraphProfile)
1275     MPM.addPass(CGProfilePass());
1276 
1277   // Now we need to do some global optimization transforms.
1278   // FIXME: It would seem like these should come first in the optimization
1279   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1280   // ordering here.
1281   MPM.addPass(GlobalDCEPass());
1282   MPM.addPass(ConstantMergePass());
1283 
1284   // TODO: Relative look table converter pass caused an issue when full lto is
1285   // enabled. See https://reviews.llvm.org/D94355 for more details.
1286   // Until the issue fixed, disable this pass during pre-linking phase.
1287   if (!LTOPreLink)
1288     MPM.addPass(RelLookupTableConverterPass());
1289 
1290   return MPM;
1291 }
1292 
1293 ModulePassManager
1294 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1295                                            bool LTOPreLink) {
1296   assert(Level != OptimizationLevel::O0 &&
1297          "Must request optimizations for the default pipeline!");
1298 
1299   ModulePassManager MPM;
1300 
1301   // Convert @llvm.global.annotations to !annotation metadata.
1302   MPM.addPass(Annotation2MetadataPass());
1303 
1304   // Force any function attributes we want the rest of the pipeline to observe.
1305   MPM.addPass(ForceFunctionAttrsPass());
1306 
1307   // Apply module pipeline start EP callback.
1308   for (auto &C : PipelineStartEPCallbacks)
1309     C(MPM, Level);
1310 
1311   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1312     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1313 
1314   // Add the core simplification pipeline.
1315   MPM.addPass(buildModuleSimplificationPipeline(
1316       Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink
1317                         : ThinOrFullLTOPhase::None));
1318 
1319   // Now add the optimization pipeline.
1320   MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink));
1321 
1322   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1323       PGOOpt->Action == PGOOptions::SampleUse)
1324     MPM.addPass(PseudoProbeUpdatePass());
1325 
1326   // Emit annotation remarks.
1327   addAnnotationRemarksPass(MPM);
1328 
1329   if (LTOPreLink)
1330     addRequiredLTOPreLinkPasses(MPM);
1331 
1332   return MPM;
1333 }
1334 
1335 ModulePassManager
1336 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1337   assert(Level != OptimizationLevel::O0 &&
1338          "Must request optimizations for the default pipeline!");
1339 
1340   ModulePassManager MPM;
1341 
1342   // Convert @llvm.global.annotations to !annotation metadata.
1343   MPM.addPass(Annotation2MetadataPass());
1344 
1345   // Force any function attributes we want the rest of the pipeline to observe.
1346   MPM.addPass(ForceFunctionAttrsPass());
1347 
1348   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1349     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1350 
1351   // Apply module pipeline start EP callback.
1352   for (auto &C : PipelineStartEPCallbacks)
1353     C(MPM, Level);
1354 
1355   // If we are planning to perform ThinLTO later, we don't bloat the code with
1356   // unrolling/vectorization/... now. Just simplify the module as much as we
1357   // can.
1358   MPM.addPass(buildModuleSimplificationPipeline(
1359       Level, ThinOrFullLTOPhase::ThinLTOPreLink));
1360 
1361   // Run partial inlining pass to partially inline functions that have
1362   // large bodies.
1363   // FIXME: It isn't clear whether this is really the right place to run this
1364   // in ThinLTO. Because there is another canonicalization and simplification
1365   // phase that will run after the thin link, running this here ends up with
1366   // less information than will be available later and it may grow functions in
1367   // ways that aren't beneficial.
1368   if (RunPartialInlining)
1369     MPM.addPass(PartialInlinerPass());
1370 
1371   // Reduce the size of the IR as much as possible.
1372   MPM.addPass(GlobalOptPass());
1373 
1374   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1375       PGOOpt->Action == PGOOptions::SampleUse)
1376     MPM.addPass(PseudoProbeUpdatePass());
1377 
1378   // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual
1379   // optimization is going to be done in PostLink stage, but clang can't
1380   // add callbacks there in case of in-process ThinLTO called by linker.
1381   for (auto &C : OptimizerLastEPCallbacks)
1382     C(MPM, Level);
1383 
1384   // Emit annotation remarks.
1385   addAnnotationRemarksPass(MPM);
1386 
1387   addRequiredLTOPreLinkPasses(MPM);
1388 
1389   return MPM;
1390 }
1391 
1392 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1393     OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1394   ModulePassManager MPM;
1395 
1396   // Convert @llvm.global.annotations to !annotation metadata.
1397   MPM.addPass(Annotation2MetadataPass());
1398 
1399   if (ImportSummary) {
1400     // These passes import type identifier resolutions for whole-program
1401     // devirtualization and CFI. They must run early because other passes may
1402     // disturb the specific instruction patterns that these passes look for,
1403     // creating dependencies on resolutions that may not appear in the summary.
1404     //
1405     // For example, GVN may transform the pattern assume(type.test) appearing in
1406     // two basic blocks into assume(phi(type.test, type.test)), which would
1407     // transform a dependency on a WPD resolution into a dependency on a type
1408     // identifier resolution for CFI.
1409     //
1410     // Also, WPD has access to more precise information than ICP and can
1411     // devirtualize more effectively, so it should operate on the IR first.
1412     //
1413     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1414     // metadata and intrinsics.
1415     MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1416     MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1417   }
1418 
1419   if (Level == OptimizationLevel::O0) {
1420     // Run a second time to clean up any type tests left behind by WPD for use
1421     // in ICP.
1422     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1423     // Drop available_externally and unreferenced globals. This is necessary
1424     // with ThinLTO in order to avoid leaving undefined references to dead
1425     // globals in the object file.
1426     MPM.addPass(EliminateAvailableExternallyPass());
1427     MPM.addPass(GlobalDCEPass());
1428     return MPM;
1429   }
1430 
1431   // Force any function attributes we want the rest of the pipeline to observe.
1432   MPM.addPass(ForceFunctionAttrsPass());
1433 
1434   // Add the core simplification pipeline.
1435   MPM.addPass(buildModuleSimplificationPipeline(
1436       Level, ThinOrFullLTOPhase::ThinLTOPostLink));
1437 
1438   // Now add the optimization pipeline.
1439   MPM.addPass(buildModuleOptimizationPipeline(Level));
1440 
1441   // Emit annotation remarks.
1442   addAnnotationRemarksPass(MPM);
1443 
1444   return MPM;
1445 }
1446 
1447 ModulePassManager
1448 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1449   assert(Level != OptimizationLevel::O0 &&
1450          "Must request optimizations for the default pipeline!");
1451   // FIXME: We should use a customized pre-link pipeline!
1452   return buildPerModuleDefaultPipeline(Level,
1453                                        /* LTOPreLink */ true);
1454 }
1455 
1456 ModulePassManager
1457 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
1458                                      ModuleSummaryIndex *ExportSummary) {
1459   ModulePassManager MPM;
1460 
1461   // Convert @llvm.global.annotations to !annotation metadata.
1462   MPM.addPass(Annotation2MetadataPass());
1463 
1464   for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
1465     C(MPM, Level);
1466 
1467   // Create a function that performs CFI checks for cross-DSO calls with targets
1468   // in the current module.
1469   MPM.addPass(CrossDSOCFIPass());
1470 
1471   if (Level == OptimizationLevel::O0) {
1472     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1473     // metadata and intrinsics.
1474     MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1475     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1476     // Run a second time to clean up any type tests left behind by WPD for use
1477     // in ICP.
1478     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1479 
1480     for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1481       C(MPM, Level);
1482 
1483     // Emit annotation remarks.
1484     addAnnotationRemarksPass(MPM);
1485 
1486     return MPM;
1487   }
1488 
1489   if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1490     // Load sample profile before running the LTO optimization pipeline.
1491     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1492                                         PGOOpt->ProfileRemappingFile,
1493                                         ThinOrFullLTOPhase::FullLTOPostLink));
1494     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1495     // RequireAnalysisPass for PSI before subsequent non-module passes.
1496     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1497   }
1498 
1499   // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1500   MPM.addPass(OpenMPOptPass());
1501 
1502   // Remove unused virtual tables to improve the quality of code generated by
1503   // whole-program devirtualization and bitset lowering.
1504   MPM.addPass(GlobalDCEPass());
1505 
1506   // Force any function attributes we want the rest of the pipeline to observe.
1507   MPM.addPass(ForceFunctionAttrsPass());
1508 
1509   // Do basic inference of function attributes from known properties of system
1510   // libraries and other oracles.
1511   MPM.addPass(InferFunctionAttrsPass());
1512 
1513   if (Level.getSpeedupLevel() > 1) {
1514     MPM.addPass(createModuleToFunctionPassAdaptor(
1515         CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
1516 
1517     // Indirect call promotion. This should promote all the targets that are
1518     // left by the earlier promotion pass that promotes intra-module targets.
1519     // This two-step promotion is to save the compile time. For LTO, it should
1520     // produce the same result as if we only do promotion here.
1521     MPM.addPass(PGOIndirectCallPromotion(
1522         true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1523 
1524     if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
1525       MPM.addPass(FunctionSpecializationPass());
1526     // Propagate constants at call sites into the functions they call.  This
1527     // opens opportunities for globalopt (and inlining) by substituting function
1528     // pointers passed as arguments to direct uses of functions.
1529     MPM.addPass(IPSCCPPass());
1530 
1531     // Attach metadata to indirect call sites indicating the set of functions
1532     // they may target at run-time. This should follow IPSCCP.
1533     MPM.addPass(CalledValuePropagationPass());
1534   }
1535 
1536   // Now deduce any function attributes based in the current code.
1537   MPM.addPass(
1538       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1539 
1540   // Do RPO function attribute inference across the module to forward-propagate
1541   // attributes where applicable.
1542   // FIXME: Is this really an optimization rather than a canonicalization?
1543   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1544 
1545   // Use in-range annotations on GEP indices to split globals where beneficial.
1546   MPM.addPass(GlobalSplitPass());
1547 
1548   // Run whole program optimization of virtual call when the list of callees
1549   // is fixed.
1550   MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1551 
1552   // Stop here at -O1.
1553   if (Level == OptimizationLevel::O1) {
1554     // The LowerTypeTestsPass needs to run to lower type metadata and the
1555     // type.test intrinsics. The pass does nothing if CFI is disabled.
1556     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1557     // Run a second time to clean up any type tests left behind by WPD for use
1558     // in ICP (which is performed earlier than this in the regular LTO
1559     // pipeline).
1560     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1561 
1562     for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1563       C(MPM, Level);
1564 
1565     // Emit annotation remarks.
1566     addAnnotationRemarksPass(MPM);
1567 
1568     return MPM;
1569   }
1570 
1571   // Optimize globals to try and fold them into constants.
1572   MPM.addPass(GlobalOptPass());
1573 
1574   // Promote any localized globals to SSA registers.
1575   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1576 
1577   // Linking modules together can lead to duplicate global constant, only
1578   // keep one copy of each constant.
1579   MPM.addPass(ConstantMergePass());
1580 
1581   // Remove unused arguments from functions.
1582   MPM.addPass(DeadArgumentEliminationPass());
1583 
1584   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1585   // simplification opportunities, and both can propagate functions through
1586   // function pointers.  When this happens, we often have to resolve varargs
1587   // calls, etc, so let instcombine do this.
1588   FunctionPassManager PeepholeFPM;
1589   PeepholeFPM.addPass(InstCombinePass());
1590   if (Level == OptimizationLevel::O3)
1591     PeepholeFPM.addPass(AggressiveInstCombinePass());
1592   invokePeepholeEPCallbacks(PeepholeFPM, Level);
1593 
1594   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
1595                                                 PTO.EagerlyInvalidateAnalyses));
1596 
1597   // Note: historically, the PruneEH pass was run first to deduce nounwind and
1598   // generally clean up exception handling overhead. It isn't clear this is
1599   // valuable as the inliner doesn't currently care whether it is inlining an
1600   // invoke or a call.
1601   // Run the inliner now.
1602   MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level)));
1603 
1604   // Optimize globals again after we ran the inliner.
1605   MPM.addPass(GlobalOptPass());
1606 
1607   // Garbage collect dead functions.
1608   MPM.addPass(GlobalDCEPass());
1609 
1610   // If we didn't decide to inline a function, check to see if we can
1611   // transform it to pass arguments by value instead of by reference.
1612   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass()));
1613 
1614   FunctionPassManager FPM;
1615   // The IPO Passes may leave cruft around. Clean up after them.
1616   FPM.addPass(InstCombinePass());
1617   invokePeepholeEPCallbacks(FPM, Level);
1618 
1619   FPM.addPass(JumpThreadingPass());
1620 
1621   // Do a post inline PGO instrumentation and use pass. This is a context
1622   // sensitive PGO pass.
1623   if (PGOOpt) {
1624     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1625       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1626                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1627                         PGOOpt->ProfileRemappingFile);
1628     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1629       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1630                         /* IsCS */ true, PGOOpt->ProfileFile,
1631                         PGOOpt->ProfileRemappingFile);
1632   }
1633 
1634   // Break up allocas
1635   FPM.addPass(SROAPass());
1636 
1637   // LTO provides additional opportunities for tailcall elimination due to
1638   // link-time inlining, and visibility of nocapture attribute.
1639   FPM.addPass(TailCallElimPass());
1640 
1641   // Run a few AA driver optimizations here and now to cleanup the code.
1642   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
1643                                                 PTO.EagerlyInvalidateAnalyses));
1644 
1645   MPM.addPass(
1646       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1647 
1648   // Require the GlobalsAA analysis for the module so we can query it within
1649   // MainFPM.
1650   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
1651   // Invalidate AAManager so it can be recreated and pick up the newly available
1652   // GlobalsAA.
1653   MPM.addPass(
1654       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
1655 
1656   FunctionPassManager MainFPM;
1657   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1658       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1659                /*AllowSpeculation=*/true),
1660       /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
1661 
1662   if (RunNewGVN)
1663     MainFPM.addPass(NewGVNPass());
1664   else
1665     MainFPM.addPass(GVNPass());
1666 
1667   // Remove dead memcpy()'s.
1668   MainFPM.addPass(MemCpyOptPass());
1669 
1670   // Nuke dead stores.
1671   MainFPM.addPass(DSEPass());
1672   MainFPM.addPass(MergedLoadStoreMotionPass());
1673 
1674 
1675   if (EnableConstraintElimination)
1676     MainFPM.addPass(ConstraintEliminationPass());
1677 
1678   LoopPassManager LPM;
1679   if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
1680     LPM.addPass(LoopFlattenPass());
1681   LPM.addPass(IndVarSimplifyPass());
1682   LPM.addPass(LoopDeletionPass());
1683   // FIXME: Add loop interchange.
1684 
1685   // Unroll small loops and perform peeling.
1686   LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
1687                                  /* OnlyWhenForced= */ !PTO.LoopUnrolling,
1688                                  PTO.ForgetAllSCEVInLoopUnroll));
1689   // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
1690   // *All* loop passes must preserve it, in order to be able to use it.
1691   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1692       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
1693 
1694   MainFPM.addPass(LoopDistributePass());
1695 
1696   addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
1697 
1698   // Run the OpenMPOpt CGSCC pass again late.
1699   MPM.addPass(
1700       createModuleToPostOrderCGSCCPassAdaptor(OpenMPOptCGSCCPass()));
1701 
1702   invokePeepholeEPCallbacks(MainFPM, Level);
1703   MainFPM.addPass(JumpThreadingPass());
1704   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
1705                                                 PTO.EagerlyInvalidateAnalyses));
1706 
1707   // Lower type metadata and the type.test intrinsic. This pass supports
1708   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1709   // to be run at link time if CFI is enabled. This pass does nothing if
1710   // CFI is disabled.
1711   MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1712   // Run a second time to clean up any type tests left behind by WPD for use
1713   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1714   MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1715 
1716   // Enable splitting late in the FullLTO post-link pipeline. This is done in
1717   // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1718   if (EnableHotColdSplit)
1719     MPM.addPass(HotColdSplittingPass());
1720 
1721   // Add late LTO optimization passes.
1722   // Delete basic blocks, which optimization passes may have killed.
1723   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass(
1724       SimplifyCFGOptions().convertSwitchRangeToICmp(true).hoistCommonInsts(
1725           true))));
1726 
1727   // Drop bodies of available eternally objects to improve GlobalDCE.
1728   MPM.addPass(EliminateAvailableExternallyPass());
1729 
1730   // Now that we have optimized the program, discard unreachable functions.
1731   MPM.addPass(GlobalDCEPass());
1732 
1733   if (PTO.MergeFunctions)
1734     MPM.addPass(MergeFunctionsPass());
1735 
1736   for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1737     C(MPM, Level);
1738 
1739   // Emit annotation remarks.
1740   addAnnotationRemarksPass(MPM);
1741 
1742   return MPM;
1743 }
1744 
1745 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
1746                                                       bool LTOPreLink) {
1747   assert(Level == OptimizationLevel::O0 &&
1748          "buildO0DefaultPipeline should only be used with O0");
1749 
1750   ModulePassManager MPM;
1751 
1752   // Perform pseudo probe instrumentation in O0 mode. This is for the
1753   // consistency between different build modes. For example, a LTO build can be
1754   // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
1755   // the postlink will require pseudo probe instrumentation in the prelink.
1756   if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
1757     MPM.addPass(SampleProfileProbePass(TM));
1758 
1759   if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1760                  PGOOpt->Action == PGOOptions::IRUse))
1761     addPGOInstrPassesForO0(
1762         MPM,
1763         /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1764         /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1765 
1766   for (auto &C : PipelineStartEPCallbacks)
1767     C(MPM, Level);
1768 
1769   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1770     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1771 
1772   for (auto &C : PipelineEarlySimplificationEPCallbacks)
1773     C(MPM, Level);
1774 
1775   // Build a minimal pipeline based on the semantics required by LLVM,
1776   // which is just that always inlining occurs. Further, disable generating
1777   // lifetime intrinsics to avoid enabling further optimizations during
1778   // code generation.
1779   MPM.addPass(AlwaysInlinerPass(
1780       /*InsertLifetimeIntrinsics=*/false));
1781 
1782   if (PTO.MergeFunctions)
1783     MPM.addPass(MergeFunctionsPass());
1784 
1785   if (EnableMatrix)
1786     MPM.addPass(
1787         createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true)));
1788 
1789   if (!CGSCCOptimizerLateEPCallbacks.empty()) {
1790     CGSCCPassManager CGPM;
1791     for (auto &C : CGSCCOptimizerLateEPCallbacks)
1792       C(CGPM, Level);
1793     if (!CGPM.isEmpty())
1794       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1795   }
1796   if (!LateLoopOptimizationsEPCallbacks.empty()) {
1797     LoopPassManager LPM;
1798     for (auto &C : LateLoopOptimizationsEPCallbacks)
1799       C(LPM, Level);
1800     if (!LPM.isEmpty()) {
1801       MPM.addPass(createModuleToFunctionPassAdaptor(
1802           createFunctionToLoopPassAdaptor(std::move(LPM))));
1803     }
1804   }
1805   if (!LoopOptimizerEndEPCallbacks.empty()) {
1806     LoopPassManager LPM;
1807     for (auto &C : LoopOptimizerEndEPCallbacks)
1808       C(LPM, Level);
1809     if (!LPM.isEmpty()) {
1810       MPM.addPass(createModuleToFunctionPassAdaptor(
1811           createFunctionToLoopPassAdaptor(std::move(LPM))));
1812     }
1813   }
1814   if (!ScalarOptimizerLateEPCallbacks.empty()) {
1815     FunctionPassManager FPM;
1816     for (auto &C : ScalarOptimizerLateEPCallbacks)
1817       C(FPM, Level);
1818     if (!FPM.isEmpty())
1819       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1820   }
1821 
1822   for (auto &C : OptimizerEarlyEPCallbacks)
1823     C(MPM, Level);
1824 
1825   if (!VectorizerStartEPCallbacks.empty()) {
1826     FunctionPassManager FPM;
1827     for (auto &C : VectorizerStartEPCallbacks)
1828       C(FPM, Level);
1829     if (!FPM.isEmpty())
1830       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1831   }
1832 
1833   ModulePassManager CoroPM;
1834   CoroPM.addPass(CoroEarlyPass());
1835   CGSCCPassManager CGPM;
1836   CGPM.addPass(CoroSplitPass());
1837   CoroPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1838   CoroPM.addPass(CoroCleanupPass());
1839   CoroPM.addPass(GlobalDCEPass());
1840   MPM.addPass(CoroConditionalWrapper(std::move(CoroPM)));
1841 
1842   for (auto &C : OptimizerLastEPCallbacks)
1843     C(MPM, Level);
1844 
1845   if (LTOPreLink)
1846     addRequiredLTOPreLinkPasses(MPM);
1847 
1848   MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
1849 
1850   return MPM;
1851 }
1852 
1853 AAManager PassBuilder::buildDefaultAAPipeline() {
1854   AAManager AA;
1855 
1856   // The order in which these are registered determines their priority when
1857   // being queried.
1858 
1859   // First we register the basic alias analysis that provides the majority of
1860   // per-function local AA logic. This is a stateless, on-demand local set of
1861   // AA techniques.
1862   AA.registerFunctionAnalysis<BasicAA>();
1863 
1864   // Next we query fast, specialized alias analyses that wrap IR-embedded
1865   // information about aliasing.
1866   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1867   AA.registerFunctionAnalysis<TypeBasedAA>();
1868 
1869   // Add support for querying global aliasing information when available.
1870   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1871   // analysis, all that the `AAManager` can do is query for any *cached*
1872   // results from `GlobalsAA` through a readonly proxy.
1873   AA.registerModuleAnalysis<GlobalsAA>();
1874 
1875   // Add target-specific alias analyses.
1876   if (TM)
1877     TM->registerDefaultAliasAnalyses(AA);
1878 
1879   return AA;
1880 }
1881