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