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/CoroEarly.h"
36 #include "llvm/Transforms/Coroutines/CoroElide.h"
37 #include "llvm/Transforms/Coroutines/CoroSplit.h"
38 #include "llvm/Transforms/IPO/AlwaysInliner.h"
39 #include "llvm/Transforms/IPO/Annotation2Metadata.h"
40 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
41 #include "llvm/Transforms/IPO/Attributor.h"
42 #include "llvm/Transforms/IPO/CalledValuePropagation.h"
43 #include "llvm/Transforms/IPO/ConstantMerge.h"
44 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
45 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
46 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
47 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
48 #include "llvm/Transforms/IPO/FunctionAttrs.h"
49 #include "llvm/Transforms/IPO/GlobalDCE.h"
50 #include "llvm/Transforms/IPO/GlobalOpt.h"
51 #include "llvm/Transforms/IPO/GlobalSplit.h"
52 #include "llvm/Transforms/IPO/HotColdSplitting.h"
53 #include "llvm/Transforms/IPO/IROutliner.h"
54 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
55 #include "llvm/Transforms/IPO/Inliner.h"
56 #include "llvm/Transforms/IPO/LowerTypeTests.h"
57 #include "llvm/Transforms/IPO/MergeFunctions.h"
58 #include "llvm/Transforms/IPO/ModuleInliner.h"
59 #include "llvm/Transforms/IPO/OpenMPOpt.h"
60 #include "llvm/Transforms/IPO/PartialInlining.h"
61 #include "llvm/Transforms/IPO/SCCP.h"
62 #include "llvm/Transforms/IPO/SampleProfile.h"
63 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
64 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
65 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
66 #include "llvm/Transforms/InstCombine/InstCombine.h"
67 #include "llvm/Transforms/Instrumentation/CGProfile.h"
68 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
69 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
72 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
73 #include "llvm/Transforms/Scalar/ADCE.h"
74 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
75 #include "llvm/Transforms/Scalar/AnnotationRemarks.h"
76 #include "llvm/Transforms/Scalar/BDCE.h"
77 #include "llvm/Transforms/Scalar/CallSiteSplitting.h"
78 #include "llvm/Transforms/Scalar/ConstraintElimination.h"
79 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
80 #include "llvm/Transforms/Scalar/DFAJumpThreading.h"
81 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
82 #include "llvm/Transforms/Scalar/DivRemPairs.h"
83 #include "llvm/Transforms/Scalar/EarlyCSE.h"
84 #include "llvm/Transforms/Scalar/Float2Int.h"
85 #include "llvm/Transforms/Scalar/GVN.h"
86 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
87 #include "llvm/Transforms/Scalar/InstSimplifyPass.h"
88 #include "llvm/Transforms/Scalar/JumpThreading.h"
89 #include "llvm/Transforms/Scalar/LICM.h"
90 #include "llvm/Transforms/Scalar/LoopDeletion.h"
91 #include "llvm/Transforms/Scalar/LoopDistribute.h"
92 #include "llvm/Transforms/Scalar/LoopFlatten.h"
93 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
94 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
95 #include "llvm/Transforms/Scalar/LoopInterchange.h"
96 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
97 #include "llvm/Transforms/Scalar/LoopPassManager.h"
98 #include "llvm/Transforms/Scalar/LoopRotation.h"
99 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
100 #include "llvm/Transforms/Scalar/LoopSink.h"
101 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
102 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
103 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
104 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
105 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
106 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
107 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
108 #include "llvm/Transforms/Scalar/NewGVN.h"
109 #include "llvm/Transforms/Scalar/Reassociate.h"
110 #include "llvm/Transforms/Scalar/SCCP.h"
111 #include "llvm/Transforms/Scalar/SROA.h"
112 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
113 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
114 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
115 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
116 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
117 #include "llvm/Transforms/Utils/AddDiscriminators.h"
118 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
119 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
120 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
121 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
122 #include "llvm/Transforms/Utils/Mem2Reg.h"
123 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
124 #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
125 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h"
126 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
127 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
128 #include "llvm/Transforms/Vectorize/VectorCombine.h"
129 
130 using namespace llvm;
131 
132 static cl::opt<InliningAdvisorMode> UseInlineAdvisor(
133     "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden,
134     cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"),
135     cl::values(clEnumValN(InliningAdvisorMode::Default, "default",
136                           "Heuristics-based inliner version."),
137                clEnumValN(InliningAdvisorMode::Development, "development",
138                           "Use development mode (runtime-loadable model)."),
139                clEnumValN(InliningAdvisorMode::Release, "release",
140                           "Use release mode (AOT-compiled model).")));
141 
142 static cl::opt<bool> EnableSyntheticCounts(
143     "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore,
144     cl::desc("Run synthetic function entry count generation "
145              "pass"));
146 
147 /// Flag to enable inline deferral during PGO.
148 static cl::opt<bool>
149     EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true),
150                             cl::Hidden,
151                             cl::desc("Enable inline deferral during PGO"));
152 
153 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false),
154                                        cl::Hidden, cl::ZeroOrMore,
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, cl::ZeroOrMore,
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::ZeroOrMore, 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   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
716       PGOOpt->Action == PGOOptions::SampleUse)
717     IP.HotCallSiteThreshold = 0;
718 
719   if (PGOOpt)
720     IP.EnableDeferral = EnablePGOInlineDeferral;
721 
722   ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst,
723                                 UseInlineAdvisor, MaxDevirtIterations);
724 
725   // Require the GlobalsAA analysis for the module so we can query it within
726   // the CGSCC pipeline.
727   MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>());
728   // Invalidate AAManager so it can be recreated and pick up the newly available
729   // GlobalsAA.
730   MIWP.addModulePass(
731       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
732 
733   // Require the ProfileSummaryAnalysis for the module so we can query it within
734   // the inliner pass.
735   MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
736 
737   // Now begin the main postorder CGSCC pipeline.
738   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
739   // manager and trying to emulate its precise behavior. Much of this doesn't
740   // make a lot of sense and we should revisit the core CGSCC structure.
741   CGSCCPassManager &MainCGPipeline = MIWP.getPM();
742 
743   // Note: historically, the PruneEH pass was run first to deduce nounwind and
744   // generally clean up exception handling overhead. It isn't clear this is
745   // valuable as the inliner doesn't currently care whether it is inlining an
746   // invoke or a call.
747 
748   if (AttributorRun & AttributorRunOption::CGSCC)
749     MainCGPipeline.addPass(AttributorCGSCCPass());
750 
751   // Now deduce any function attributes based in the current code.
752   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
753 
754   // When at O3 add argument promotion to the pass pipeline.
755   // FIXME: It isn't at all clear why this should be limited to O3.
756   if (Level == OptimizationLevel::O3)
757     MainCGPipeline.addPass(ArgumentPromotionPass());
758 
759   // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if
760   // there are no OpenMP runtime calls present in the module.
761   if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3)
762     MainCGPipeline.addPass(OpenMPOptCGSCCPass());
763 
764   for (auto &C : CGSCCOptimizerLateEPCallbacks)
765     C(MainCGPipeline, Level);
766 
767   // Lastly, add the core function simplification pipeline nested inside the
768   // CGSCC walk.
769   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
770       buildFunctionSimplificationPipeline(Level, Phase),
771       PTO.EagerlyInvalidateAnalyses, EnableNoRerunSimplificationPipeline));
772 
773   MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0));
774 
775   if (EnableNoRerunSimplificationPipeline)
776     MIWP.addLateModulePass(createModuleToFunctionPassAdaptor(
777         InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>()));
778 
779   return MIWP;
780 }
781 
782 ModulePassManager
783 PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level,
784                                         ThinOrFullLTOPhase Phase) {
785   ModulePassManager MPM;
786 
787   InlineParams IP = getInlineParamsFromOptLevel(Level);
788   if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt &&
789       PGOOpt->Action == PGOOptions::SampleUse)
790     IP.HotCallSiteThreshold = 0;
791 
792   if (PGOOpt)
793     IP.EnableDeferral = EnablePGOInlineDeferral;
794 
795   // The inline deferral logic is used to avoid losing some
796   // inlining chance in future. It is helpful in SCC inliner, in which
797   // inlining is processed in bottom-up order.
798   // While in module inliner, the inlining order is a priority-based order
799   // by default. The inline deferral is unnecessary there. So we disable the
800   // inline deferral logic in module inliner.
801   IP.EnableDeferral = false;
802 
803   MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor));
804 
805   MPM.addPass(createModuleToFunctionPassAdaptor(
806       buildFunctionSimplificationPipeline(Level, Phase),
807       PTO.EagerlyInvalidateAnalyses));
808 
809   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
810       CoroSplitPass(Level != OptimizationLevel::O0)));
811 
812   return MPM;
813 }
814 
815 ModulePassManager
816 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
817                                                ThinOrFullLTOPhase Phase) {
818   ModulePassManager MPM;
819 
820   // Place pseudo probe instrumentation as the first pass of the pipeline to
821   // minimize the impact of optimization changes.
822   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
823       Phase != ThinOrFullLTOPhase::ThinLTOPostLink)
824     MPM.addPass(SampleProfileProbePass(TM));
825 
826   bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse);
827 
828   // In ThinLTO mode, when flattened profile is used, all the available
829   // profile information will be annotated in PreLink phase so there is
830   // no need to load the profile again in PostLink.
831   bool LoadSampleProfile =
832       HasSampleProfile &&
833       !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink);
834 
835   // During the ThinLTO backend phase we perform early indirect call promotion
836   // here, before globalopt. Otherwise imported available_externally functions
837   // look unreferenced and are removed. If we are going to load the sample
838   // profile then defer until later.
839   // TODO: See if we can move later and consolidate with the location where
840   // we perform ICP when we are loading a sample profile.
841   // TODO: We pass HasSampleProfile (whether there was a sample profile file
842   // passed to the compile) to the SamplePGO flag of ICP. This is used to
843   // determine whether the new direct calls are annotated with prof metadata.
844   // Ideally this should be determined from whether the IR is annotated with
845   // sample profile, and not whether the a sample profile was provided on the
846   // command line. E.g. for flattened profiles where we will not be reloading
847   // the sample profile in the ThinLTO backend, we ideally shouldn't have to
848   // provide the sample profile file.
849   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile)
850     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile));
851 
852   // Do basic inference of function attributes from known properties of system
853   // libraries and other oracles.
854   MPM.addPass(InferFunctionAttrsPass());
855 
856   // Create an early function pass manager to cleanup the output of the
857   // frontend.
858   FunctionPassManager EarlyFPM;
859   // Lower llvm.expect to metadata before attempting transforms.
860   // Compare/branch metadata may alter the behavior of passes like SimplifyCFG.
861   EarlyFPM.addPass(LowerExpectIntrinsicPass());
862   EarlyFPM.addPass(SimplifyCFGPass());
863   EarlyFPM.addPass(SROAPass());
864   EarlyFPM.addPass(EarlyCSEPass());
865   EarlyFPM.addPass(CoroEarlyPass());
866   if (Level == OptimizationLevel::O3)
867     EarlyFPM.addPass(CallSiteSplittingPass());
868 
869   // In SamplePGO ThinLTO backend, we need instcombine before profile annotation
870   // to convert bitcast to direct calls so that they can be inlined during the
871   // profile annotation prepration step.
872   // More details about SamplePGO design can be found in:
873   // https://research.google.com/pubs/pub45290.html
874   // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured.
875   if (LoadSampleProfile)
876     EarlyFPM.addPass(InstCombinePass());
877   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM),
878                                                 PTO.EagerlyInvalidateAnalyses));
879 
880   if (LoadSampleProfile) {
881     // Annotate sample profile right after early FPM to ensure freshness of
882     // the debug info.
883     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
884                                         PGOOpt->ProfileRemappingFile, Phase));
885     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
886     // RequireAnalysisPass for PSI before subsequent non-module passes.
887     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
888     // Do not invoke ICP in the LTOPrelink phase as it makes it hard
889     // for the profile annotation to be accurate in the LTO backend.
890     if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink &&
891         Phase != ThinOrFullLTOPhase::FullLTOPreLink)
892       // We perform early indirect call promotion here, before globalopt.
893       // This is important for the ThinLTO backend phase because otherwise
894       // imported available_externally functions look unreferenced and are
895       // removed.
896       MPM.addPass(
897           PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */));
898   }
899 
900   // Try to perform OpenMP specific optimizations on the module. This is a
901   // (quick!) no-op if there are no OpenMP runtime calls present in the module.
902   if (Level != OptimizationLevel::O0)
903     MPM.addPass(OpenMPOptPass());
904 
905   if (AttributorRun & AttributorRunOption::MODULE)
906     MPM.addPass(AttributorPass());
907 
908   // Lower type metadata and the type.test intrinsic in the ThinLTO
909   // post link pipeline after ICP. This is to enable usage of the type
910   // tests in ICP sequences.
911   if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink)
912     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
913 
914   for (auto &C : PipelineEarlySimplificationEPCallbacks)
915     C(MPM, Level);
916 
917   // Specialize functions with IPSCCP.
918   if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
919     MPM.addPass(FunctionSpecializationPass());
920 
921   // Interprocedural constant propagation now that basic cleanup has occurred
922   // and prior to optimizing globals.
923   // FIXME: This position in the pipeline hasn't been carefully considered in
924   // years, it should be re-analyzed.
925   MPM.addPass(IPSCCPPass());
926 
927   // Attach metadata to indirect call sites indicating the set of functions
928   // they may target at run-time. This should follow IPSCCP.
929   MPM.addPass(CalledValuePropagationPass());
930 
931   // Optimize globals to try and fold them into constants.
932   MPM.addPass(GlobalOptPass());
933 
934   // Promote any localized globals to SSA registers.
935   // FIXME: Should this instead by a run of SROA?
936   // FIXME: We should probably run instcombine and simplifycfg afterward to
937   // delete control flows that are dead once globals have been folded to
938   // constants.
939   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
940 
941   // Remove any dead arguments exposed by cleanups and constant folding
942   // globals.
943   MPM.addPass(DeadArgumentEliminationPass());
944 
945   // Create a small function pass pipeline to cleanup after all the global
946   // optimizations.
947   FunctionPassManager GlobalCleanupPM;
948   GlobalCleanupPM.addPass(InstCombinePass());
949   invokePeepholeEPCallbacks(GlobalCleanupPM, Level);
950 
951   GlobalCleanupPM.addPass(
952       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
953   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM),
954                                                 PTO.EagerlyInvalidateAnalyses));
955 
956   // Add all the requested passes for instrumentation PGO, if requested.
957   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
958       (PGOOpt->Action == PGOOptions::IRInstr ||
959        PGOOpt->Action == PGOOptions::IRUse)) {
960     addPGOInstrPasses(MPM, Level,
961                       /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr,
962                       /* IsCS */ false, PGOOpt->ProfileFile,
963                       PGOOpt->ProfileRemappingFile);
964     MPM.addPass(PGOIndirectCallPromotion(false, false));
965   }
966   if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink &&
967       PGOOpt->CSAction == PGOOptions::CSIRInstr)
968     MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile));
969 
970   // Synthesize function entry counts for non-PGO compilation.
971   if (EnableSyntheticCounts && !PGOOpt)
972     MPM.addPass(SyntheticCountsPropagation());
973 
974   if (EnableModuleInliner)
975     MPM.addPass(buildModuleInlinerPipeline(Level, Phase));
976   else
977     MPM.addPass(buildInlinerPipeline(Level, Phase));
978 
979   if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) {
980     MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
981     MPM.addPass(ModuleMemProfilerPass());
982   }
983 
984   return MPM;
985 }
986 
987 /// TODO: Should LTO cause any differences to this set of passes?
988 void PassBuilder::addVectorPasses(OptimizationLevel Level,
989                                   FunctionPassManager &FPM, bool IsFullLTO) {
990   FPM.addPass(LoopVectorizePass(
991       LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization)));
992 
993   if (IsFullLTO) {
994     // The vectorizer may have significantly shortened a loop body; unroll
995     // again. Unroll small loops to hide loop backedge latency and saturate any
996     // parallel execution resources of an out-of-order processor. We also then
997     // need to clean up redundancies and loop invariant code.
998     // FIXME: It would be really good to use a loop-integrated instruction
999     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1000     // across the loop nests.
1001     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1002     if (EnableUnrollAndJam && PTO.LoopUnrolling)
1003       FPM.addPass(createFunctionToLoopPassAdaptor(
1004           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1005     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1006         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1007         PTO.ForgetAllSCEVInLoopUnroll)));
1008     FPM.addPass(WarnMissedTransformationsPass());
1009   }
1010 
1011   if (!IsFullLTO) {
1012     // Eliminate loads by forwarding stores from the previous iteration to loads
1013     // of the current iteration.
1014     FPM.addPass(LoopLoadEliminationPass());
1015   }
1016   // Cleanup after the loop optimization passes.
1017   FPM.addPass(InstCombinePass());
1018 
1019   if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1020     ExtraVectorPassManager ExtraPasses;
1021     // At higher optimization levels, try to clean up any runtime overlap and
1022     // alignment checks inserted by the vectorizer. We want to track correlated
1023     // runtime checks for two inner loops in the same outer loop, fold any
1024     // common computations, hoist loop-invariant aspects out of any outer loop,
1025     // and unswitch the runtime checks if possible. Once hoisted, we may have
1026     // dead (or speculatable) control flows or more combining opportunities.
1027     ExtraPasses.addPass(EarlyCSEPass());
1028     ExtraPasses.addPass(CorrelatedValuePropagationPass());
1029     ExtraPasses.addPass(InstCombinePass());
1030     LoopPassManager LPM;
1031     LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1032                          /*AllowSpeculation=*/true));
1033     LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level ==
1034                                        OptimizationLevel::O3));
1035     ExtraPasses.addPass(
1036         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1037     ExtraPasses.addPass(
1038         createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true,
1039                                         /*UseBlockFrequencyInfo=*/true));
1040     ExtraPasses.addPass(
1041         SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1042     ExtraPasses.addPass(InstCombinePass());
1043     FPM.addPass(std::move(ExtraPasses));
1044   }
1045 
1046   // Now that we've formed fast to execute loop structures, we do further
1047   // optimizations. These are run afterward as they might block doing complex
1048   // analyses and transforms such as what are needed for loop vectorization.
1049 
1050   // Cleanup after loop vectorization, etc. Simplification passes like CVP and
1051   // GVN, loop transforms, and others have already run, so it's now better to
1052   // convert to more optimized IR using more aggressive simplify CFG options.
1053   // The extra sinking transform can create larger basic blocks, so do this
1054   // before SLP vectorization.
1055   FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions()
1056                                   .forwardSwitchCondToPhi(true)
1057                                   .convertSwitchRangeToICmp(true)
1058                                   .convertSwitchToLookupTable(true)
1059                                   .needCanonicalLoops(false)
1060                                   .hoistCommonInsts(true)
1061                                   .sinkCommonInsts(true)));
1062 
1063   if (IsFullLTO) {
1064     FPM.addPass(SCCPPass());
1065     FPM.addPass(InstCombinePass());
1066     FPM.addPass(BDCEPass());
1067   }
1068 
1069   // Optimize parallel scalar instruction chains into SIMD instructions.
1070   if (PTO.SLPVectorization) {
1071     FPM.addPass(SLPVectorizerPass());
1072     if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) {
1073       FPM.addPass(EarlyCSEPass());
1074     }
1075   }
1076   // Enhance/cleanup vector code.
1077   FPM.addPass(VectorCombinePass());
1078 
1079   if (!IsFullLTO) {
1080     FPM.addPass(InstCombinePass());
1081     // Unroll small loops to hide loop backedge latency and saturate any
1082     // parallel execution resources of an out-of-order processor. We also then
1083     // need to clean up redundancies and loop invariant code.
1084     // FIXME: It would be really good to use a loop-integrated instruction
1085     // combiner for cleanup here so that the unrolling and LICM can be pipelined
1086     // across the loop nests.
1087     // We do UnrollAndJam in a separate LPM to ensure it happens before unroll
1088     if (EnableUnrollAndJam && PTO.LoopUnrolling) {
1089       FPM.addPass(createFunctionToLoopPassAdaptor(
1090           LoopUnrollAndJamPass(Level.getSpeedupLevel())));
1091     }
1092     FPM.addPass(LoopUnrollPass(LoopUnrollOptions(
1093         Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling,
1094         PTO.ForgetAllSCEVInLoopUnroll)));
1095     FPM.addPass(WarnMissedTransformationsPass());
1096     FPM.addPass(InstCombinePass());
1097     FPM.addPass(
1098         RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
1099     FPM.addPass(createFunctionToLoopPassAdaptor(
1100         LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1101                  /*AllowSpeculation=*/true),
1102         /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
1103   }
1104 
1105   // Now that we've vectorized and unrolled loops, we may have more refined
1106   // alignment information, try to re-derive it here.
1107   FPM.addPass(AlignmentFromAssumptionsPass());
1108 
1109   if (IsFullLTO)
1110     FPM.addPass(InstCombinePass());
1111 }
1112 
1113 ModulePassManager
1114 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
1115                                              bool LTOPreLink) {
1116   ModulePassManager MPM;
1117 
1118   // Optimize globals now that the module is fully simplified.
1119   MPM.addPass(GlobalOptPass());
1120   MPM.addPass(GlobalDCEPass());
1121 
1122   // Run partial inlining pass to partially inline functions that have
1123   // large bodies.
1124   if (RunPartialInlining)
1125     MPM.addPass(PartialInlinerPass());
1126 
1127   // Remove avail extern fns and globals definitions since we aren't compiling
1128   // an object file for later LTO. For LTO we want to preserve these so they
1129   // are eligible for inlining at link-time. Note if they are unreferenced they
1130   // will be removed by GlobalDCE later, so this only impacts referenced
1131   // available externally globals. Eventually they will be suppressed during
1132   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
1133   // may make globals referenced by available external functions dead and saves
1134   // running remaining passes on the eliminated functions. These should be
1135   // preserved during prelinking for link-time inlining decisions.
1136   if (!LTOPreLink)
1137     MPM.addPass(EliminateAvailableExternallyPass());
1138 
1139   if (EnableOrderFileInstrumentation)
1140     MPM.addPass(InstrOrderFilePass());
1141 
1142   // Do RPO function attribute inference across the module to forward-propagate
1143   // attributes where applicable.
1144   // FIXME: Is this really an optimization rather than a canonicalization?
1145   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1146 
1147   // Do a post inline PGO instrumentation and use pass. This is a context
1148   // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as
1149   // cross-module inline has not been done yet. The context sensitive
1150   // instrumentation is after all the inlines are done.
1151   if (!LTOPreLink && PGOOpt) {
1152     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1153       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1154                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1155                         PGOOpt->ProfileRemappingFile);
1156     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1157       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1158                         /* IsCS */ true, PGOOpt->ProfileFile,
1159                         PGOOpt->ProfileRemappingFile);
1160   }
1161 
1162   // Re-compute GlobalsAA here prior to function passes. This is particularly
1163   // useful as the above will have inlined, DCE'ed, and function-attr
1164   // propagated everything. We should at this point have a reasonably minimal
1165   // and richly annotated call graph. By computing aliasing and mod/ref
1166   // information for all local globals here, the late loop passes and notably
1167   // the vectorizer will be able to use them to help recognize vectorizable
1168   // memory operations.
1169   MPM.addPass(RecomputeGlobalsAAPass());
1170 
1171   FunctionPassManager OptimizePM;
1172   OptimizePM.addPass(Float2IntPass());
1173   OptimizePM.addPass(LowerConstantIntrinsicsPass());
1174 
1175   if (EnableMatrix) {
1176     OptimizePM.addPass(LowerMatrixIntrinsicsPass());
1177     OptimizePM.addPass(EarlyCSEPass());
1178   }
1179 
1180   // FIXME: We need to run some loop optimizations to re-rotate loops after
1181   // simplifycfg and others undo their rotation.
1182 
1183   // Optimize the loop execution. These passes operate on entire loop nests
1184   // rather than on each loop in an inside-out manner, and so they are actually
1185   // function passes.
1186 
1187   for (auto &C : VectorizerStartEPCallbacks)
1188     C(OptimizePM, Level);
1189 
1190   LoopPassManager LPM;
1191   // First rotate loops that may have been un-rotated by prior passes.
1192   // Disable header duplication at -Oz.
1193   LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink));
1194   // Some loops may have become dead by now. Try to delete them.
1195   // FIXME: see discussion in https://reviews.llvm.org/D112851,
1196   //        this may need to be revisited once we run GVN before loop deletion
1197   //        in the simplification pipeline.
1198   LPM.addPass(LoopDeletionPass());
1199   OptimizePM.addPass(createFunctionToLoopPassAdaptor(
1200       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false));
1201 
1202   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
1203   // into separate loop that would otherwise inhibit vectorization.  This is
1204   // currently only performed for loops marked with the metadata
1205   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
1206   OptimizePM.addPass(LoopDistributePass());
1207 
1208   // Populates the VFABI attribute with the scalar-to-vector mappings
1209   // from the TargetLibraryInfo.
1210   OptimizePM.addPass(InjectTLIMappings());
1211 
1212   addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false);
1213 
1214   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
1215   // canonicalization pass that enables other optimizations. As a result,
1216   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
1217   // result too early.
1218   OptimizePM.addPass(LoopSinkPass());
1219 
1220   // And finally clean up LCSSA form before generating code.
1221   OptimizePM.addPass(InstSimplifyPass());
1222 
1223   // This hoists/decomposes div/rem ops. It should run after other sink/hoist
1224   // passes to avoid re-sinking, but before SimplifyCFG because it can allow
1225   // flattening of blocks.
1226   OptimizePM.addPass(DivRemPairsPass());
1227 
1228   // LoopSink (and other loop passes since the last simplifyCFG) might have
1229   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
1230   OptimizePM.addPass(
1231       SimplifyCFGPass(SimplifyCFGOptions().convertSwitchRangeToICmp(true)));
1232 
1233   OptimizePM.addPass(CoroCleanupPass());
1234 
1235   // Add the core optimizing pipeline.
1236   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM),
1237                                                 PTO.EagerlyInvalidateAnalyses));
1238 
1239   for (auto &C : OptimizerLastEPCallbacks)
1240     C(MPM, Level);
1241 
1242   // Split out cold code. Splitting is done late to avoid hiding context from
1243   // other optimizations and inadvertently regressing performance. The tradeoff
1244   // is that this has a higher code size cost than splitting early.
1245   if (EnableHotColdSplit && !LTOPreLink)
1246     MPM.addPass(HotColdSplittingPass());
1247 
1248   // Search the code for similar regions of code. If enough similar regions can
1249   // be found where extracting the regions into their own function will decrease
1250   // the size of the program, we extract the regions, a deduplicate the
1251   // structurally similar regions.
1252   if (EnableIROutliner)
1253     MPM.addPass(IROutlinerPass());
1254 
1255   // Merge functions if requested.
1256   if (PTO.MergeFunctions)
1257     MPM.addPass(MergeFunctionsPass());
1258 
1259   if (PTO.CallGraphProfile)
1260     MPM.addPass(CGProfilePass());
1261 
1262   // Now we need to do some global optimization transforms.
1263   // FIXME: It would seem like these should come first in the optimization
1264   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
1265   // ordering here.
1266   MPM.addPass(GlobalDCEPass());
1267   MPM.addPass(ConstantMergePass());
1268 
1269   // TODO: Relative look table converter pass caused an issue when full lto is
1270   // enabled. See https://reviews.llvm.org/D94355 for more details.
1271   // Until the issue fixed, disable this pass during pre-linking phase.
1272   if (!LTOPreLink)
1273     MPM.addPass(RelLookupTableConverterPass());
1274 
1275   return MPM;
1276 }
1277 
1278 ModulePassManager
1279 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
1280                                            bool LTOPreLink) {
1281   assert(Level != OptimizationLevel::O0 &&
1282          "Must request optimizations for the default pipeline!");
1283 
1284   ModulePassManager MPM;
1285 
1286   // Convert @llvm.global.annotations to !annotation metadata.
1287   MPM.addPass(Annotation2MetadataPass());
1288 
1289   // Force any function attributes we want the rest of the pipeline to observe.
1290   MPM.addPass(ForceFunctionAttrsPass());
1291 
1292   // Apply module pipeline start EP callback.
1293   for (auto &C : PipelineStartEPCallbacks)
1294     C(MPM, Level);
1295 
1296   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1297     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1298 
1299   // Add the core simplification pipeline.
1300   MPM.addPass(buildModuleSimplificationPipeline(
1301       Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink
1302                         : ThinOrFullLTOPhase::None));
1303 
1304   // Now add the optimization pipeline.
1305   MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink));
1306 
1307   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1308       PGOOpt->Action == PGOOptions::SampleUse)
1309     MPM.addPass(PseudoProbeUpdatePass());
1310 
1311   // Emit annotation remarks.
1312   addAnnotationRemarksPass(MPM);
1313 
1314   if (LTOPreLink)
1315     addRequiredLTOPreLinkPasses(MPM);
1316 
1317   return MPM;
1318 }
1319 
1320 ModulePassManager
1321 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1322   assert(Level != OptimizationLevel::O0 &&
1323          "Must request optimizations for the default pipeline!");
1324 
1325   ModulePassManager MPM;
1326 
1327   // Convert @llvm.global.annotations to !annotation metadata.
1328   MPM.addPass(Annotation2MetadataPass());
1329 
1330   // Force any function attributes we want the rest of the pipeline to observe.
1331   MPM.addPass(ForceFunctionAttrsPass());
1332 
1333   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1334     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1335 
1336   // Apply module pipeline start EP callback.
1337   for (auto &C : PipelineStartEPCallbacks)
1338     C(MPM, Level);
1339 
1340   // If we are planning to perform ThinLTO later, we don't bloat the code with
1341   // unrolling/vectorization/... now. Just simplify the module as much as we
1342   // can.
1343   MPM.addPass(buildModuleSimplificationPipeline(
1344       Level, ThinOrFullLTOPhase::ThinLTOPreLink));
1345 
1346   // Run partial inlining pass to partially inline functions that have
1347   // large bodies.
1348   // FIXME: It isn't clear whether this is really the right place to run this
1349   // in ThinLTO. Because there is another canonicalization and simplification
1350   // phase that will run after the thin link, running this here ends up with
1351   // less information than will be available later and it may grow functions in
1352   // ways that aren't beneficial.
1353   if (RunPartialInlining)
1354     MPM.addPass(PartialInlinerPass());
1355 
1356   // Reduce the size of the IR as much as possible.
1357   MPM.addPass(GlobalOptPass());
1358 
1359   // Module simplification splits coroutines, but does not fully clean up
1360   // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up
1361   // on these, we schedule the cleanup here.
1362   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1363 
1364   if (PGOOpt && PGOOpt->PseudoProbeForProfiling &&
1365       PGOOpt->Action == PGOOptions::SampleUse)
1366     MPM.addPass(PseudoProbeUpdatePass());
1367 
1368   // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual
1369   // optimization is going to be done in PostLink stage, but clang can't
1370   // add callbacks there in case of in-process ThinLTO called by linker.
1371   for (auto &C : OptimizerLastEPCallbacks)
1372     C(MPM, Level);
1373 
1374   // Emit annotation remarks.
1375   addAnnotationRemarksPass(MPM);
1376 
1377   addRequiredLTOPreLinkPasses(MPM);
1378 
1379   return MPM;
1380 }
1381 
1382 ModulePassManager PassBuilder::buildThinLTODefaultPipeline(
1383     OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) {
1384   ModulePassManager MPM;
1385 
1386   // Convert @llvm.global.annotations to !annotation metadata.
1387   MPM.addPass(Annotation2MetadataPass());
1388 
1389   if (ImportSummary) {
1390     // These passes import type identifier resolutions for whole-program
1391     // devirtualization and CFI. They must run early because other passes may
1392     // disturb the specific instruction patterns that these passes look for,
1393     // creating dependencies on resolutions that may not appear in the summary.
1394     //
1395     // For example, GVN may transform the pattern assume(type.test) appearing in
1396     // two basic blocks into assume(phi(type.test, type.test)), which would
1397     // transform a dependency on a WPD resolution into a dependency on a type
1398     // identifier resolution for CFI.
1399     //
1400     // Also, WPD has access to more precise information than ICP and can
1401     // devirtualize more effectively, so it should operate on the IR first.
1402     //
1403     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1404     // metadata and intrinsics.
1405     MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary));
1406     MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary));
1407   }
1408 
1409   if (Level == OptimizationLevel::O0) {
1410     // Run a second time to clean up any type tests left behind by WPD for use
1411     // in ICP.
1412     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1413     // Drop available_externally and unreferenced globals. This is necessary
1414     // with ThinLTO in order to avoid leaving undefined references to dead
1415     // globals in the object file.
1416     MPM.addPass(EliminateAvailableExternallyPass());
1417     MPM.addPass(GlobalDCEPass());
1418     return MPM;
1419   }
1420 
1421   // Force any function attributes we want the rest of the pipeline to observe.
1422   MPM.addPass(ForceFunctionAttrsPass());
1423 
1424   // Add the core simplification pipeline.
1425   MPM.addPass(buildModuleSimplificationPipeline(
1426       Level, ThinOrFullLTOPhase::ThinLTOPostLink));
1427 
1428   // Now add the optimization pipeline.
1429   MPM.addPass(buildModuleOptimizationPipeline(Level));
1430 
1431   // Emit annotation remarks.
1432   addAnnotationRemarksPass(MPM);
1433 
1434   return MPM;
1435 }
1436 
1437 ModulePassManager
1438 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) {
1439   assert(Level != OptimizationLevel::O0 &&
1440          "Must request optimizations for the default pipeline!");
1441   // FIXME: We should use a customized pre-link pipeline!
1442   return buildPerModuleDefaultPipeline(Level,
1443                                        /* LTOPreLink */ true);
1444 }
1445 
1446 ModulePassManager
1447 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
1448                                      ModuleSummaryIndex *ExportSummary) {
1449   ModulePassManager MPM;
1450 
1451   // Convert @llvm.global.annotations to !annotation metadata.
1452   MPM.addPass(Annotation2MetadataPass());
1453 
1454   for (auto &C : FullLinkTimeOptimizationEarlyEPCallbacks)
1455     C(MPM, Level);
1456 
1457   // Create a function that performs CFI checks for cross-DSO calls with targets
1458   // in the current module.
1459   MPM.addPass(CrossDSOCFIPass());
1460 
1461   if (Level == OptimizationLevel::O0) {
1462     // The WPD and LowerTypeTest passes need to run at -O0 to lower type
1463     // metadata and intrinsics.
1464     MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1465     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1466     // Run a second time to clean up any type tests left behind by WPD for use
1467     // in ICP.
1468     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1469 
1470     for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1471       C(MPM, Level);
1472 
1473     // Emit annotation remarks.
1474     addAnnotationRemarksPass(MPM);
1475 
1476     return MPM;
1477   }
1478 
1479   if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) {
1480     // Load sample profile before running the LTO optimization pipeline.
1481     MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile,
1482                                         PGOOpt->ProfileRemappingFile,
1483                                         ThinOrFullLTOPhase::FullLTOPostLink));
1484     // Cache ProfileSummaryAnalysis once to avoid the potential need to insert
1485     // RequireAnalysisPass for PSI before subsequent non-module passes.
1486     MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
1487   }
1488 
1489   // Try to run OpenMP optimizations, quick no-op if no OpenMP metadata present.
1490   MPM.addPass(OpenMPOptPass());
1491 
1492   // Remove unused virtual tables to improve the quality of code generated by
1493   // whole-program devirtualization and bitset lowering.
1494   MPM.addPass(GlobalDCEPass());
1495 
1496   // Force any function attributes we want the rest of the pipeline to observe.
1497   MPM.addPass(ForceFunctionAttrsPass());
1498 
1499   // Do basic inference of function attributes from known properties of system
1500   // libraries and other oracles.
1501   MPM.addPass(InferFunctionAttrsPass());
1502 
1503   if (Level.getSpeedupLevel() > 1) {
1504     MPM.addPass(createModuleToFunctionPassAdaptor(
1505         CallSiteSplittingPass(), PTO.EagerlyInvalidateAnalyses));
1506 
1507     // Indirect call promotion. This should promote all the targets that are
1508     // left by the earlier promotion pass that promotes intra-module targets.
1509     // This two-step promotion is to save the compile time. For LTO, it should
1510     // produce the same result as if we only do promotion here.
1511     MPM.addPass(PGOIndirectCallPromotion(
1512         true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse));
1513 
1514     if (EnableFunctionSpecialization && Level == OptimizationLevel::O3)
1515       MPM.addPass(FunctionSpecializationPass());
1516     // Propagate constants at call sites into the functions they call.  This
1517     // opens opportunities for globalopt (and inlining) by substituting function
1518     // pointers passed as arguments to direct uses of functions.
1519     MPM.addPass(IPSCCPPass());
1520 
1521     // Attach metadata to indirect call sites indicating the set of functions
1522     // they may target at run-time. This should follow IPSCCP.
1523     MPM.addPass(CalledValuePropagationPass());
1524   }
1525 
1526   // Now deduce any function attributes based in the current code.
1527   MPM.addPass(
1528       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1529 
1530   // Do RPO function attribute inference across the module to forward-propagate
1531   // attributes where applicable.
1532   // FIXME: Is this really an optimization rather than a canonicalization?
1533   MPM.addPass(ReversePostOrderFunctionAttrsPass());
1534 
1535   // Use in-range annotations on GEP indices to split globals where beneficial.
1536   MPM.addPass(GlobalSplitPass());
1537 
1538   // Run whole program optimization of virtual call when the list of callees
1539   // is fixed.
1540   MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr));
1541 
1542   // Stop here at -O1.
1543   if (Level == OptimizationLevel::O1) {
1544     // The LowerTypeTestsPass needs to run to lower type metadata and the
1545     // type.test intrinsics. The pass does nothing if CFI is disabled.
1546     MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1547     // Run a second time to clean up any type tests left behind by WPD for use
1548     // in ICP (which is performed earlier than this in the regular LTO
1549     // pipeline).
1550     MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1551 
1552     for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1553       C(MPM, Level);
1554 
1555     // Emit annotation remarks.
1556     addAnnotationRemarksPass(MPM);
1557 
1558     return MPM;
1559   }
1560 
1561   // Optimize globals to try and fold them into constants.
1562   MPM.addPass(GlobalOptPass());
1563 
1564   // Promote any localized globals to SSA registers.
1565   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
1566 
1567   // Linking modules together can lead to duplicate global constant, only
1568   // keep one copy of each constant.
1569   MPM.addPass(ConstantMergePass());
1570 
1571   // Remove unused arguments from functions.
1572   MPM.addPass(DeadArgumentEliminationPass());
1573 
1574   // Reduce the code after globalopt and ipsccp.  Both can open up significant
1575   // simplification opportunities, and both can propagate functions through
1576   // function pointers.  When this happens, we often have to resolve varargs
1577   // calls, etc, so let instcombine do this.
1578   FunctionPassManager PeepholeFPM;
1579   PeepholeFPM.addPass(InstCombinePass());
1580   if (Level == OptimizationLevel::O3)
1581     PeepholeFPM.addPass(AggressiveInstCombinePass());
1582   invokePeepholeEPCallbacks(PeepholeFPM, Level);
1583 
1584   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM),
1585                                                 PTO.EagerlyInvalidateAnalyses));
1586 
1587   // Note: historically, the PruneEH pass was run first to deduce nounwind and
1588   // generally clean up exception handling overhead. It isn't clear this is
1589   // valuable as the inliner doesn't currently care whether it is inlining an
1590   // invoke or a call.
1591   // Run the inliner now.
1592   MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level)));
1593 
1594   // Optimize globals again after we ran the inliner.
1595   MPM.addPass(GlobalOptPass());
1596 
1597   // Garbage collect dead functions.
1598   MPM.addPass(GlobalDCEPass());
1599 
1600   // If we didn't decide to inline a function, check to see if we can
1601   // transform it to pass arguments by value instead of by reference.
1602   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass()));
1603 
1604   FunctionPassManager FPM;
1605   // The IPO Passes may leave cruft around. Clean up after them.
1606   FPM.addPass(InstCombinePass());
1607   invokePeepholeEPCallbacks(FPM, Level);
1608 
1609   FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
1610 
1611   // Do a post inline PGO instrumentation and use pass. This is a context
1612   // sensitive PGO pass.
1613   if (PGOOpt) {
1614     if (PGOOpt->CSAction == PGOOptions::CSIRInstr)
1615       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true,
1616                         /* IsCS */ true, PGOOpt->CSProfileGenFile,
1617                         PGOOpt->ProfileRemappingFile);
1618     else if (PGOOpt->CSAction == PGOOptions::CSIRUse)
1619       addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false,
1620                         /* IsCS */ true, PGOOpt->ProfileFile,
1621                         PGOOpt->ProfileRemappingFile);
1622   }
1623 
1624   // Break up allocas
1625   FPM.addPass(SROAPass());
1626 
1627   // LTO provides additional opportunities for tailcall elimination due to
1628   // link-time inlining, and visibility of nocapture attribute.
1629   FPM.addPass(TailCallElimPass());
1630 
1631   // Run a few AA driver optimizations here and now to cleanup the code.
1632   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
1633                                                 PTO.EagerlyInvalidateAnalyses));
1634 
1635   MPM.addPass(
1636       createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass()));
1637 
1638   // Require the GlobalsAA analysis for the module so we can query it within
1639   // MainFPM.
1640   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
1641   // Invalidate AAManager so it can be recreated and pick up the newly available
1642   // GlobalsAA.
1643   MPM.addPass(
1644       createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>()));
1645 
1646   FunctionPassManager MainFPM;
1647   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1648       LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap,
1649                /*AllowSpeculation=*/true),
1650       /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true));
1651 
1652   if (RunNewGVN)
1653     MainFPM.addPass(NewGVNPass());
1654   else
1655     MainFPM.addPass(GVNPass());
1656 
1657   // Remove dead memcpy()'s.
1658   MainFPM.addPass(MemCpyOptPass());
1659 
1660   // Nuke dead stores.
1661   MainFPM.addPass(DSEPass());
1662   MainFPM.addPass(MergedLoadStoreMotionPass());
1663 
1664 
1665   if (EnableConstraintElimination)
1666     MainFPM.addPass(ConstraintEliminationPass());
1667 
1668   LoopPassManager LPM;
1669   if (EnableLoopFlatten && Level.getSpeedupLevel() > 1)
1670     LPM.addPass(LoopFlattenPass());
1671   LPM.addPass(IndVarSimplifyPass());
1672   LPM.addPass(LoopDeletionPass());
1673   // FIXME: Add loop interchange.
1674 
1675   // Unroll small loops and perform peeling.
1676   LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(),
1677                                  /* OnlyWhenForced= */ !PTO.LoopUnrolling,
1678                                  PTO.ForgetAllSCEVInLoopUnroll));
1679   // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA.
1680   // *All* loop passes must preserve it, in order to be able to use it.
1681   MainFPM.addPass(createFunctionToLoopPassAdaptor(
1682       std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true));
1683 
1684   MainFPM.addPass(LoopDistributePass());
1685 
1686   addVectorPasses(Level, MainFPM, /* IsFullLTO */ true);
1687 
1688   // Run the OpenMPOpt CGSCC pass again late.
1689   MPM.addPass(
1690       createModuleToPostOrderCGSCCPassAdaptor(OpenMPOptCGSCCPass()));
1691 
1692   invokePeepholeEPCallbacks(MainFPM, Level);
1693   MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true));
1694   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM),
1695                                                 PTO.EagerlyInvalidateAnalyses));
1696 
1697   // Lower type metadata and the type.test intrinsic. This pass supports
1698   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
1699   // to be run at link time if CFI is enabled. This pass does nothing if
1700   // CFI is disabled.
1701   MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr));
1702   // Run a second time to clean up any type tests left behind by WPD for use
1703   // in ICP (which is performed earlier than this in the regular LTO pipeline).
1704   MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true));
1705 
1706   // Enable splitting late in the FullLTO post-link pipeline. This is done in
1707   // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses).
1708   if (EnableHotColdSplit)
1709     MPM.addPass(HotColdSplittingPass());
1710 
1711   // Add late LTO optimization passes.
1712   // Delete basic blocks, which optimization passes may have killed.
1713   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass(
1714       SimplifyCFGOptions().convertSwitchRangeToICmp(true).hoistCommonInsts(
1715           true))));
1716 
1717   // Drop bodies of available eternally objects to improve GlobalDCE.
1718   MPM.addPass(EliminateAvailableExternallyPass());
1719 
1720   // Now that we have optimized the program, discard unreachable functions.
1721   MPM.addPass(GlobalDCEPass());
1722 
1723   if (PTO.MergeFunctions)
1724     MPM.addPass(MergeFunctionsPass());
1725 
1726   for (auto &C : FullLinkTimeOptimizationLastEPCallbacks)
1727     C(MPM, Level);
1728 
1729   // Emit annotation remarks.
1730   addAnnotationRemarksPass(MPM);
1731 
1732   return MPM;
1733 }
1734 
1735 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level,
1736                                                       bool LTOPreLink) {
1737   assert(Level == OptimizationLevel::O0 &&
1738          "buildO0DefaultPipeline should only be used with O0");
1739 
1740   ModulePassManager MPM;
1741 
1742   // Perform pseudo probe instrumentation in O0 mode. This is for the
1743   // consistency between different build modes. For example, a LTO build can be
1744   // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in
1745   // the postlink will require pseudo probe instrumentation in the prelink.
1746   if (PGOOpt && PGOOpt->PseudoProbeForProfiling)
1747     MPM.addPass(SampleProfileProbePass(TM));
1748 
1749   if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1750                  PGOOpt->Action == PGOOptions::IRUse))
1751     addPGOInstrPassesForO0(
1752         MPM,
1753         /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1754         /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile);
1755 
1756   for (auto &C : PipelineStartEPCallbacks)
1757     C(MPM, Level);
1758 
1759   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
1760     MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
1761 
1762   for (auto &C : PipelineEarlySimplificationEPCallbacks)
1763     C(MPM, Level);
1764 
1765   // Build a minimal pipeline based on the semantics required by LLVM,
1766   // which is just that always inlining occurs. Further, disable generating
1767   // lifetime intrinsics to avoid enabling further optimizations during
1768   // code generation.
1769   MPM.addPass(AlwaysInlinerPass(
1770       /*InsertLifetimeIntrinsics=*/false));
1771 
1772   if (PTO.MergeFunctions)
1773     MPM.addPass(MergeFunctionsPass());
1774 
1775   if (EnableMatrix)
1776     MPM.addPass(
1777         createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true)));
1778 
1779   if (!CGSCCOptimizerLateEPCallbacks.empty()) {
1780     CGSCCPassManager CGPM;
1781     for (auto &C : CGSCCOptimizerLateEPCallbacks)
1782       C(CGPM, Level);
1783     if (!CGPM.isEmpty())
1784       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1785   }
1786   if (!LateLoopOptimizationsEPCallbacks.empty()) {
1787     LoopPassManager LPM;
1788     for (auto &C : LateLoopOptimizationsEPCallbacks)
1789       C(LPM, Level);
1790     if (!LPM.isEmpty()) {
1791       MPM.addPass(createModuleToFunctionPassAdaptor(
1792           createFunctionToLoopPassAdaptor(std::move(LPM))));
1793     }
1794   }
1795   if (!LoopOptimizerEndEPCallbacks.empty()) {
1796     LoopPassManager LPM;
1797     for (auto &C : LoopOptimizerEndEPCallbacks)
1798       C(LPM, Level);
1799     if (!LPM.isEmpty()) {
1800       MPM.addPass(createModuleToFunctionPassAdaptor(
1801           createFunctionToLoopPassAdaptor(std::move(LPM))));
1802     }
1803   }
1804   if (!ScalarOptimizerLateEPCallbacks.empty()) {
1805     FunctionPassManager FPM;
1806     for (auto &C : ScalarOptimizerLateEPCallbacks)
1807       C(FPM, Level);
1808     if (!FPM.isEmpty())
1809       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1810   }
1811   if (!VectorizerStartEPCallbacks.empty()) {
1812     FunctionPassManager FPM;
1813     for (auto &C : VectorizerStartEPCallbacks)
1814       C(FPM, Level);
1815     if (!FPM.isEmpty())
1816       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1817   }
1818 
1819   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1820   CGSCCPassManager CGPM;
1821   CGPM.addPass(CoroSplitPass());
1822   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1823   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1824 
1825   for (auto &C : OptimizerLastEPCallbacks)
1826     C(MPM, Level);
1827 
1828   if (LTOPreLink)
1829     addRequiredLTOPreLinkPasses(MPM);
1830 
1831   MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass()));
1832 
1833   return MPM;
1834 }
1835 
1836 AAManager PassBuilder::buildDefaultAAPipeline() {
1837   AAManager AA;
1838 
1839   // The order in which these are registered determines their priority when
1840   // being queried.
1841 
1842   // First we register the basic alias analysis that provides the majority of
1843   // per-function local AA logic. This is a stateless, on-demand local set of
1844   // AA techniques.
1845   AA.registerFunctionAnalysis<BasicAA>();
1846 
1847   // Next we query fast, specialized alias analyses that wrap IR-embedded
1848   // information about aliasing.
1849   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
1850   AA.registerFunctionAnalysis<TypeBasedAA>();
1851 
1852   // Add support for querying global aliasing information when available.
1853   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
1854   // analysis, all that the `AAManager` can do is query for any *cached*
1855   // results from `GlobalsAA` through a readonly proxy.
1856   AA.registerModuleAnalysis<GlobalsAA>();
1857 
1858   // Add target-specific alias analyses.
1859   if (TM)
1860     TM->registerDefaultAliasAnalyses(AA);
1861 
1862   return AA;
1863 }
1864