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