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