1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the PassManagerBuilder class, which is used to set up a
11 // "standard" optimization sequence suitable for languages like C and C++.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
16 #include "llvm-c/Transforms/PassManagerBuilder.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/ModuleSummaryIndex.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Transforms/IPO.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/Instrumentation.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Transforms/Scalar/GVN.h"
41 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
42 #include "llvm/Transforms/Vectorize.h"
43 
44 using namespace llvm;
45 
46 static cl::opt<bool>
47     RunPartialInlining("enable-partial-inlining", cl::init(false), cl::Hidden,
48                        cl::ZeroOrMore, cl::desc("Run Partial inlinining pass"));
49 
50 static cl::opt<bool>
51     RunLoopVectorization("vectorize-loops", cl::Hidden,
52                          cl::desc("Run the Loop vectorization passes"));
53 
54 static cl::opt<bool>
55 RunSLPVectorization("vectorize-slp", cl::Hidden,
56                     cl::desc("Run the SLP vectorization passes"));
57 
58 static cl::opt<bool>
59 RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
60                     cl::desc("Run the BB vectorization passes"));
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 static 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 static cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden,
76                                cl::desc("Run the NewGVN pass"));
77 
78 static cl::opt<bool>
79 RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
80   cl::init(true), cl::Hidden,
81   cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
82            "vectorizer instead of before"));
83 
84 // Experimental option to use CFL-AA
85 enum class CFLAAType { None, Steensgaard, Andersen, Both };
86 static cl::opt<CFLAAType>
87     UseCFLAA("use-cfl-aa", cl::init(CFLAAType::None), cl::Hidden,
88              cl::desc("Enable the new, experimental CFL alias analysis"),
89              cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
90                         clEnumValN(CFLAAType::Steensgaard, "steens",
91                                    "Enable unification-based CFL-AA"),
92                         clEnumValN(CFLAAType::Andersen, "anders",
93                                    "Enable inclusion-based CFL-AA"),
94                         clEnumValN(CFLAAType::Both, "both",
95                                    "Enable both variants of CFL-AA")));
96 
97 static cl::opt<bool> EnableLoopInterchange(
98     "enable-loopinterchange", cl::init(false), cl::Hidden,
99     cl::desc("Enable the new, experimental LoopInterchange Pass"));
100 
101 static cl::opt<bool> EnableNonLTOGlobalsModRef(
102     "enable-non-lto-gmr", cl::init(true), cl::Hidden,
103     cl::desc(
104         "Enable the GlobalsModRef AliasAnalysis outside of the LTO pipeline."));
105 
106 static cl::opt<bool> EnableLoopLoadElim(
107     "enable-loop-load-elim", cl::init(true), cl::Hidden,
108     cl::desc("Enable the LoopLoadElimination Pass"));
109 
110 static cl::opt<bool>
111     EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden,
112                             cl::desc("Enable preparation for ThinLTO."));
113 
114 static cl::opt<bool> RunPGOInstrGen(
115     "profile-generate", cl::init(false), cl::Hidden,
116     cl::desc("Enable PGO instrumentation."));
117 
118 static cl::opt<std::string>
119     PGOOutputFile("profile-generate-file", cl::init(""), cl::Hidden,
120                       cl::desc("Specify the path of profile data file."));
121 
122 static cl::opt<std::string> RunPGOInstrUse(
123     "profile-use", cl::init(""), cl::Hidden, cl::value_desc("filename"),
124     cl::desc("Enable use phase of PGO instrumentation and specify the path "
125              "of profile data file"));
126 
127 static cl::opt<bool> UseLoopVersioningLICM(
128     "enable-loop-versioning-licm", cl::init(false), cl::Hidden,
129     cl::desc("Enable the experimental Loop Versioning LICM pass"));
130 
131 static cl::opt<bool>
132     DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden,
133                       cl::desc("Disable pre-instrumentation inliner"));
134 
135 static cl::opt<int> PreInlineThreshold(
136     "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore,
137     cl::desc("Control the amount of inlining in pre-instrumentation inliner "
138              "(default = 75)"));
139 
140 static cl::opt<bool> EnableEarlyCSEMemSSA(
141     "enable-earlycse-memssa", cl::init(false), cl::Hidden,
142     cl::desc("Enable the EarlyCSE w/ MemorySSA pass (default = off)"));
143 
144 static cl::opt<bool> EnableGVNHoist(
145     "enable-gvn-hoist", cl::init(false), cl::Hidden,
146     cl::desc("Enable the GVN hoisting pass (default = off)"));
147 
148 static cl::opt<bool>
149     DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false),
150                               cl::Hidden,
151                               cl::desc("Disable shrink-wrap library calls"));
152 
153 static cl::opt<bool>
154     EnableSimpleLoopUnswitch("enable-simple-loop-unswitch", cl::init(false),
155                              cl::Hidden,
156                              cl::desc("Enable the simple loop unswitch pass."));
157 
158 static cl::opt<bool> EnableGVNSink(
159     "enable-gvn-sink", cl::init(false), cl::Hidden,
160     cl::desc("Enable the GVN sinking pass (default = off)"));
161 
162 PassManagerBuilder::PassManagerBuilder() {
163     OptLevel = 2;
164     SizeLevel = 0;
165     LibraryInfo = nullptr;
166     Inliner = nullptr;
167     DisableUnitAtATime = false;
168     DisableUnrollLoops = false;
169     BBVectorize = RunBBVectorization;
170     SLPVectorize = RunSLPVectorization;
171     LoopVectorize = RunLoopVectorization;
172     RerollLoops = RunLoopRerolling;
173     NewGVN = RunNewGVN;
174     DisableGVNLoadPRE = false;
175     VerifyInput = false;
176     VerifyOutput = false;
177     MergeFunctions = false;
178     PrepareForLTO = false;
179     EnablePGOInstrGen = RunPGOInstrGen;
180     PGOInstrGen = PGOOutputFile;
181     PGOInstrUse = RunPGOInstrUse;
182     PrepareForThinLTO = EnablePrepareForThinLTO;
183     PerformThinLTO = false;
184     DivergentTarget = false;
185 }
186 
187 PassManagerBuilder::~PassManagerBuilder() {
188   delete LibraryInfo;
189   delete Inliner;
190 }
191 
192 /// Set of global extensions, automatically added as part of the standard set.
193 static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
194    PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
195 
196 void PassManagerBuilder::addGlobalExtension(
197     PassManagerBuilder::ExtensionPointTy Ty,
198     PassManagerBuilder::ExtensionFn Fn) {
199   GlobalExtensions->push_back(std::make_pair(Ty, std::move(Fn)));
200 }
201 
202 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
203   Extensions.push_back(std::make_pair(Ty, std::move(Fn)));
204 }
205 
206 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
207                                            legacy::PassManagerBase &PM) const {
208   for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
209     if ((*GlobalExtensions)[i].first == ETy)
210       (*GlobalExtensions)[i].second(*this, PM);
211   for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
212     if (Extensions[i].first == ETy)
213       Extensions[i].second(*this, PM);
214 }
215 
216 void PassManagerBuilder::addInitialAliasAnalysisPasses(
217     legacy::PassManagerBase &PM) const {
218   switch (UseCFLAA) {
219   case CFLAAType::Steensgaard:
220     PM.add(createCFLSteensAAWrapperPass());
221     break;
222   case CFLAAType::Andersen:
223     PM.add(createCFLAndersAAWrapperPass());
224     break;
225   case CFLAAType::Both:
226     PM.add(createCFLSteensAAWrapperPass());
227     PM.add(createCFLAndersAAWrapperPass());
228     break;
229   default:
230     break;
231   }
232 
233   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
234   // BasicAliasAnalysis wins if they disagree. This is intended to help
235   // support "obvious" type-punning idioms.
236   PM.add(createTypeBasedAAWrapperPass());
237   PM.add(createScopedNoAliasAAWrapperPass());
238 }
239 
240 void PassManagerBuilder::addInstructionCombiningPass(
241     legacy::PassManagerBase &PM) const {
242   bool ExpensiveCombines = OptLevel > 2;
243   PM.add(createInstructionCombiningPass(ExpensiveCombines));
244 }
245 
246 void PassManagerBuilder::populateFunctionPassManager(
247     legacy::FunctionPassManager &FPM) {
248   addExtensionsToPM(EP_EarlyAsPossible, FPM);
249 
250   // Add LibraryInfo if we have some.
251   if (LibraryInfo)
252     FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
253 
254   if (OptLevel == 0) return;
255 
256   addInitialAliasAnalysisPasses(FPM);
257 
258   FPM.add(createCFGSimplificationPass());
259   FPM.add(createSROAPass());
260   FPM.add(createEarlyCSEPass());
261   FPM.add(createLowerExpectIntrinsicPass());
262 }
263 
264 // Do PGO instrumentation generation or use pass as the option specified.
265 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM) {
266   if (!EnablePGOInstrGen && PGOInstrUse.empty())
267     return;
268   // Perform the preinline and cleanup passes for O1 and above.
269   // And avoid doing them if optimizing for size.
270   if (OptLevel > 0 && SizeLevel == 0 && !DisablePreInliner) {
271     // Create preinline pass. We construct an InlineParams object and specify
272     // the threshold here to avoid the command line options of the regular
273     // inliner to influence pre-inlining. The only fields of InlineParams we
274     // care about are DefaultThreshold and HintThreshold.
275     InlineParams IP;
276     IP.DefaultThreshold = PreInlineThreshold;
277     // FIXME: The hint threshold has the same value used by the regular inliner.
278     // This should probably be lowered after performance testing.
279     IP.HintThreshold = 325;
280 
281     MPM.add(createFunctionInliningPass(IP));
282     MPM.add(createSROAPass());
283     MPM.add(createEarlyCSEPass());             // Catch trivial redundancies
284     MPM.add(createCFGSimplificationPass());    // Merge & remove BBs
285     MPM.add(createInstructionCombiningPass()); // Combine silly seq's
286     addExtensionsToPM(EP_Peephole, MPM);
287   }
288   if (EnablePGOInstrGen) {
289     MPM.add(createPGOInstrumentationGenLegacyPass());
290     // Add the profile lowering pass.
291     InstrProfOptions Options;
292     if (!PGOInstrGen.empty())
293       Options.InstrProfileOutput = PGOInstrGen;
294     Options.DoCounterPromotion = true;
295     MPM.add(createLoopRotatePass());
296     MPM.add(createInstrProfilingLegacyPass(Options));
297   }
298   if (!PGOInstrUse.empty())
299     MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse));
300   // Indirect call promotion that promotes intra-module targets only.
301   // For ThinLTO this is done earlier due to interactions with globalopt
302   // for imported functions. We don't run this at -O0.
303   if (OptLevel > 0)
304     MPM.add(
305         createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty()));
306 }
307 void PassManagerBuilder::addFunctionSimplificationPasses(
308     legacy::PassManagerBase &MPM) {
309   // Start of function pass.
310   // Break up aggregate allocas, using SSAUpdater.
311   MPM.add(createSROAPass());
312   MPM.add(createEarlyCSEPass(EnableEarlyCSEMemSSA)); // Catch trivial redundancies
313   if (EnableGVNHoist)
314     MPM.add(createGVNHoistPass());
315   if (EnableGVNSink) {
316     MPM.add(createGVNSinkPass());
317     MPM.add(createCFGSimplificationPass());
318   }
319 
320   // Speculative execution if the target has divergent branches; otherwise nop.
321   MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass());
322   MPM.add(createJumpThreadingPass());         // Thread jumps.
323   MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
324   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
325   // Combine silly seq's
326   addInstructionCombiningPass(MPM);
327   if (SizeLevel == 0 && !DisableLibCallsShrinkWrap)
328     MPM.add(createLibCallsShrinkWrapPass());
329   addExtensionsToPM(EP_Peephole, MPM);
330 
331   // Optimize memory intrinsic calls based on the profiled size information.
332   if (SizeLevel == 0)
333     MPM.add(createPGOMemOPSizeOptLegacyPass());
334 
335   MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
336   MPM.add(createCFGSimplificationPass());     // Merge & remove BBs
337   MPM.add(createReassociatePass());           // Reassociate expressions
338   // Rotate Loop - disable header duplication at -Oz
339   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
340   MPM.add(createLICMPass());                  // Hoist loop invariants
341   if (EnableSimpleLoopUnswitch)
342     MPM.add(createSimpleLoopUnswitchLegacyPass());
343   else
344     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
345   MPM.add(createCFGSimplificationPass());
346   addInstructionCombiningPass(MPM);
347   MPM.add(createIndVarSimplifyPass());        // Canonicalize indvars
348   MPM.add(createLoopIdiomPass());             // Recognize idioms like memset.
349   addExtensionsToPM(EP_LateLoopOptimizations, MPM);
350   MPM.add(createLoopDeletionPass());          // Delete dead loops
351 
352   if (EnableLoopInterchange) {
353     MPM.add(createLoopInterchangePass()); // Interchange loops
354     MPM.add(createCFGSimplificationPass());
355   }
356   if (!DisableUnrollLoops)
357     MPM.add(createSimpleLoopUnrollPass(OptLevel));    // Unroll small loops
358   addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
359 
360   if (OptLevel > 1) {
361     MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
362     MPM.add(NewGVN ? createNewGVNPass()
363                    : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
364   }
365   MPM.add(createMemCpyOptPass());             // Remove memcpy / form memset
366   MPM.add(createSCCPPass());                  // Constant prop with SCCP
367 
368   // Delete dead bit computations (instcombine runs after to fold away the dead
369   // computations, and then ADCE will run later to exploit any new DCE
370   // opportunities that creates).
371   MPM.add(createBitTrackingDCEPass());        // Delete dead bit computations
372 
373   // Run instcombine after redundancy elimination to exploit opportunities
374   // opened up by them.
375   addInstructionCombiningPass(MPM);
376   addExtensionsToPM(EP_Peephole, MPM);
377   MPM.add(createJumpThreadingPass());         // Thread jumps
378   MPM.add(createCorrelatedValuePropagationPass());
379   MPM.add(createDeadStoreEliminationPass());  // Delete dead stores
380   MPM.add(createLICMPass());
381 
382   addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
383 
384   if (RerollLoops)
385     MPM.add(createLoopRerollPass());
386   if (!RunSLPAfterLoopVectorization) {
387     if (SLPVectorize)
388       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
389 
390     if (BBVectorize) {
391       MPM.add(createBBVectorizePass());
392       addInstructionCombiningPass(MPM);
393       addExtensionsToPM(EP_Peephole, MPM);
394       if (OptLevel > 1 && UseGVNAfterVectorization)
395         MPM.add(NewGVN
396                     ? createNewGVNPass()
397                     : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
398       else
399         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
400 
401       // BBVectorize may have significantly shortened a loop body; unroll again.
402       if (!DisableUnrollLoops)
403         MPM.add(createLoopUnrollPass(OptLevel));
404     }
405   }
406 
407   MPM.add(createAggressiveDCEPass());         // Delete dead instructions
408   MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
409   // Clean up after everything.
410   addInstructionCombiningPass(MPM);
411   addExtensionsToPM(EP_Peephole, MPM);
412 }
413 
414 void PassManagerBuilder::populateModulePassManager(
415     legacy::PassManagerBase &MPM) {
416   if (!PGOSampleUse.empty()) {
417     MPM.add(createPruneEHPass());
418     MPM.add(createSampleProfileLoaderPass(PGOSampleUse));
419   }
420 
421   // Allow forcing function attributes as a debugging and tuning aid.
422   MPM.add(createForceFunctionAttrsLegacyPass());
423 
424   // If all optimizations are disabled, just run the always-inline pass and,
425   // if enabled, the function merging pass.
426   if (OptLevel == 0) {
427     addPGOInstrPasses(MPM);
428     if (Inliner) {
429       MPM.add(Inliner);
430       Inliner = nullptr;
431     }
432 
433     // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
434     // creates a CGSCC pass manager, but we don't want to add extensions into
435     // that pass manager. To prevent this we insert a no-op module pass to reset
436     // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
437     // builds. The function merging pass is
438     if (MergeFunctions)
439       MPM.add(createMergeFunctionsPass());
440     else if (!GlobalExtensions->empty() || !Extensions.empty())
441       MPM.add(createBarrierNoopPass());
442 
443     addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
444 
445     // Rename anon globals to be able to export them in the summary.
446     // This has to be done after we add the extensions to the pass manager
447     // as there could be passes (e.g. Adddress sanitizer) which introduce
448     // new unnamed globals.
449     if (PrepareForThinLTO)
450       MPM.add(createNameAnonGlobalPass());
451     return;
452   }
453 
454   // Add LibraryInfo if we have some.
455   if (LibraryInfo)
456     MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
457 
458   addInitialAliasAnalysisPasses(MPM);
459 
460   // For ThinLTO there are two passes of indirect call promotion. The
461   // first is during the compile phase when PerformThinLTO=false and
462   // intra-module indirect call targets are promoted. The second is during
463   // the ThinLTO backend when PerformThinLTO=true, when we promote imported
464   // inter-module indirect calls. For that we perform indirect call promotion
465   // earlier in the pass pipeline, here before globalopt. Otherwise imported
466   // available_externally functions look unreferenced and are removed.
467   if (PerformThinLTO)
468     MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true,
469                                                      !PGOSampleUse.empty()));
470 
471   // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops
472   // as it will change the CFG too much to make the 2nd profile annotation
473   // in backend more difficult.
474   bool PrepareForThinLTOUsingPGOSampleProfile =
475       PrepareForThinLTO && !PGOSampleUse.empty();
476   if (PrepareForThinLTOUsingPGOSampleProfile)
477     DisableUnrollLoops = true;
478 
479   if (!DisableUnitAtATime) {
480     // Infer attributes about declarations if possible.
481     MPM.add(createInferFunctionAttrsLegacyPass());
482 
483     addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
484 
485     MPM.add(createIPSCCPPass());          // IP SCCP
486     MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
487     // Promote any localized global vars.
488     MPM.add(createPromoteMemoryToRegisterPass());
489 
490     MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
491 
492     addInstructionCombiningPass(MPM); // Clean up after IPCP & DAE
493     addExtensionsToPM(EP_Peephole, MPM);
494     MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
495   }
496 
497   // For SamplePGO in ThinLTO compile phase, we do not want to do indirect
498   // call promotion as it will change the CFG too much to make the 2nd
499   // profile annotation in backend more difficult.
500   // PGO instrumentation is added during the compile phase for ThinLTO, do
501   // not run it a second time
502   if (!PerformThinLTO && !PrepareForThinLTOUsingPGOSampleProfile)
503     addPGOInstrPasses(MPM);
504 
505   if (EnableNonLTOGlobalsModRef)
506     // We add a module alias analysis pass here. In part due to bugs in the
507     // analysis infrastructure this "works" in that the analysis stays alive
508     // for the entire SCC pass run below.
509     MPM.add(createGlobalsAAWrapperPass());
510 
511   // Start of CallGraph SCC passes.
512   if (!DisableUnitAtATime)
513     MPM.add(createPruneEHPass()); // Remove dead EH info
514   if (Inliner) {
515     MPM.add(Inliner);
516     Inliner = nullptr;
517   }
518   if (!DisableUnitAtATime)
519     MPM.add(createPostOrderFunctionAttrsLegacyPass());
520   if (OptLevel > 2)
521     MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
522 
523   addExtensionsToPM(EP_CGSCCOptimizerLate, MPM);
524   addFunctionSimplificationPasses(MPM);
525 
526   // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
527   // pass manager that we are specifically trying to avoid. To prevent this
528   // we must insert a no-op module pass to reset the pass manager.
529   MPM.add(createBarrierNoopPass());
530   if (RunPartialInlining)
531     MPM.add(createPartialInliningPass());
532 
533   if (!DisableUnitAtATime && OptLevel > 1 && !PrepareForLTO &&
534       !PrepareForThinLTO)
535     // Remove avail extern fns and globals definitions if we aren't
536     // compiling an object file for later LTO. For LTO we want to preserve
537     // these so they are eligible for inlining at link-time. Note if they
538     // are unreferenced they will be removed by GlobalDCE later, so
539     // this only impacts referenced available externally globals.
540     // Eventually they will be suppressed during codegen, but eliminating
541     // here enables more opportunity for GlobalDCE as it may make
542     // globals referenced by available external functions dead
543     // and saves running remaining passes on the eliminated functions.
544     MPM.add(createEliminateAvailableExternallyPass());
545 
546   if (!DisableUnitAtATime)
547     MPM.add(createReversePostOrderFunctionAttrsPass());
548 
549   // If we are planning to perform ThinLTO later, let's not bloat the code with
550   // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes
551   // during ThinLTO and perform the rest of the optimizations afterward.
552   if (PrepareForThinLTO) {
553     // Reduce the size of the IR as much as possible.
554     MPM.add(createGlobalOptimizerPass());
555     // Rename anon globals to be able to export them in the summary.
556     MPM.add(createNameAnonGlobalPass());
557     return;
558   }
559 
560   if (PerformThinLTO)
561     // Optimize globals now when performing ThinLTO, this enables more
562     // optimizations later.
563     MPM.add(createGlobalOptimizerPass());
564 
565   // Scheduling LoopVersioningLICM when inlining is over, because after that
566   // we may see more accurate aliasing. Reason to run this late is that too
567   // early versioning may prevent further inlining due to increase of code
568   // size. By placing it just after inlining other optimizations which runs
569   // later might get benefit of no-alias assumption in clone loop.
570   if (UseLoopVersioningLICM) {
571     MPM.add(createLoopVersioningLICMPass());    // Do LoopVersioningLICM
572     MPM.add(createLICMPass());                  // Hoist loop invariants
573   }
574 
575   if (EnableNonLTOGlobalsModRef)
576     // We add a fresh GlobalsModRef run at this point. This is particularly
577     // useful as the above will have inlined, DCE'ed, and function-attr
578     // propagated everything. We should at this point have a reasonably minimal
579     // and richly annotated call graph. By computing aliasing and mod/ref
580     // information for all local globals here, the late loop passes and notably
581     // the vectorizer will be able to use them to help recognize vectorizable
582     // memory operations.
583     //
584     // Note that this relies on a bug in the pass manager which preserves
585     // a module analysis into a function pass pipeline (and throughout it) so
586     // long as the first function pass doesn't invalidate the module analysis.
587     // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for
588     // this to work. Fortunately, it is trivial to preserve AliasAnalysis
589     // (doing nothing preserves it as it is required to be conservatively
590     // correct in the face of IR changes).
591     MPM.add(createGlobalsAAWrapperPass());
592 
593   MPM.add(createFloat2IntPass());
594 
595   addExtensionsToPM(EP_VectorizerStart, MPM);
596 
597   // Re-rotate loops in all our loop nests. These may have fallout out of
598   // rotated form due to GVN or other transformations, and the vectorizer relies
599   // on the rotated form. Disable header duplication at -Oz.
600   MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
601 
602   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
603   // into separate loop that would otherwise inhibit vectorization.  This is
604   // currently only performed for loops marked with the metadata
605   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
606   MPM.add(createLoopDistributePass());
607 
608   MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
609 
610   // Eliminate loads by forwarding stores from the previous iteration to loads
611   // of the current iteration.
612   if (EnableLoopLoadElim)
613     MPM.add(createLoopLoadEliminationPass());
614 
615   // FIXME: Because of #pragma vectorize enable, the passes below are always
616   // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
617   // on -O1 and no #pragma is found). Would be good to have these two passes
618   // as function calls, so that we can only pass them when the vectorizer
619   // changed the code.
620   addInstructionCombiningPass(MPM);
621   if (OptLevel > 1 && ExtraVectorizerPasses) {
622     // At higher optimization levels, try to clean up any runtime overlap and
623     // alignment checks inserted by the vectorizer. We want to track correllated
624     // runtime checks for two inner loops in the same outer loop, fold any
625     // common computations, hoist loop-invariant aspects out of any outer loop,
626     // and unswitch the runtime checks if possible. Once hoisted, we may have
627     // dead (or speculatable) control flows or more combining opportunities.
628     MPM.add(createEarlyCSEPass());
629     MPM.add(createCorrelatedValuePropagationPass());
630     addInstructionCombiningPass(MPM);
631     MPM.add(createLICMPass());
632     MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget));
633     MPM.add(createCFGSimplificationPass());
634     addInstructionCombiningPass(MPM);
635   }
636 
637   if (RunSLPAfterLoopVectorization) {
638     if (SLPVectorize) {
639       MPM.add(createSLPVectorizerPass());   // Vectorize parallel scalar chains.
640       if (OptLevel > 1 && ExtraVectorizerPasses) {
641         MPM.add(createEarlyCSEPass());
642       }
643     }
644 
645     if (BBVectorize) {
646       MPM.add(createBBVectorizePass());
647       addInstructionCombiningPass(MPM);
648       addExtensionsToPM(EP_Peephole, MPM);
649       if (OptLevel > 1 && UseGVNAfterVectorization)
650         MPM.add(NewGVN
651                     ? createNewGVNPass()
652                     : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
653       else
654         MPM.add(createEarlyCSEPass());      // Catch trivial redundancies
655 
656       // BBVectorize may have significantly shortened a loop body; unroll again.
657       if (!DisableUnrollLoops)
658         MPM.add(createLoopUnrollPass(OptLevel));
659     }
660   }
661 
662   addExtensionsToPM(EP_Peephole, MPM);
663   MPM.add(createLateCFGSimplificationPass()); // Switches to lookup tables
664   addInstructionCombiningPass(MPM);
665 
666   if (!DisableUnrollLoops) {
667     MPM.add(createLoopUnrollPass(OptLevel));    // Unroll small loops
668 
669     // LoopUnroll may generate some redundency to cleanup.
670     addInstructionCombiningPass(MPM);
671 
672     // Runtime unrolling will introduce runtime check in loop prologue. If the
673     // unrolled loop is a inner loop, then the prologue will be inside the
674     // outer loop. LICM pass can help to promote the runtime check out if the
675     // checked value is loop invariant.
676     MPM.add(createLICMPass());
677  }
678 
679   // After vectorization and unrolling, assume intrinsics may tell us more
680   // about pointer alignments.
681   MPM.add(createAlignmentFromAssumptionsPass());
682 
683   if (!DisableUnitAtATime) {
684     // FIXME: We shouldn't bother with this anymore.
685     MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
686 
687     // GlobalOpt already deletes dead functions and globals, at -O2 try a
688     // late pass of GlobalDCE.  It is capable of deleting dead cycles.
689     if (OptLevel > 1) {
690       MPM.add(createGlobalDCEPass());         // Remove dead fns and globals.
691       MPM.add(createConstantMergePass());     // Merge dup global constants
692     }
693   }
694 
695   if (MergeFunctions)
696     MPM.add(createMergeFunctionsPass());
697 
698   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
699   // canonicalization pass that enables other optimizations. As a result,
700   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
701   // result too early.
702   MPM.add(createLoopSinkPass());
703   // Get rid of LCSSA nodes.
704   MPM.add(createInstructionSimplifierPass());
705 
706   // LoopSink (and other loop passes since the last simplifyCFG) might have
707   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
708   MPM.add(createCFGSimplificationPass());
709 
710   addExtensionsToPM(EP_OptimizerLast, MPM);
711 }
712 
713 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
714   // Remove unused virtual tables to improve the quality of code generated by
715   // whole-program devirtualization and bitset lowering.
716   PM.add(createGlobalDCEPass());
717 
718   // Provide AliasAnalysis services for optimizations.
719   addInitialAliasAnalysisPasses(PM);
720 
721   // Allow forcing function attributes as a debugging and tuning aid.
722   PM.add(createForceFunctionAttrsLegacyPass());
723 
724   // Infer attributes about declarations if possible.
725   PM.add(createInferFunctionAttrsLegacyPass());
726 
727   if (OptLevel > 1) {
728     // Indirect call promotion. This should promote all the targets that are
729     // left by the earlier promotion pass that promotes intra-module targets.
730     // This two-step promotion is to save the compile time. For LTO, it should
731     // produce the same result as if we only do promotion here.
732     PM.add(
733         createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty()));
734 
735     // Propagate constants at call sites into the functions they call.  This
736     // opens opportunities for globalopt (and inlining) by substituting function
737     // pointers passed as arguments to direct uses of functions.
738     PM.add(createIPSCCPPass());
739   }
740 
741   // Infer attributes about definitions. The readnone attribute in particular is
742   // required for virtual constant propagation.
743   PM.add(createPostOrderFunctionAttrsLegacyPass());
744   PM.add(createReversePostOrderFunctionAttrsPass());
745 
746   // Split globals using inrange annotations on GEP indices. This can help
747   // improve the quality of generated code when virtual constant propagation or
748   // control flow integrity are enabled.
749   PM.add(createGlobalSplitPass());
750 
751   // Apply whole-program devirtualization and virtual constant propagation.
752   PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
753 
754   // That's all we need at opt level 1.
755   if (OptLevel == 1)
756     return;
757 
758   // Now that we internalized some globals, see if we can hack on them!
759   PM.add(createGlobalOptimizerPass());
760   // Promote any localized global vars.
761   PM.add(createPromoteMemoryToRegisterPass());
762 
763   // Linking modules together can lead to duplicated global constants, only
764   // keep one copy of each constant.
765   PM.add(createConstantMergePass());
766 
767   // Remove unused arguments from functions.
768   PM.add(createDeadArgEliminationPass());
769 
770   // Reduce the code after globalopt and ipsccp.  Both can open up significant
771   // simplification opportunities, and both can propagate functions through
772   // function pointers.  When this happens, we often have to resolve varargs
773   // calls, etc, so let instcombine do this.
774   addInstructionCombiningPass(PM);
775   addExtensionsToPM(EP_Peephole, PM);
776 
777   // Inline small functions
778   bool RunInliner = Inliner;
779   if (RunInliner) {
780     PM.add(Inliner);
781     Inliner = nullptr;
782   }
783 
784   PM.add(createPruneEHPass());   // Remove dead EH info.
785 
786   // Optimize globals again if we ran the inliner.
787   if (RunInliner)
788     PM.add(createGlobalOptimizerPass());
789   PM.add(createGlobalDCEPass()); // Remove dead functions.
790 
791   // If we didn't decide to inline a function, check to see if we can
792   // transform it to pass arguments by value instead of by reference.
793   PM.add(createArgumentPromotionPass());
794 
795   // The IPO passes may leave cruft around.  Clean up after them.
796   addInstructionCombiningPass(PM);
797   addExtensionsToPM(EP_Peephole, PM);
798   PM.add(createJumpThreadingPass());
799 
800   // Break up allocas
801   PM.add(createSROAPass());
802 
803   // Run a few AA driven optimizations here and now, to cleanup the code.
804   PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture.
805   PM.add(createGlobalsAAWrapperPass()); // IP alias analysis.
806 
807   PM.add(createLICMPass());                 // Hoist loop invariants.
808   PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
809   PM.add(NewGVN ? createNewGVNPass()
810                 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
811   PM.add(createMemCpyOptPass());            // Remove dead memcpys.
812 
813   // Nuke dead stores.
814   PM.add(createDeadStoreEliminationPass());
815 
816   // More loops are countable; try to optimize them.
817   PM.add(createIndVarSimplifyPass());
818   PM.add(createLoopDeletionPass());
819   if (EnableLoopInterchange)
820     PM.add(createLoopInterchangePass());
821 
822   if (!DisableUnrollLoops)
823     PM.add(createSimpleLoopUnrollPass(OptLevel));   // Unroll small loops
824   PM.add(createLoopVectorizePass(true, LoopVectorize));
825   // The vectorizer may have significantly shortened a loop body; unroll again.
826   if (!DisableUnrollLoops)
827     PM.add(createLoopUnrollPass(OptLevel));
828 
829   // Now that we've optimized loops (in particular loop induction variables),
830   // we may have exposed more scalar opportunities. Run parts of the scalar
831   // optimizer again at this point.
832   addInstructionCombiningPass(PM); // Initial cleanup
833   PM.add(createCFGSimplificationPass()); // if-convert
834   PM.add(createSCCPPass()); // Propagate exposed constants
835   addInstructionCombiningPass(PM); // Clean up again
836   PM.add(createBitTrackingDCEPass());
837 
838   // More scalar chains could be vectorized due to more alias information
839   if (RunSLPAfterLoopVectorization)
840     if (SLPVectorize)
841       PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
842 
843   // After vectorization, assume intrinsics may tell us more about pointer
844   // alignments.
845   PM.add(createAlignmentFromAssumptionsPass());
846 
847   // Cleanup and simplify the code after the scalar optimizations.
848   addInstructionCombiningPass(PM);
849   addExtensionsToPM(EP_Peephole, PM);
850 
851   PM.add(createJumpThreadingPass());
852 }
853 
854 void PassManagerBuilder::addLateLTOOptimizationPasses(
855     legacy::PassManagerBase &PM) {
856   // Delete basic blocks, which optimization passes may have killed.
857   PM.add(createCFGSimplificationPass());
858 
859   // Drop bodies of available externally objects to improve GlobalDCE.
860   PM.add(createEliminateAvailableExternallyPass());
861 
862   // Now that we have optimized the program, discard unreachable functions.
863   PM.add(createGlobalDCEPass());
864 
865   // FIXME: this is profitable (for compiler time) to do at -O0 too, but
866   // currently it damages debug info.
867   if (MergeFunctions)
868     PM.add(createMergeFunctionsPass());
869 }
870 
871 void PassManagerBuilder::populateThinLTOPassManager(
872     legacy::PassManagerBase &PM) {
873   PerformThinLTO = true;
874 
875   if (VerifyInput)
876     PM.add(createVerifierPass());
877 
878   if (ImportSummary) {
879     // These passes import type identifier resolutions for whole-program
880     // devirtualization and CFI. They must run early because other passes may
881     // disturb the specific instruction patterns that these passes look for,
882     // creating dependencies on resolutions that may not appear in the summary.
883     //
884     // For example, GVN may transform the pattern assume(type.test) appearing in
885     // two basic blocks into assume(phi(type.test, type.test)), which would
886     // transform a dependency on a WPD resolution into a dependency on a type
887     // identifier resolution for CFI.
888     //
889     // Also, WPD has access to more precise information than ICP and can
890     // devirtualize more effectively, so it should operate on the IR first.
891     PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary));
892     PM.add(createLowerTypeTestsPass(nullptr, ImportSummary));
893   }
894 
895   populateModulePassManager(PM);
896 
897   if (VerifyOutput)
898     PM.add(createVerifierPass());
899   PerformThinLTO = false;
900 }
901 
902 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
903   if (LibraryInfo)
904     PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
905 
906   if (VerifyInput)
907     PM.add(createVerifierPass());
908 
909   if (OptLevel != 0)
910     addLTOOptimizationPasses(PM);
911   else {
912     // The whole-program-devirt pass needs to run at -O0 because only it knows
913     // about the llvm.type.checked.load intrinsic: it needs to both lower the
914     // intrinsic itself and handle it in the summary.
915     PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr));
916   }
917 
918   // Create a function that performs CFI checks for cross-DSO calls with targets
919   // in the current module.
920   PM.add(createCrossDSOCFIPass());
921 
922   // Lower type metadata and the type.test intrinsic. This pass supports Clang's
923   // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at
924   // link time if CFI is enabled. The pass does nothing if CFI is disabled.
925   PM.add(createLowerTypeTestsPass(ExportSummary, nullptr));
926 
927   if (OptLevel != 0)
928     addLateLTOOptimizationPasses(PM);
929 
930   if (VerifyOutput)
931     PM.add(createVerifierPass());
932 }
933 
934 inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
935     return reinterpret_cast<PassManagerBuilder*>(P);
936 }
937 
938 inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
939   return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
940 }
941 
942 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
943   PassManagerBuilder *PMB = new PassManagerBuilder();
944   return wrap(PMB);
945 }
946 
947 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
948   PassManagerBuilder *Builder = unwrap(PMB);
949   delete Builder;
950 }
951 
952 void
953 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
954                                   unsigned OptLevel) {
955   PassManagerBuilder *Builder = unwrap(PMB);
956   Builder->OptLevel = OptLevel;
957 }
958 
959 void
960 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
961                                    unsigned SizeLevel) {
962   PassManagerBuilder *Builder = unwrap(PMB);
963   Builder->SizeLevel = SizeLevel;
964 }
965 
966 void
967 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
968                                             LLVMBool Value) {
969   PassManagerBuilder *Builder = unwrap(PMB);
970   Builder->DisableUnitAtATime = Value;
971 }
972 
973 void
974 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
975                                             LLVMBool Value) {
976   PassManagerBuilder *Builder = unwrap(PMB);
977   Builder->DisableUnrollLoops = Value;
978 }
979 
980 void
981 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
982                                                  LLVMBool Value) {
983   // NOTE: The simplify-libcalls pass has been removed.
984 }
985 
986 void
987 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
988                                               unsigned Threshold) {
989   PassManagerBuilder *Builder = unwrap(PMB);
990   Builder->Inliner = createFunctionInliningPass(Threshold);
991 }
992 
993 void
994 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
995                                                   LLVMPassManagerRef PM) {
996   PassManagerBuilder *Builder = unwrap(PMB);
997   legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
998   Builder->populateFunctionPassManager(*FPM);
999 }
1000 
1001 void
1002 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
1003                                                 LLVMPassManagerRef PM) {
1004   PassManagerBuilder *Builder = unwrap(PMB);
1005   legacy::PassManagerBase *MPM = unwrap(PM);
1006   Builder->populateModulePassManager(*MPM);
1007 }
1008 
1009 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
1010                                                   LLVMPassManagerRef PM,
1011                                                   LLVMBool Internalize,
1012                                                   LLVMBool RunInliner) {
1013   PassManagerBuilder *Builder = unwrap(PMB);
1014   legacy::PassManagerBase *LPM = unwrap(PM);
1015 
1016   // A small backwards compatibility hack. populateLTOPassManager used to take
1017   // an RunInliner option.
1018   if (RunInliner && !Builder->Inliner)
1019     Builder->Inliner = createFunctionInliningPass();
1020 
1021   Builder->populateLTOPassManager(*LPM);
1022 }
1023