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