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