xref: /netbsd-src/external/apache2/llvm/dist/llvm/include/llvm/CodeGen/CodeGenPassBuilder.h (revision 82d56013d7b633d116a93943de88e08335357a7c)
1 //===- Construction of codegen pass pipelines ------------------*- C++ -*--===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// Interfaces for registering analysis passes, producing common pass manager
11 /// configurations, and parsing of pass pipelines.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CODEGEN_CODEGENPASSBUILDER_H
16 #define LLVM_CODEGEN_CODEGENPASSBUILDER_H
17 
18 #include "llvm/ADT/FunctionExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BasicAliasAnalysis.h"
23 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
24 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
25 #include "llvm/Analysis/ScopedNoAliasAA.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
28 #include "llvm/CodeGen/ExpandReductions.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachinePassManager.h"
31 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
32 #include "llvm/CodeGen/ReplaceWithVeclib.h"
33 #include "llvm/CodeGen/UnreachableBlockElim.h"
34 #include "llvm/IR/IRPrintingPasses.h"
35 #include "llvm/IR/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCTargetOptions.h"
40 #include "llvm/Support/CodeGen.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Target/CGPassBuilderOption.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
48 #include "llvm/Transforms/Scalar/LoopPassManager.h"
49 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
50 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
51 #include "llvm/Transforms/Scalar/MergeICmps.h"
52 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
53 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
54 #include "llvm/Transforms/Utils.h"
55 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
56 #include "llvm/Transforms/Utils/LowerInvoke.h"
57 #include <cassert>
58 #include <type_traits>
59 #include <utility>
60 
61 namespace llvm {
62 
63 // FIXME: Dummy target independent passes definitions that have not yet been
64 // ported to new pass manager. Once they do, remove these.
65 #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
66   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
67     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
68     PreservedAnalyses run(Function &, FunctionAnalysisManager &) {             \
69       return PreservedAnalyses::all();                                         \
70     }                                                                          \
71   };
72 #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                        \
73   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
74     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
75     PreservedAnalyses run(Module &, ModuleAnalysisManager &) {                 \
76       return PreservedAnalyses::all();                                         \
77     }                                                                          \
78   };
79 #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                \
80   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
81     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
82     Error run(Module &, MachineFunctionAnalysisManager &) {                    \
83       return Error::success();                                                 \
84     }                                                                          \
85     PreservedAnalyses run(MachineFunction &,                                   \
86                           MachineFunctionAnalysisManager &) {                  \
87       llvm_unreachable("this api is to make new PM api happy");                \
88     }                                                                          \
89     static AnalysisKey Key;                                                    \
90   };
91 #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)              \
92   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
93     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
94     PreservedAnalyses run(MachineFunction &,                                   \
95                           MachineFunctionAnalysisManager &) {                  \
96       return PreservedAnalyses::all();                                         \
97     }                                                                          \
98     static AnalysisKey Key;                                                    \
99   };
100 #include "MachinePassRegistry.def"
101 
102 /// This class provides access to building LLVM's passes.
103 ///
104 /// Its members provide the baseline state available to passes during their
105 /// construction. The \c MachinePassRegistry.def file specifies how to construct
106 /// all of the built-in passes, and those may reference these members during
107 /// construction.
108 template <typename DerivedT> class CodeGenPassBuilder {
109 public:
CodeGenPassBuilder(LLVMTargetMachine & TM,CGPassBuilderOption Opts,PassInstrumentationCallbacks * PIC)110   explicit CodeGenPassBuilder(LLVMTargetMachine &TM, CGPassBuilderOption Opts,
111                               PassInstrumentationCallbacks *PIC)
112       : TM(TM), Opt(Opts), PIC(PIC) {
113     // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
114     //     substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
115 
116     // Target should override TM.Options.EnableIPRA in their target-specific
117     // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
118     if (Opt.EnableIPRA)
119       TM.Options.EnableIPRA = *Opt.EnableIPRA;
120 
121     if (Opt.EnableGlobalISelAbort)
122       TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
123 
124     if (!Opt.OptimizeRegAlloc)
125       Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOpt::None;
126   }
127 
128   Error buildPipeline(ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
129                       raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
130                       CodeGenFileType FileType) const;
131 
132   void registerModuleAnalyses(ModuleAnalysisManager &) const;
133   void registerFunctionAnalyses(FunctionAnalysisManager &) const;
134   void registerMachineFunctionAnalyses(MachineFunctionAnalysisManager &) const;
135   std::pair<StringRef, bool> getPassNameFromLegacyName(StringRef) const;
136 
registerAnalyses(MachineFunctionAnalysisManager & MFAM)137   void registerAnalyses(MachineFunctionAnalysisManager &MFAM) const {
138     registerModuleAnalyses(*MFAM.MAM);
139     registerFunctionAnalyses(*MFAM.FAM);
140     registerMachineFunctionAnalyses(MFAM);
141   }
142 
getPassInstrumentationCallbacks()143   PassInstrumentationCallbacks *getPassInstrumentationCallbacks() const {
144     return PIC;
145   }
146 
147 protected:
148   template <typename PassT> using has_key_t = decltype(PassT::Key);
149 
150   template <typename PassT>
151   using is_module_pass_t = decltype(std::declval<PassT &>().run(
152       std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
153 
154   template <typename PassT>
155   using is_function_pass_t = decltype(std::declval<PassT &>().run(
156       std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
157 
158   // Function object to maintain state while adding codegen IR passes.
159   class AddIRPass {
160   public:
161     AddIRPass(ModulePassManager &MPM, bool DebugPM, bool Check = true)
MPM(MPM)162         : MPM(MPM), FPM() {
163       if (Check)
164         AddingFunctionPasses = false;
165     }
~AddIRPass()166     ~AddIRPass() {
167       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
168     }
169 
170     // Add Function Pass
171     template <typename PassT>
172     std::enable_if_t<is_detected<is_function_pass_t, PassT>::value>
operator()173     operator()(PassT &&Pass) {
174       if (AddingFunctionPasses && !*AddingFunctionPasses)
175         AddingFunctionPasses = true;
176       FPM.addPass(std::forward<PassT>(Pass));
177     }
178 
179     // Add Module Pass
180     template <typename PassT>
181     std::enable_if_t<is_detected<is_module_pass_t, PassT>::value &&
182                      !is_detected<is_function_pass_t, PassT>::value>
operator()183     operator()(PassT &&Pass) {
184       assert((!AddingFunctionPasses || !*AddingFunctionPasses) &&
185              "could not add module pass after adding function pass");
186       MPM.addPass(std::forward<PassT>(Pass));
187     }
188 
189   private:
190     ModulePassManager &MPM;
191     FunctionPassManager FPM;
192     // The codegen IR pipeline are mostly function passes with the exceptions of
193     // a few loop and module passes. `AddingFunctionPasses` make sures that
194     // we could only add module passes at the beginning of the pipeline. Once
195     // we begin adding function passes, we could no longer add module passes.
196     // This special-casing introduces less adaptor passes. If we have the need
197     // of adding module passes after function passes, we could change the
198     // implementation to accommodate that.
199     Optional<bool> AddingFunctionPasses;
200   };
201 
202   // Function object to maintain state while adding codegen machine passes.
203   class AddMachinePass {
204   public:
AddMachinePass(MachineFunctionPassManager & PM)205     AddMachinePass(MachineFunctionPassManager &PM) : PM(PM) {}
206 
operator()207     template <typename PassT> void operator()(PassT &&Pass) {
208       static_assert(
209           is_detected<has_key_t, PassT>::value,
210           "Machine function pass must define a static member variable `Key`.");
211       for (auto &C : BeforeCallbacks)
212         if (!C(&PassT::Key))
213           return;
214       PM.addPass(std::forward<PassT>(Pass));
215       for (auto &C : AfterCallbacks)
216         C(&PassT::Key);
217     }
218 
insertPass(AnalysisKey * ID,PassT Pass)219     template <typename PassT> void insertPass(AnalysisKey *ID, PassT Pass) {
220       AfterCallbacks.emplace_back(
221           [this, ID, Pass = std::move(Pass)](AnalysisKey *PassID) {
222             if (PassID == ID)
223               this->PM.addPass(std::move(Pass));
224           });
225     }
226 
disablePass(AnalysisKey * ID)227     void disablePass(AnalysisKey *ID) {
228       BeforeCallbacks.emplace_back(
229           [ID](AnalysisKey *PassID) { return PassID != ID; });
230     }
231 
releasePM()232     MachineFunctionPassManager releasePM() { return std::move(PM); }
233 
234   private:
235     MachineFunctionPassManager &PM;
236     SmallVector<llvm::unique_function<bool(AnalysisKey *)>, 4> BeforeCallbacks;
237     SmallVector<llvm::unique_function<void(AnalysisKey *)>, 4> AfterCallbacks;
238   };
239 
240   LLVMTargetMachine &TM;
241   CGPassBuilderOption Opt;
242   PassInstrumentationCallbacks *PIC;
243 
244   /// Target override these hooks to parse target-specific analyses.
registerTargetAnalysis(ModuleAnalysisManager &)245   void registerTargetAnalysis(ModuleAnalysisManager &) const {}
registerTargetAnalysis(FunctionAnalysisManager &)246   void registerTargetAnalysis(FunctionAnalysisManager &) const {}
registerTargetAnalysis(MachineFunctionAnalysisManager &)247   void registerTargetAnalysis(MachineFunctionAnalysisManager &) const {}
getTargetPassNameFromLegacyName(StringRef)248   std::pair<StringRef, bool> getTargetPassNameFromLegacyName(StringRef) const {
249     return {"", false};
250   }
251 
getTM()252   template <typename TMC> TMC &getTM() const { return static_cast<TMC &>(TM); }
getOptLevel()253   CodeGenOpt::Level getOptLevel() const { return TM.getOptLevel(); }
254 
255   /// Check whether or not GlobalISel should abort on error.
256   /// When this is disabled, GlobalISel will fall back on SDISel instead of
257   /// erroring out.
isGlobalISelAbortEnabled()258   bool isGlobalISelAbortEnabled() const {
259     return TM.Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
260   }
261 
262   /// Check whether or not a diagnostic should be emitted when GlobalISel
263   /// uses the fallback path. In other words, it will emit a diagnostic
264   /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
reportDiagnosticWhenGlobalISelFallback()265   bool reportDiagnosticWhenGlobalISelFallback() const {
266     return TM.Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
267   }
268 
269   /// addInstSelector - This method should install an instruction selector pass,
270   /// which converts from LLVM code to machine instructions.
addInstSelector(AddMachinePass &)271   Error addInstSelector(AddMachinePass &) const {
272     return make_error<StringError>("addInstSelector is not overridden",
273                                    inconvertibleErrorCode());
274   }
275 
276   /// Add passes that optimize instruction level parallelism for out-of-order
277   /// targets. These passes are run while the machine code is still in SSA
278   /// form, so they can use MachineTraceMetrics to control their heuristics.
279   ///
280   /// All passes added here should preserve the MachineDominatorTree,
281   /// MachineLoopInfo, and MachineTraceMetrics analyses.
addILPOpts(AddMachinePass &)282   void addILPOpts(AddMachinePass &) const {}
283 
284   /// This method may be implemented by targets that want to run passes
285   /// immediately before register allocation.
addPreRegAlloc(AddMachinePass &)286   void addPreRegAlloc(AddMachinePass &) const {}
287 
288   /// addPreRewrite - Add passes to the optimized register allocation pipeline
289   /// after register allocation is complete, but before virtual registers are
290   /// rewritten to physical registers.
291   ///
292   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
293   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
294   /// When these passes run, VirtRegMap contains legal physreg assignments for
295   /// all virtual registers.
296   ///
297   /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
298   /// be honored. This is also not generally used for the the fast variant,
299   /// where the allocation and rewriting are done in one pass.
addPreRewrite(AddMachinePass &)300   void addPreRewrite(AddMachinePass &) const {}
301 
302   /// Add passes to be run immediately after virtual registers are rewritten
303   /// to physical registers.
addPostRewrite(AddMachinePass &)304   void addPostRewrite(AddMachinePass &) const {}
305 
306   /// This method may be implemented by targets that want to run passes after
307   /// register allocation pass pipeline but before prolog-epilog insertion.
addPostRegAlloc(AddMachinePass &)308   void addPostRegAlloc(AddMachinePass &) const {}
309 
310   /// This method may be implemented by targets that want to run passes after
311   /// prolog-epilog insertion and before the second instruction scheduling pass.
addPreSched2(AddMachinePass &)312   void addPreSched2(AddMachinePass &) const {}
313 
314   /// This pass may be implemented by targets that want to run passes
315   /// immediately before machine code is emitted.
addPreEmitPass(AddMachinePass &)316   void addPreEmitPass(AddMachinePass &) const {}
317 
318   /// Targets may add passes immediately before machine code is emitted in this
319   /// callback. This is called even later than `addPreEmitPass`.
320   // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
321   // position and remove the `2` suffix here as this callback is what
322   // `addPreEmitPass` *should* be but in reality isn't.
addPreEmitPass2(AddMachinePass &)323   void addPreEmitPass2(AddMachinePass &) const {}
324 
325   /// {{@ For GlobalISel
326   ///
327 
328   /// addPreISel - This method should add any "last minute" LLVM->LLVM
329   /// passes (which are run just before instruction selector).
addPreISel(AddIRPass &)330   void addPreISel(AddIRPass &) const {
331     llvm_unreachable("addPreISel is not overridden");
332   }
333 
334   /// This method should install an IR translator pass, which converts from
335   /// LLVM code to machine instructions with possibly generic opcodes.
addIRTranslator(AddMachinePass &)336   Error addIRTranslator(AddMachinePass &) const {
337     return make_error<StringError>("addIRTranslator is not overridden",
338                                    inconvertibleErrorCode());
339   }
340 
341   /// This method may be implemented by targets that want to run passes
342   /// immediately before legalization.
addPreLegalizeMachineIR(AddMachinePass &)343   void addPreLegalizeMachineIR(AddMachinePass &) const {}
344 
345   /// This method should install a legalize pass, which converts the instruction
346   /// sequence into one that can be selected by the target.
addLegalizeMachineIR(AddMachinePass &)347   Error addLegalizeMachineIR(AddMachinePass &) const {
348     return make_error<StringError>("addLegalizeMachineIR is not overridden",
349                                    inconvertibleErrorCode());
350   }
351 
352   /// This method may be implemented by targets that want to run passes
353   /// immediately before the register bank selection.
addPreRegBankSelect(AddMachinePass &)354   void addPreRegBankSelect(AddMachinePass &) const {}
355 
356   /// This method should install a register bank selector pass, which
357   /// assigns register banks to virtual registers without a register
358   /// class or register banks.
addRegBankSelect(AddMachinePass &)359   Error addRegBankSelect(AddMachinePass &) const {
360     return make_error<StringError>("addRegBankSelect is not overridden",
361                                    inconvertibleErrorCode());
362   }
363 
364   /// This method may be implemented by targets that want to run passes
365   /// immediately before the (global) instruction selection.
addPreGlobalInstructionSelect(AddMachinePass &)366   void addPreGlobalInstructionSelect(AddMachinePass &) const {}
367 
368   /// This method should install a (global) instruction selector pass, which
369   /// converts possibly generic instructions to fully target-specific
370   /// instructions, thereby constraining all generic virtual registers to
371   /// register classes.
addGlobalInstructionSelect(AddMachinePass &)372   Error addGlobalInstructionSelect(AddMachinePass &) const {
373     return make_error<StringError>(
374         "addGlobalInstructionSelect is not overridden",
375         inconvertibleErrorCode());
376   }
377   /// @}}
378 
379   /// High level function that adds all passes necessary to go from llvm IR
380   /// representation to the MI representation.
381   /// Adds IR based lowering and target specific optimization passes and finally
382   /// the core instruction selection passes.
383   void addISelPasses(AddIRPass &) const;
384 
385   /// Add the actual instruction selection passes. This does not include
386   /// preparation passes on IR.
387   Error addCoreISelPasses(AddMachinePass &) const;
388 
389   /// Add the complete, standard set of LLVM CodeGen passes.
390   /// Fully developed targets will not generally override this.
391   Error addMachinePasses(AddMachinePass &) const;
392 
393   /// Add passes to lower exception handling for the code generator.
394   void addPassesToHandleExceptions(AddIRPass &) const;
395 
396   /// Add common target configurable passes that perform LLVM IR to IR
397   /// transforms following machine independent optimization.
398   void addIRPasses(AddIRPass &) const;
399 
400   /// Add pass to prepare the LLVM IR for code generation. This should be done
401   /// before exception handling preparation passes.
402   void addCodeGenPrepare(AddIRPass &) const;
403 
404   /// Add common passes that perform LLVM IR to IR transforms in preparation for
405   /// instruction selection.
406   void addISelPrepare(AddIRPass &) const;
407 
408   /// Methods with trivial inline returns are convenient points in the common
409   /// codegen pass pipeline where targets may insert passes. Methods with
410   /// out-of-line standard implementations are major CodeGen stages called by
411   /// addMachinePasses. Some targets may override major stages when inserting
412   /// passes is insufficient, but maintaining overriden stages is more work.
413   ///
414 
415   /// addMachineSSAOptimization - Add standard passes that optimize machine
416   /// instructions in SSA form.
417   void addMachineSSAOptimization(AddMachinePass &) const;
418 
419   /// addFastRegAlloc - Add the minimum set of target-independent passes that
420   /// are required for fast register allocation.
421   Error addFastRegAlloc(AddMachinePass &) const;
422 
423   /// addOptimizedRegAlloc - Add passes related to register allocation.
424   /// LLVMTargetMachine provides standard regalloc passes for most targets.
425   void addOptimizedRegAlloc(AddMachinePass &) const;
426 
427   /// Add passes that optimize machine instructions after register allocation.
428   void addMachineLateOptimization(AddMachinePass &) const;
429 
430   /// addGCPasses - Add late codegen passes that analyze code for garbage
431   /// collection. This should return true if GC info should be printed after
432   /// these passes.
addGCPasses(AddMachinePass &)433   void addGCPasses(AddMachinePass &) const {}
434 
435   /// Add standard basic block placement passes.
436   void addBlockPlacement(AddMachinePass &) const;
437 
438   using CreateMCStreamer =
439       std::function<Expected<std::unique_ptr<MCStreamer>>(MCContext &)>;
addAsmPrinter(AddMachinePass &,CreateMCStreamer)440   void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const {
441     llvm_unreachable("addAsmPrinter is not overridden");
442   }
443 
444   /// Utilities for targets to add passes to the pass manager.
445   ///
446 
447   /// createTargetRegisterAllocator - Create the register allocator pass for
448   /// this target at the current optimization level.
449   void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const;
450 
451   /// addMachinePasses helper to create the target-selected or overriden
452   /// regalloc pass.
453   void addRegAllocPass(AddMachinePass &, bool Optimized) const;
454 
455   /// Add core register alloator passes which do the actual register assignment
456   /// and rewriting. \returns true if any passes were added.
457   Error addRegAssignmentFast(AddMachinePass &) const;
458   Error addRegAssignmentOptimized(AddMachinePass &) const;
459 
460 private:
derived()461   DerivedT &derived() { return static_cast<DerivedT &>(*this); }
derived()462   const DerivedT &derived() const {
463     return static_cast<const DerivedT &>(*this);
464   }
465 };
466 
467 template <typename Derived>
buildPipeline(ModulePassManager & MPM,MachineFunctionPassManager & MFPM,raw_pwrite_stream & Out,raw_pwrite_stream * DwoOut,CodeGenFileType FileType)468 Error CodeGenPassBuilder<Derived>::buildPipeline(
469     ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
470     raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
471     CodeGenFileType FileType) const {
472   AddIRPass addIRPass(MPM, Opt.DebugPM);
473   addISelPasses(addIRPass);
474 
475   AddMachinePass addPass(MFPM);
476   if (auto Err = addCoreISelPasses(addPass))
477     return std::move(Err);
478 
479   if (auto Err = derived().addMachinePasses(addPass))
480     return std::move(Err);
481 
482   derived().addAsmPrinter(
483       addPass, [this, &Out, DwoOut, FileType](MCContext &Ctx) {
484         return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
485       });
486 
487   addPass(FreeMachineFunctionPass());
488   return Error::success();
489 }
490 
registerAAAnalyses(CFLAAType UseCFLAA)491 static inline AAManager registerAAAnalyses(CFLAAType UseCFLAA) {
492   AAManager AA;
493 
494   // The order in which these are registered determines their priority when
495   // being queried.
496 
497   switch (UseCFLAA) {
498   case CFLAAType::Steensgaard:
499     AA.registerFunctionAnalysis<CFLSteensAA>();
500     break;
501   case CFLAAType::Andersen:
502     AA.registerFunctionAnalysis<CFLAndersAA>();
503     break;
504   case CFLAAType::Both:
505     AA.registerFunctionAnalysis<CFLAndersAA>();
506     AA.registerFunctionAnalysis<CFLSteensAA>();
507     break;
508   default:
509     break;
510   }
511 
512   // Basic AliasAnalysis support.
513   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
514   // BasicAliasAnalysis wins if they disagree. This is intended to help
515   // support "obvious" type-punning idioms.
516   AA.registerFunctionAnalysis<TypeBasedAA>();
517   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
518   AA.registerFunctionAnalysis<BasicAA>();
519 
520   return AA;
521 }
522 
523 template <typename Derived>
registerModuleAnalyses(ModuleAnalysisManager & MAM)524 void CodeGenPassBuilder<Derived>::registerModuleAnalyses(
525     ModuleAnalysisManager &MAM) const {
526 #define MODULE_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                          \
527   MAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
528 #include "MachinePassRegistry.def"
529   derived().registerTargetAnalysis(MAM);
530 }
531 
532 template <typename Derived>
registerFunctionAnalyses(FunctionAnalysisManager & FAM)533 void CodeGenPassBuilder<Derived>::registerFunctionAnalyses(
534     FunctionAnalysisManager &FAM) const {
535   FAM.registerPass([this] { return registerAAAnalyses(this->Opt.UseCFLAA); });
536 
537 #define FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                        \
538   FAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
539 #include "MachinePassRegistry.def"
540   derived().registerTargetAnalysis(FAM);
541 }
542 
543 template <typename Derived>
registerMachineFunctionAnalyses(MachineFunctionAnalysisManager & MFAM)544 void CodeGenPassBuilder<Derived>::registerMachineFunctionAnalyses(
545     MachineFunctionAnalysisManager &MFAM) const {
546 #define MACHINE_FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                \
547   MFAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
548 #include "MachinePassRegistry.def"
549   derived().registerTargetAnalysis(MFAM);
550 }
551 
552 // FIXME: For new PM, use pass name directly in commandline seems good.
553 // Translate stringfied pass name to its old commandline name. Returns the
554 // matching legacy name and a boolean value indicating if the pass is a machine
555 // pass.
556 template <typename Derived>
557 std::pair<StringRef, bool>
getPassNameFromLegacyName(StringRef Name)558 CodeGenPassBuilder<Derived>::getPassNameFromLegacyName(StringRef Name) const {
559   std::pair<StringRef, bool> Ret;
560   if (Name.empty())
561     return Ret;
562 
563 #define FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                            \
564   if (Name == NAME)                                                            \
565     Ret = {#PASS_NAME, false};
566 #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
567   if (Name == NAME)                                                            \
568     Ret = {#PASS_NAME, false};
569 #define MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                              \
570   if (Name == NAME)                                                            \
571     Ret = {#PASS_NAME, false};
572 #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                        \
573   if (Name == NAME)                                                            \
574     Ret = {#PASS_NAME, false};
575 #define MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
576   if (Name == NAME)                                                            \
577     Ret = {#PASS_NAME, true};
578 #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                \
579   if (Name == NAME)                                                            \
580     Ret = {#PASS_NAME, true};
581 #define MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                    \
582   if (Name == NAME)                                                            \
583     Ret = {#PASS_NAME, true};
584 #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)              \
585   if (Name == NAME)                                                            \
586     Ret = {#PASS_NAME, true};
587 #include "llvm/CodeGen/MachinePassRegistry.def"
588 
589   if (Ret.first.empty())
590     Ret = derived().getTargetPassNameFromLegacyName(Name);
591 
592   if (Ret.first.empty())
593     report_fatal_error(Twine('\"') + Twine(Name) +
594                        Twine("\" pass could not be found."));
595 
596   return Ret;
597 }
598 
599 template <typename Derived>
addISelPasses(AddIRPass & addPass)600 void CodeGenPassBuilder<Derived>::addISelPasses(AddIRPass &addPass) const {
601   if (TM.useEmulatedTLS())
602     addPass(LowerEmuTLSPass());
603 
604   addPass(PreISelIntrinsicLoweringPass());
605 
606   derived().addIRPasses(addPass);
607   derived().addCodeGenPrepare(addPass);
608   addPassesToHandleExceptions(addPass);
609   derived().addISelPrepare(addPass);
610 }
611 
612 /// Add common target configurable passes that perform LLVM IR to IR transforms
613 /// following machine independent optimization.
614 template <typename Derived>
addIRPasses(AddIRPass & addPass)615 void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
616   // Before running any passes, run the verifier to determine if the input
617   // coming from the front-end and/or optimizer is valid.
618   if (!Opt.DisableVerify)
619     addPass(VerifierPass());
620 
621   // Run loop strength reduction before anything else.
622   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableLSR) {
623     addPass(createFunctionToLoopPassAdaptor(
624         LoopStrengthReducePass(), /*UseMemorySSA*/ true, Opt.DebugPM));
625     // FIXME: use -stop-after so we could remove PrintLSR
626     if (Opt.PrintLSR)
627       addPass(PrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
628   }
629 
630   if (getOptLevel() != CodeGenOpt::None) {
631     // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
632     // loads and compares. ExpandMemCmpPass then tries to expand those calls
633     // into optimally-sized loads and compares. The transforms are enabled by a
634     // target lowering hook.
635     if (!Opt.DisableMergeICmps)
636       addPass(MergeICmpsPass());
637     addPass(ExpandMemCmpPass());
638   }
639 
640   // Run GC lowering passes for builtin collectors
641   // TODO: add a pass insertion point here
642   addPass(GCLoweringPass());
643   addPass(ShadowStackGCLoweringPass());
644   addPass(LowerConstantIntrinsicsPass());
645 
646   // Make sure that no unreachable blocks are instruction selected.
647   addPass(UnreachableBlockElimPass());
648 
649   // Prepare expensive constants for SelectionDAG.
650   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableConstantHoisting)
651     addPass(ConstantHoistingPass());
652 
653   // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
654   // operands with calls to the corresponding functions in a vector library.
655   if (getOptLevel() != CodeGenOpt::None)
656     addPass(ReplaceWithVeclib());
657 
658   if (getOptLevel() != CodeGenOpt::None && !Opt.DisablePartialLibcallInlining)
659     addPass(PartiallyInlineLibCallsPass());
660 
661   // Instrument function entry and exit, e.g. with calls to mcount().
662   addPass(EntryExitInstrumenterPass(/*PostInlining=*/true));
663 
664   // Add scalarization of target's unsupported masked memory intrinsics pass.
665   // the unsupported intrinsic will be replaced with a chain of basic blocks,
666   // that stores/loads element one-by-one if the appropriate mask bit is set.
667   addPass(ScalarizeMaskedMemIntrinPass());
668 
669   // Expand reduction intrinsics into shuffle sequences if the target wants to.
670   addPass(ExpandReductionsPass());
671 }
672 
673 /// Turn exception handling constructs into something the code generators can
674 /// handle.
675 template <typename Derived>
addPassesToHandleExceptions(AddIRPass & addPass)676 void CodeGenPassBuilder<Derived>::addPassesToHandleExceptions(
677     AddIRPass &addPass) const {
678   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
679   assert(MCAI && "No MCAsmInfo");
680   switch (MCAI->getExceptionHandlingType()) {
681   case ExceptionHandling::SjLj:
682     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
683     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
684     // catch info can get misplaced when a selector ends up more than one block
685     // removed from the parent invoke(s). This could happen when a landing
686     // pad is shared by multiple invokes and is also a target of a normal
687     // edge from elsewhere.
688     addPass(SjLjEHPreparePass());
689     LLVM_FALLTHROUGH;
690   case ExceptionHandling::DwarfCFI:
691   case ExceptionHandling::ARM:
692   case ExceptionHandling::AIX:
693     addPass(DwarfEHPass(getOptLevel()));
694     break;
695   case ExceptionHandling::WinEH:
696     // We support using both GCC-style and MSVC-style exceptions on Windows, so
697     // add both preparation passes. Each pass will only actually run if it
698     // recognizes the personality function.
699     addPass(WinEHPass());
700     addPass(DwarfEHPass(getOptLevel()));
701     break;
702   case ExceptionHandling::Wasm:
703     // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
704     // on catchpads and cleanuppads because it does not outline them into
705     // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
706     // should remove PHIs there.
707     addPass(WinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
708     addPass(WasmEHPass());
709     break;
710   case ExceptionHandling::None:
711     addPass(LowerInvokePass());
712 
713     // The lower invoke pass may create unreachable code. Remove it.
714     addPass(UnreachableBlockElimPass());
715     break;
716   }
717 }
718 
719 /// Add pass to prepare the LLVM IR for code generation. This should be done
720 /// before exception handling preparation passes.
721 template <typename Derived>
addCodeGenPrepare(AddIRPass & addPass)722 void CodeGenPassBuilder<Derived>::addCodeGenPrepare(AddIRPass &addPass) const {
723   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableCGP)
724     addPass(CodeGenPreparePass());
725   // TODO: Default ctor'd RewriteSymbolPass is no-op.
726   // addPass(RewriteSymbolPass());
727 }
728 
729 /// Add common passes that perform LLVM IR to IR transforms in preparation for
730 /// instruction selection.
731 template <typename Derived>
addISelPrepare(AddIRPass & addPass)732 void CodeGenPassBuilder<Derived>::addISelPrepare(AddIRPass &addPass) const {
733   derived().addPreISel(addPass);
734 
735   // Add both the safe stack and the stack protection passes: each of them will
736   // only protect functions that have corresponding attributes.
737   addPass(SafeStackPass());
738   addPass(StackProtectorPass());
739 
740   if (Opt.PrintISelInput)
741     addPass(PrintFunctionPass(dbgs(),
742                               "\n\n*** Final LLVM Code input to ISel ***\n"));
743 
744   // All passes which modify the LLVM IR are now complete; run the verifier
745   // to ensure that the IR is valid.
746   if (!Opt.DisableVerify)
747     addPass(VerifierPass());
748 }
749 
750 template <typename Derived>
addCoreISelPasses(AddMachinePass & addPass)751 Error CodeGenPassBuilder<Derived>::addCoreISelPasses(
752     AddMachinePass &addPass) const {
753   // Enable FastISel with -fast-isel, but allow that to be overridden.
754   TM.setO0WantsFastISel(Opt.EnableFastISelOption.getValueOr(true));
755 
756   // Determine an instruction selector.
757   enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
758   SelectorType Selector;
759 
760   if (Opt.EnableFastISelOption && *Opt.EnableFastISelOption == true)
761     Selector = SelectorType::FastISel;
762   else if ((Opt.EnableGlobalISelOption &&
763             *Opt.EnableGlobalISelOption == true) ||
764            (TM.Options.EnableGlobalISel &&
765             (!Opt.EnableGlobalISelOption ||
766              *Opt.EnableGlobalISelOption == false)))
767     Selector = SelectorType::GlobalISel;
768   else if (TM.getOptLevel() == CodeGenOpt::None && TM.getO0WantsFastISel())
769     Selector = SelectorType::FastISel;
770   else
771     Selector = SelectorType::SelectionDAG;
772 
773   // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
774   if (Selector == SelectorType::FastISel) {
775     TM.setFastISel(true);
776     TM.setGlobalISel(false);
777   } else if (Selector == SelectorType::GlobalISel) {
778     TM.setFastISel(false);
779     TM.setGlobalISel(true);
780   }
781 
782   // Add instruction selector passes.
783   if (Selector == SelectorType::GlobalISel) {
784     if (auto Err = derived().addIRTranslator(addPass))
785       return std::move(Err);
786 
787     derived().addPreLegalizeMachineIR(addPass);
788 
789     if (auto Err = derived().addLegalizeMachineIR(addPass))
790       return std::move(Err);
791 
792     // Before running the register bank selector, ask the target if it
793     // wants to run some passes.
794     derived().addPreRegBankSelect(addPass);
795 
796     if (auto Err = derived().addRegBankSelect(addPass))
797       return std::move(Err);
798 
799     derived().addPreGlobalInstructionSelect(addPass);
800 
801     if (auto Err = derived().addGlobalInstructionSelect(addPass))
802       return std::move(Err);
803 
804     // Pass to reset the MachineFunction if the ISel failed.
805     addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
806                                      isGlobalISelAbortEnabled()));
807 
808     // Provide a fallback path when we do not want to abort on
809     // not-yet-supported input.
810     if (!isGlobalISelAbortEnabled())
811       if (auto Err = derived().addInstSelector(addPass))
812         return std::move(Err);
813 
814   } else if (auto Err = derived().addInstSelector(addPass))
815     return std::move(Err);
816 
817   // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
818   // FinalizeISel.
819   addPass(FinalizeISelPass());
820 
821   // // Print the instruction selected machine code...
822   // printAndVerify("After Instruction Selection");
823 
824   return Error::success();
825 }
826 
827 /// Add the complete set of target-independent postISel code generator passes.
828 ///
829 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
830 /// with nontrivial configuration or multiple passes are broken out below in
831 /// add%Stage routines.
832 ///
833 /// Any CodeGenPassBuilder<Derived>::addXX routine may be overriden by the
834 /// Target. The addPre/Post methods with empty header implementations allow
835 /// injecting target-specific fixups just before or after major stages.
836 /// Additionally, targets have the flexibility to change pass order within a
837 /// stage by overriding default implementation of add%Stage routines below. Each
838 /// technique has maintainability tradeoffs because alternate pass orders are
839 /// not well supported. addPre/Post works better if the target pass is easily
840 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
841 /// the target should override the stage instead.
842 template <typename Derived>
addMachinePasses(AddMachinePass & addPass)843 Error CodeGenPassBuilder<Derived>::addMachinePasses(
844     AddMachinePass &addPass) const {
845   // Add passes that optimize machine instructions in SSA form.
846   if (getOptLevel() != CodeGenOpt::None) {
847     derived().addMachineSSAOptimization(addPass);
848   } else {
849     // If the target requests it, assign local variables to stack slots relative
850     // to one another and simplify frame index references where possible.
851     addPass(LocalStackSlotPass());
852   }
853 
854   if (TM.Options.EnableIPRA)
855     addPass(RegUsageInfoPropagationPass());
856 
857   // Run pre-ra passes.
858   derived().addPreRegAlloc(addPass);
859 
860   // Run register allocation and passes that are tightly coupled with it,
861   // including phi elimination and scheduling.
862   if (*Opt.OptimizeRegAlloc) {
863     derived().addOptimizedRegAlloc(addPass);
864   } else {
865     if (auto Err = derived().addFastRegAlloc(addPass))
866       return Err;
867   }
868 
869   // Run post-ra passes.
870   derived().addPostRegAlloc(addPass);
871 
872   // Insert prolog/epilog code.  Eliminate abstract frame index references...
873   if (getOptLevel() != CodeGenOpt::None) {
874     addPass(PostRAMachineSinkingPass());
875     addPass(ShrinkWrapPass());
876   }
877 
878   addPass(PrologEpilogInserterPass());
879 
880   /// Add passes that optimize machine instructions after register allocation.
881   if (getOptLevel() != CodeGenOpt::None)
882     derived().addMachineLateOptimization(addPass);
883 
884   // Expand pseudo instructions before second scheduling pass.
885   addPass(ExpandPostRAPseudosPass());
886 
887   // Run pre-sched2 passes.
888   derived().addPreSched2(addPass);
889 
890   if (Opt.EnableImplicitNullChecks)
891     addPass(ImplicitNullChecksPass());
892 
893   // Second pass scheduler.
894   // Let Target optionally insert this pass by itself at some other
895   // point.
896   if (getOptLevel() != CodeGenOpt::None &&
897       !TM.targetSchedulesPostRAScheduling()) {
898     if (Opt.MISchedPostRA)
899       addPass(PostMachineSchedulerPass());
900     else
901       addPass(PostRASchedulerPass());
902   }
903 
904   // GC
905   derived().addGCPasses(addPass);
906 
907   // Basic block placement.
908   if (getOptLevel() != CodeGenOpt::None)
909     derived().addBlockPlacement(addPass);
910 
911   // Insert before XRay Instrumentation.
912   addPass(FEntryInserterPass());
913 
914   addPass(XRayInstrumentationPass());
915   addPass(PatchableFunctionPass());
916 
917   derived().addPreEmitPass(addPass);
918 
919   if (TM.Options.EnableIPRA)
920     // Collect register usage information and produce a register mask of
921     // clobbered registers, to be used to optimize call sites.
922     addPass(RegUsageInfoCollectorPass());
923 
924   addPass(FuncletLayoutPass());
925 
926   addPass(StackMapLivenessPass());
927   addPass(LiveDebugValuesPass());
928 
929   if (TM.Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
930       Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
931     bool RunOnAllFunctions =
932         (Opt.EnableMachineOutliner == RunOutliner::AlwaysOutline);
933     bool AddOutliner = RunOnAllFunctions || TM.Options.SupportsDefaultOutlining;
934     if (AddOutliner)
935       addPass(MachineOutlinerPass(RunOnAllFunctions));
936   }
937 
938   // Add passes that directly emit MI after all other MI passes.
939   derived().addPreEmitPass2(addPass);
940 
941   return Error::success();
942 }
943 
944 /// Add passes that optimize machine instructions in SSA form.
945 template <typename Derived>
addMachineSSAOptimization(AddMachinePass & addPass)946 void CodeGenPassBuilder<Derived>::addMachineSSAOptimization(
947     AddMachinePass &addPass) const {
948   // Pre-ra tail duplication.
949   addPass(EarlyTailDuplicatePass());
950 
951   // Optimize PHIs before DCE: removing dead PHI cycles may make more
952   // instructions dead.
953   addPass(OptimizePHIsPass());
954 
955   // This pass merges large allocas. StackSlotColoring is a different pass
956   // which merges spill slots.
957   addPass(StackColoringPass());
958 
959   // If the target requests it, assign local variables to stack slots relative
960   // to one another and simplify frame index references where possible.
961   addPass(LocalStackSlotPass());
962 
963   // With optimization, dead code should already be eliminated. However
964   // there is one known exception: lowered code for arguments that are only
965   // used by tail calls, where the tail calls reuse the incoming stack
966   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
967   addPass(DeadMachineInstructionElimPass());
968 
969   // Allow targets to insert passes that improve instruction level parallelism,
970   // like if-conversion. Such passes will typically need dominator trees and
971   // loop info, just like LICM and CSE below.
972   derived().addILPOpts(addPass);
973 
974   addPass(EarlyMachineLICMPass());
975   addPass(MachineCSEPass());
976 
977   addPass(MachineSinkingPass());
978 
979   addPass(PeepholeOptimizerPass());
980   // Clean-up the dead code that may have been generated by peephole
981   // rewriting.
982   addPass(DeadMachineInstructionElimPass());
983 }
984 
985 //===---------------------------------------------------------------------===//
986 /// Register Allocation Pass Configuration
987 //===---------------------------------------------------------------------===//
988 
989 /// Instantiate the default register allocator pass for this target for either
990 /// the optimized or unoptimized allocation path. This will be added to the pass
991 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
992 /// in the optimized case.
993 ///
994 /// A target that uses the standard regalloc pass order for fast or optimized
995 /// allocation may still override this for per-target regalloc
996 /// selection. But -regalloc=... always takes precedence.
997 template <typename Derived>
addTargetRegisterAllocator(AddMachinePass & addPass,bool Optimized)998 void CodeGenPassBuilder<Derived>::addTargetRegisterAllocator(
999     AddMachinePass &addPass, bool Optimized) const {
1000   if (Optimized)
1001     addPass(RAGreedyPass());
1002   else
1003     addPass(RAFastPass());
1004 }
1005 
1006 /// Find and instantiate the register allocation pass requested by this target
1007 /// at the current optimization level.  Different register allocators are
1008 /// defined as separate passes because they may require different analysis.
1009 template <typename Derived>
addRegAllocPass(AddMachinePass & addPass,bool Optimized)1010 void CodeGenPassBuilder<Derived>::addRegAllocPass(AddMachinePass &addPass,
1011                                                   bool Optimized) const {
1012   if (Opt.RegAlloc == RegAllocType::Default)
1013     // With no -regalloc= override, ask the target for a regalloc pass.
1014     derived().addTargetRegisterAllocator(addPass, Optimized);
1015   else if (Opt.RegAlloc == RegAllocType::Basic)
1016     addPass(RABasicPass());
1017   else if (Opt.RegAlloc == RegAllocType::Fast)
1018     addPass(RAFastPass());
1019   else if (Opt.RegAlloc == RegAllocType::Greedy)
1020     addPass(RAGreedyPass());
1021   else if (Opt.RegAlloc == RegAllocType::PBQP)
1022     addPass(RAPBQPPass());
1023   else
1024     llvm_unreachable("unknonwn register allocator type");
1025 }
1026 
1027 template <typename Derived>
addRegAssignmentFast(AddMachinePass & addPass)1028 Error CodeGenPassBuilder<Derived>::addRegAssignmentFast(
1029     AddMachinePass &addPass) const {
1030   if (Opt.RegAlloc != RegAllocType::Default &&
1031       Opt.RegAlloc != RegAllocType::Fast)
1032     return make_error<StringError>(
1033         "Must use fast (default) register allocator for unoptimized regalloc.",
1034         inconvertibleErrorCode());
1035 
1036   addRegAllocPass(addPass, false);
1037   return Error::success();
1038 }
1039 
1040 template <typename Derived>
addRegAssignmentOptimized(AddMachinePass & addPass)1041 Error CodeGenPassBuilder<Derived>::addRegAssignmentOptimized(
1042     AddMachinePass &addPass) const {
1043   // Add the selected register allocation pass.
1044   addRegAllocPass(addPass, true);
1045 
1046   // Allow targets to change the register assignments before rewriting.
1047   derived().addPreRewrite(addPass);
1048 
1049   // Finally rewrite virtual registers.
1050   addPass(VirtRegRewriterPass());
1051   // Perform stack slot coloring and post-ra machine LICM.
1052   //
1053   // FIXME: Re-enable coloring with register when it's capable of adding
1054   // kill markers.
1055   addPass(StackSlotColoringPass());
1056 
1057   return Error::success();
1058 }
1059 
1060 /// Add the minimum set of target-independent passes that are required for
1061 /// register allocation. No coalescing or scheduling.
1062 template <typename Derived>
addFastRegAlloc(AddMachinePass & addPass)1063 Error CodeGenPassBuilder<Derived>::addFastRegAlloc(
1064     AddMachinePass &addPass) const {
1065   addPass(PHIEliminationPass());
1066   addPass(TwoAddressInstructionPass());
1067   return derived().addRegAssignmentFast(addPass);
1068 }
1069 
1070 /// Add standard target-independent passes that are tightly coupled with
1071 /// optimized register allocation, including coalescing, machine instruction
1072 /// scheduling, and register allocation itself.
1073 template <typename Derived>
addOptimizedRegAlloc(AddMachinePass & addPass)1074 void CodeGenPassBuilder<Derived>::addOptimizedRegAlloc(
1075     AddMachinePass &addPass) const {
1076   addPass(DetectDeadLanesPass());
1077 
1078   addPass(ProcessImplicitDefsPass());
1079 
1080   // Edge splitting is smarter with machine loop info.
1081   addPass(PHIEliminationPass());
1082 
1083   // Eventually, we want to run LiveIntervals before PHI elimination.
1084   if (Opt.EarlyLiveIntervals)
1085     addPass(LiveIntervalsPass());
1086 
1087   addPass(TwoAddressInstructionPass());
1088   addPass(RegisterCoalescerPass());
1089 
1090   // The machine scheduler may accidentally create disconnected components
1091   // when moving subregister definitions around, avoid this by splitting them to
1092   // separate vregs before. Splitting can also improve reg. allocation quality.
1093   addPass(RenameIndependentSubregsPass());
1094 
1095   // PreRA instruction scheduling.
1096   addPass(MachineSchedulerPass());
1097 
1098   if (derived().addRegAssignmentOptimized(addPass)) {
1099     // Allow targets to expand pseudo instructions depending on the choice of
1100     // registers before MachineCopyPropagation.
1101     derived().addPostRewrite(addPass);
1102 
1103     // Copy propagate to forward register uses and try to eliminate COPYs that
1104     // were not coalesced.
1105     addPass(MachineCopyPropagationPass());
1106 
1107     // Run post-ra machine LICM to hoist reloads / remats.
1108     //
1109     // FIXME: can this move into MachineLateOptimization?
1110     addPass(MachineLICMPass());
1111   }
1112 }
1113 
1114 //===---------------------------------------------------------------------===//
1115 /// Post RegAlloc Pass Configuration
1116 //===---------------------------------------------------------------------===//
1117 
1118 /// Add passes that optimize machine instructions after register allocation.
1119 template <typename Derived>
addMachineLateOptimization(AddMachinePass & addPass)1120 void CodeGenPassBuilder<Derived>::addMachineLateOptimization(
1121     AddMachinePass &addPass) const {
1122   // Branch folding must be run after regalloc and prolog/epilog insertion.
1123   addPass(BranchFolderPass());
1124 
1125   // Tail duplication.
1126   // Note that duplicating tail just increases code size and degrades
1127   // performance for targets that require Structured Control Flow.
1128   // In addition it can also make CFG irreducible. Thus we disable it.
1129   if (!TM.requiresStructuredCFG())
1130     addPass(TailDuplicatePass());
1131 
1132   // Copy propagation.
1133   addPass(MachineCopyPropagationPass());
1134 }
1135 
1136 /// Add standard basic block placement passes.
1137 template <typename Derived>
addBlockPlacement(AddMachinePass & addPass)1138 void CodeGenPassBuilder<Derived>::addBlockPlacement(
1139     AddMachinePass &addPass) const {
1140   addPass(MachineBlockPlacementPass());
1141   // Run a separate pass to collect block placement statistics.
1142   if (Opt.EnableBlockPlacementStats)
1143     addPass(MachineBlockPlacementStatsPass());
1144 }
1145 
1146 } // namespace llvm
1147 
1148 #endif // LLVM_CODEGEN_CODEGENPASSBUILDER_H
1149