1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //
10 //===----------------------------------------------------------------------===//
11 
12 #include "AArch64TargetMachine.h"
13 #include "AArch64.h"
14 #include "AArch64MacroFusion.h"
15 #include "AArch64Subtarget.h"
16 #include "AArch64TargetObjectFile.h"
17 #include "AArch64TargetTransformInfo.h"
18 #include "MCTargetDesc/AArch64MCTargetDesc.h"
19 #include "TargetInfo/AArch64TargetInfo.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/CodeGen/CSEConfigBase.h"
24 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
25 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
26 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
27 #include "llvm/CodeGen/GlobalISel/Localizer.h"
28 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
29 #include "llvm/CodeGen/MachineScheduler.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/CodeGen/TargetPassConfig.h"
32 #include "llvm/IR/Attributes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCTargetOptions.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CodeGen.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/CFGuard.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include <memory>
46 #include <string>
47 
48 using namespace llvm;
49 
50 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
51                                 cl::desc("Enable the CCMP formation pass"),
52                                 cl::init(true), cl::Hidden);
53 
54 static cl::opt<bool>
55     EnableCondBrTuning("aarch64-enable-cond-br-tune",
56                        cl::desc("Enable the conditional branch tuning pass"),
57                        cl::init(true), cl::Hidden);
58 
59 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
60                                cl::desc("Enable the machine combiner pass"),
61                                cl::init(true), cl::Hidden);
62 
63 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
64                                           cl::desc("Suppress STP for AArch64"),
65                                           cl::init(true), cl::Hidden);
66 
67 static cl::opt<bool> EnableAdvSIMDScalar(
68     "aarch64-enable-simd-scalar",
69     cl::desc("Enable use of AdvSIMD scalar integer instructions"),
70     cl::init(false), cl::Hidden);
71 
72 static cl::opt<bool>
73     EnablePromoteConstant("aarch64-enable-promote-const",
74                           cl::desc("Enable the promote constant pass"),
75                           cl::init(true), cl::Hidden);
76 
77 static cl::opt<bool> EnableCollectLOH(
78     "aarch64-enable-collect-loh",
79     cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
80     cl::init(true), cl::Hidden);
81 
82 static cl::opt<bool>
83     EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
84                                   cl::desc("Enable the pass that removes dead"
85                                            " definitons and replaces stores to"
86                                            " them with stores to the zero"
87                                            " register"),
88                                   cl::init(true));
89 
90 static cl::opt<bool> EnableRedundantCopyElimination(
91     "aarch64-enable-copyelim",
92     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
93     cl::Hidden);
94 
95 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
96                                         cl::desc("Enable the load/store pair"
97                                                  " optimization pass"),
98                                         cl::init(true), cl::Hidden);
99 
100 static cl::opt<bool> EnableAtomicTidy(
101     "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
102     cl::desc("Run SimplifyCFG after expanding atomic operations"
103              " to make use of cmpxchg flow-based information"),
104     cl::init(true));
105 
106 static cl::opt<bool>
107 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
108                         cl::desc("Run early if-conversion"),
109                         cl::init(true));
110 
111 static cl::opt<bool>
112     EnableCondOpt("aarch64-enable-condopt",
113                   cl::desc("Enable the condition optimizer pass"),
114                   cl::init(true), cl::Hidden);
115 
116 static cl::opt<bool>
117 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
118                 cl::desc("Work around Cortex-A53 erratum 835769"),
119                 cl::init(false));
120 
121 static cl::opt<bool>
122     EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
123                  cl::desc("Enable optimizations on complex GEPs"),
124                  cl::init(false));
125 
126 static cl::opt<bool>
127     BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
128                      cl::desc("Relax out of range conditional branches"));
129 
130 static cl::opt<bool> EnableCompressJumpTables(
131     "aarch64-enable-compress-jump-tables", cl::Hidden, cl::init(true),
132     cl::desc("Use smallest entry possible for jump tables"));
133 
134 // FIXME: Unify control over GlobalMerge.
135 static cl::opt<cl::boolOrDefault>
136     EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
137                       cl::desc("Enable the global merge pass"));
138 
139 static cl::opt<bool>
140     EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
141                            cl::desc("Enable the loop data prefetch pass"),
142                            cl::init(true));
143 
144 static cl::opt<int> EnableGlobalISelAtO(
145     "aarch64-enable-global-isel-at-O", cl::Hidden,
146     cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
147     cl::init(0));
148 
149 static cl::opt<bool> EnableFalkorHWPFFix("aarch64-enable-falkor-hwpf-fix",
150                                          cl::init(true), cl::Hidden);
151 
152 static cl::opt<bool>
153     EnableBranchTargets("aarch64-enable-branch-targets", cl::Hidden,
154                         cl::desc("Enable the AAcrh64 branch target pass"),
155                         cl::init(true));
156 
157 extern "C" void LLVMInitializeAArch64Target() {
158   // Register the target.
159   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
160   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
161   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
162   RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
163   RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
164   auto PR = PassRegistry::getPassRegistry();
165   initializeGlobalISel(*PR);
166   initializeAArch64A53Fix835769Pass(*PR);
167   initializeAArch64A57FPLoadBalancingPass(*PR);
168   initializeAArch64AdvSIMDScalarPass(*PR);
169   initializeAArch64BranchTargetsPass(*PR);
170   initializeAArch64CollectLOHPass(*PR);
171   initializeAArch64CompressJumpTablesPass(*PR);
172   initializeAArch64ConditionalComparesPass(*PR);
173   initializeAArch64ConditionOptimizerPass(*PR);
174   initializeAArch64DeadRegisterDefinitionsPass(*PR);
175   initializeAArch64ExpandPseudoPass(*PR);
176   initializeAArch64LoadStoreOptPass(*PR);
177   initializeAArch64SIMDInstrOptPass(*PR);
178   initializeAArch64PreLegalizerCombinerPass(*PR);
179   initializeAArch64PromoteConstantPass(*PR);
180   initializeAArch64RedundantCopyEliminationPass(*PR);
181   initializeAArch64StorePairSuppressPass(*PR);
182   initializeFalkorHWPFFixPass(*PR);
183   initializeFalkorMarkStridedAccessesLegacyPass(*PR);
184   initializeLDTLSCleanupPass(*PR);
185   initializeAArch64SpeculationHardeningPass(*PR);
186   initializeAArch64StackTaggingPass(*PR);
187   initializeAArch64StackTaggingPreRAPass(*PR);
188 }
189 
190 //===----------------------------------------------------------------------===//
191 // AArch64 Lowering public interface.
192 //===----------------------------------------------------------------------===//
193 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
194   if (TT.isOSBinFormatMachO())
195     return std::make_unique<AArch64_MachoTargetObjectFile>();
196   if (TT.isOSBinFormatCOFF())
197     return std::make_unique<AArch64_COFFTargetObjectFile>();
198 
199   return std::make_unique<AArch64_ELFTargetObjectFile>();
200 }
201 
202 // Helper function to build a DataLayout string
203 static std::string computeDataLayout(const Triple &TT,
204                                      const MCTargetOptions &Options,
205                                      bool LittleEndian) {
206   if (Options.getABIName() == "ilp32")
207     return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
208   if (TT.isOSBinFormatMachO()) {
209     if (TT.getArch() == Triple::aarch64_32)
210       return "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128";
211     return "e-m:o-i64:64-i128:128-n32:64-S128";
212   }
213   if (TT.isOSBinFormatCOFF())
214     return "e-m:w-p:64:64-i32:32-i64:64-i128:128-n32:64-S128";
215   if (LittleEndian)
216     return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
217   return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
218 }
219 
220 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
221                                            Optional<Reloc::Model> RM) {
222   // AArch64 Darwin and Windows are always PIC.
223   if (TT.isOSDarwin() || TT.isOSWindows())
224     return Reloc::PIC_;
225   // On ELF platforms the default static relocation model has a smart enough
226   // linker to cope with referencing external symbols defined in a shared
227   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
228   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
229     return Reloc::Static;
230   return *RM;
231 }
232 
233 static CodeModel::Model
234 getEffectiveAArch64CodeModel(const Triple &TT, Optional<CodeModel::Model> CM,
235                              bool JIT) {
236   if (CM) {
237     if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
238         *CM != CodeModel::Large) {
239       if (!TT.isOSFuchsia())
240         report_fatal_error(
241             "Only small, tiny and large code models are allowed on AArch64");
242       else if (*CM != CodeModel::Kernel)
243         report_fatal_error("Only small, tiny, kernel, and large code models "
244                            "are allowed on AArch64");
245     } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
246       report_fatal_error("tiny code model is only supported on ELF");
247     return *CM;
248   }
249   // The default MCJIT memory managers make no guarantees about where they can
250   // find an executable page; JITed code needs to be able to refer to globals
251   // no matter how far away they are.
252   // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
253   // since with large code model LLVM generating 4 MOV instructions, and
254   // Windows doesn't support relocating these long branch (4 MOVs).
255   if (JIT && !TT.isOSWindows())
256     return CodeModel::Large;
257   return CodeModel::Small;
258 }
259 
260 /// Create an AArch64 architecture model.
261 ///
262 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
263                                            StringRef CPU, StringRef FS,
264                                            const TargetOptions &Options,
265                                            Optional<Reloc::Model> RM,
266                                            Optional<CodeModel::Model> CM,
267                                            CodeGenOpt::Level OL, bool JIT,
268                                            bool LittleEndian)
269     : LLVMTargetMachine(T,
270                         computeDataLayout(TT, Options.MCOptions, LittleEndian),
271                         TT, CPU, FS, Options, getEffectiveRelocModel(TT, RM),
272                         getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
273       TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
274   initAsmInfo();
275 
276   if (TT.isOSBinFormatMachO()) {
277     this->Options.TrapUnreachable = true;
278     this->Options.NoTrapAfterNoreturn = true;
279   }
280 
281   if (getMCAsmInfo()->usesWindowsCFI()) {
282     // Unwinding can get confused if the last instruction in an
283     // exception-handling region (function, funclet, try block, etc.)
284     // is a call.
285     //
286     // FIXME: We could elide the trap if the next instruction would be in
287     // the same region anyway.
288     this->Options.TrapUnreachable = true;
289   }
290 
291   // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
292   // MachO/CodeModel::Large, which GlobalISel does not support.
293   if (getOptLevel() <= EnableGlobalISelAtO &&
294       TT.getArch() != Triple::aarch64_32 &&
295       !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO())) {
296     setGlobalISel(true);
297     setGlobalISelAbort(GlobalISelAbortMode::Disable);
298   }
299 
300   // AArch64 supports the MachineOutliner.
301   setMachineOutliner(true);
302 
303   // AArch64 supports default outlining behaviour.
304   setSupportsDefaultOutlining(true);
305 }
306 
307 AArch64TargetMachine::~AArch64TargetMachine() = default;
308 
309 const AArch64Subtarget *
310 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
311   Attribute CPUAttr = F.getFnAttribute("target-cpu");
312   Attribute FSAttr = F.getFnAttribute("target-features");
313 
314   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
315                         ? CPUAttr.getValueAsString().str()
316                         : TargetCPU;
317   std::string FS = !FSAttr.hasAttribute(Attribute::None)
318                        ? FSAttr.getValueAsString().str()
319                        : TargetFS;
320 
321   auto &I = SubtargetMap[CPU + FS];
322   if (!I) {
323     // This needs to be done before we create a new subtarget since any
324     // creation will depend on the TM and the code generation flags on the
325     // function that reside in TargetOptions.
326     resetTargetOptions(F);
327     I = std::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
328                                             isLittle);
329   }
330   return I.get();
331 }
332 
333 void AArch64leTargetMachine::anchor() { }
334 
335 AArch64leTargetMachine::AArch64leTargetMachine(
336     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
337     const TargetOptions &Options, Optional<Reloc::Model> RM,
338     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
339     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
340 
341 void AArch64beTargetMachine::anchor() { }
342 
343 AArch64beTargetMachine::AArch64beTargetMachine(
344     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
345     const TargetOptions &Options, Optional<Reloc::Model> RM,
346     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
347     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
348 
349 namespace {
350 
351 /// AArch64 Code Generator Pass Configuration Options.
352 class AArch64PassConfig : public TargetPassConfig {
353 public:
354   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
355       : TargetPassConfig(TM, PM) {
356     if (TM.getOptLevel() != CodeGenOpt::None)
357       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
358   }
359 
360   AArch64TargetMachine &getAArch64TargetMachine() const {
361     return getTM<AArch64TargetMachine>();
362   }
363 
364   ScheduleDAGInstrs *
365   createMachineScheduler(MachineSchedContext *C) const override {
366     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
367     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
368     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
369     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
370     if (ST.hasFusion())
371       DAG->addMutation(createAArch64MacroFusionDAGMutation());
372     return DAG;
373   }
374 
375   ScheduleDAGInstrs *
376   createPostMachineScheduler(MachineSchedContext *C) const override {
377     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
378     if (ST.hasFusion()) {
379       // Run the Macro Fusion after RA again since literals are expanded from
380       // pseudos then (v. addPreSched2()).
381       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
382       DAG->addMutation(createAArch64MacroFusionDAGMutation());
383       return DAG;
384     }
385 
386     return nullptr;
387   }
388 
389   void addIRPasses()  override;
390   bool addPreISel() override;
391   bool addInstSelector() override;
392   bool addIRTranslator() override;
393   void addPreLegalizeMachineIR() override;
394   bool addLegalizeMachineIR() override;
395   bool addRegBankSelect() override;
396   void addPreGlobalInstructionSelect() override;
397   bool addGlobalInstructionSelect() override;
398   bool addILPOpts() override;
399   void addPreRegAlloc() override;
400   void addPostRegAlloc() override;
401   void addPreSched2() override;
402   void addPreEmitPass() override;
403 
404   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
405 };
406 
407 } // end anonymous namespace
408 
409 TargetTransformInfo
410 AArch64TargetMachine::getTargetTransformInfo(const Function &F) {
411   return TargetTransformInfo(AArch64TTIImpl(this, F));
412 }
413 
414 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
415   return new AArch64PassConfig(*this, PM);
416 }
417 
418 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
419   return getStandardCSEConfigForOpt(TM->getOptLevel());
420 }
421 
422 void AArch64PassConfig::addIRPasses() {
423   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
424   // ourselves.
425   addPass(createAtomicExpandPass());
426 
427   // Cmpxchg instructions are often used with a subsequent comparison to
428   // determine whether it succeeded. We can exploit existing control-flow in
429   // ldrex/strex loops to simplify this, but it needs tidying up.
430   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
431     addPass(createCFGSimplificationPass(1, true, true, false, true));
432 
433   // Run LoopDataPrefetch
434   //
435   // Run this before LSR to remove the multiplies involved in computing the
436   // pointer values N iterations ahead.
437   if (TM->getOptLevel() != CodeGenOpt::None) {
438     if (EnableLoopDataPrefetch)
439       addPass(createLoopDataPrefetchPass());
440     if (EnableFalkorHWPFFix)
441       addPass(createFalkorMarkStridedAccessesPass());
442   }
443 
444   TargetPassConfig::addIRPasses();
445 
446   // Match interleaved memory accesses to ldN/stN intrinsics.
447   if (TM->getOptLevel() != CodeGenOpt::None) {
448     addPass(createInterleavedLoadCombinePass());
449     addPass(createInterleavedAccessPass());
450   }
451 
452   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
453     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
454     // and lower a GEP with multiple indices to either arithmetic operations or
455     // multiple GEPs with single index.
456     addPass(createSeparateConstOffsetFromGEPPass(true));
457     // Call EarlyCSE pass to find and remove subexpressions in the lowered
458     // result.
459     addPass(createEarlyCSEPass());
460     // Do loop invariant code motion in case part of the lowered result is
461     // invariant.
462     addPass(createLICMPass());
463   }
464 
465   addPass(createAArch64StackTaggingPass(/* MergeInit = */ TM->getOptLevel() !=
466                                         CodeGenOpt::None));
467 
468   // Add Control Flow Guard checks.
469   if (TM->getTargetTriple().isOSWindows())
470     addPass(createCFGuardCheckPass());
471 }
472 
473 // Pass Pipeline Configuration
474 bool AArch64PassConfig::addPreISel() {
475   // Run promote constant before global merge, so that the promoted constants
476   // get a chance to be merged
477   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
478     addPass(createAArch64PromoteConstantPass());
479   // FIXME: On AArch64, this depends on the type.
480   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
481   // and the offset has to be a multiple of the related size in bytes.
482   if ((TM->getOptLevel() != CodeGenOpt::None &&
483        EnableGlobalMerge == cl::BOU_UNSET) ||
484       EnableGlobalMerge == cl::BOU_TRUE) {
485     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
486                                (EnableGlobalMerge == cl::BOU_UNSET);
487 
488     // Merging of extern globals is enabled by default on non-Mach-O as we
489     // expect it to be generally either beneficial or harmless. On Mach-O it
490     // is disabled as we emit the .subsections_via_symbols directive which
491     // means that merging extern globals is not safe.
492     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
493 
494     // FIXME: extern global merging is only enabled when we optimise for size
495     // because there are some regressions with it also enabled for performance.
496     if (!OnlyOptimizeForSize)
497       MergeExternalByDefault = false;
498 
499     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
500                                   MergeExternalByDefault));
501   }
502 
503   return false;
504 }
505 
506 bool AArch64PassConfig::addInstSelector() {
507   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
508 
509   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
510   // references to _TLS_MODULE_BASE_ as possible.
511   if (TM->getTargetTriple().isOSBinFormatELF() &&
512       getOptLevel() != CodeGenOpt::None)
513     addPass(createAArch64CleanupLocalDynamicTLSPass());
514 
515   return false;
516 }
517 
518 bool AArch64PassConfig::addIRTranslator() {
519   addPass(new IRTranslator());
520   return false;
521 }
522 
523 void AArch64PassConfig::addPreLegalizeMachineIR() {
524   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
525   addPass(createAArch64PreLegalizeCombiner(IsOptNone));
526 }
527 
528 bool AArch64PassConfig::addLegalizeMachineIR() {
529   addPass(new Legalizer());
530   return false;
531 }
532 
533 bool AArch64PassConfig::addRegBankSelect() {
534   addPass(new RegBankSelect());
535   return false;
536 }
537 
538 void AArch64PassConfig::addPreGlobalInstructionSelect() {
539   addPass(new Localizer());
540 }
541 
542 bool AArch64PassConfig::addGlobalInstructionSelect() {
543   addPass(new InstructionSelect());
544   return false;
545 }
546 
547 bool AArch64PassConfig::addILPOpts() {
548   if (EnableCondOpt)
549     addPass(createAArch64ConditionOptimizerPass());
550   if (EnableCCMP)
551     addPass(createAArch64ConditionalCompares());
552   if (EnableMCR)
553     addPass(&MachineCombinerID);
554   if (EnableCondBrTuning)
555     addPass(createAArch64CondBrTuning());
556   if (EnableEarlyIfConversion)
557     addPass(&EarlyIfConverterID);
558   if (EnableStPairSuppress)
559     addPass(createAArch64StorePairSuppressPass());
560   addPass(createAArch64SIMDInstrOptPass());
561   if (TM->getOptLevel() != CodeGenOpt::None)
562     addPass(createAArch64StackTaggingPreRAPass());
563   return true;
564 }
565 
566 void AArch64PassConfig::addPreRegAlloc() {
567   // Change dead register definitions to refer to the zero register.
568   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
569     addPass(createAArch64DeadRegisterDefinitions());
570 
571   // Use AdvSIMD scalar instructions whenever profitable.
572   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
573     addPass(createAArch64AdvSIMDScalar());
574     // The AdvSIMD pass may produce copies that can be rewritten to
575     // be register coaleascer friendly.
576     addPass(&PeepholeOptimizerID);
577   }
578 }
579 
580 void AArch64PassConfig::addPostRegAlloc() {
581   // Remove redundant copy instructions.
582   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
583     addPass(createAArch64RedundantCopyEliminationPass());
584 
585   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
586     // Improve performance for some FP/SIMD code for A57.
587     addPass(createAArch64A57FPLoadBalancing());
588 }
589 
590 void AArch64PassConfig::addPreSched2() {
591   // Expand some pseudo instructions to allow proper scheduling.
592   addPass(createAArch64ExpandPseudoPass());
593   // Use load/store pair instructions when possible.
594   if (TM->getOptLevel() != CodeGenOpt::None) {
595     if (EnableLoadStoreOpt)
596       addPass(createAArch64LoadStoreOptimizationPass());
597   }
598 
599   // The AArch64SpeculationHardeningPass destroys dominator tree and natural
600   // loop info, which is needed for the FalkorHWPFFixPass and also later on.
601   // Therefore, run the AArch64SpeculationHardeningPass before the
602   // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
603   // info.
604   addPass(createAArch64SpeculationHardeningPass());
605 
606   if (TM->getOptLevel() != CodeGenOpt::None) {
607     if (EnableFalkorHWPFFix)
608       addPass(createFalkorHWPFFixPass());
609   }
610 }
611 
612 void AArch64PassConfig::addPreEmitPass() {
613   // Machine Block Placement might have created new opportunities when run
614   // at O3, where the Tail Duplication Threshold is set to 4 instructions.
615   // Run the load/store optimizer once more.
616   if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
617     addPass(createAArch64LoadStoreOptimizationPass());
618 
619   if (EnableA53Fix835769)
620     addPass(createAArch64A53Fix835769());
621 
622   if (EnableBranchTargets)
623     addPass(createAArch64BranchTargetsPass());
624 
625   // Relax conditional branch instructions if they're otherwise out of
626   // range of their destination.
627   if (BranchRelaxation)
628     addPass(&BranchRelaxationPassID);
629 
630   // Identify valid longjmp targets for Windows Control Flow Guard.
631   if (TM->getTargetTriple().isOSWindows())
632     addPass(createCFGuardLongjmpPass());
633 
634   if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
635     addPass(createAArch64CompressJumpTablesPass());
636 
637   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
638       TM->getTargetTriple().isOSBinFormatMachO())
639     addPass(createAArch64CollectLOHPass());
640 }
641