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" LLVM_EXTERNAL_VISIBILITY 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       report_fatal_error(
240           "Only small, tiny and large code models are allowed on AArch64");
241     } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
242       report_fatal_error("tiny code model is only supported on ELF");
243     return *CM;
244   }
245   // The default MCJIT memory managers make no guarantees about where they can
246   // find an executable page; JITed code needs to be able to refer to globals
247   // no matter how far away they are.
248   // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
249   // since with large code model LLVM generating 4 MOV instructions, and
250   // Windows doesn't support relocating these long branch (4 MOVs).
251   if (JIT && !TT.isOSWindows())
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   if (this->Options.TLSSize == 0) // default
288     this->Options.TLSSize = 24;
289   if ((getCodeModel() == CodeModel::Small ||
290        getCodeModel() == CodeModel::Kernel) &&
291       this->Options.TLSSize > 32)
292     // for the small (and kernel) code model, the maximum TLS size is 4GiB
293     this->Options.TLSSize = 32;
294   else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
295     // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
296     this->Options.TLSSize = 24;
297 
298   // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
299   // MachO/CodeModel::Large, which GlobalISel does not support.
300   if (getOptLevel() <= EnableGlobalISelAtO &&
301       TT.getArch() != Triple::aarch64_32 &&
302       !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO())) {
303     setGlobalISel(true);
304     setGlobalISelAbort(GlobalISelAbortMode::Disable);
305   }
306 
307   // AArch64 supports the MachineOutliner.
308   setMachineOutliner(true);
309 
310   // AArch64 supports default outlining behaviour.
311   setSupportsDefaultOutlining(true);
312 }
313 
314 AArch64TargetMachine::~AArch64TargetMachine() = default;
315 
316 const AArch64Subtarget *
317 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
318   Attribute CPUAttr = F.getFnAttribute("target-cpu");
319   Attribute FSAttr = F.getFnAttribute("target-features");
320 
321   std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
322                         ? CPUAttr.getValueAsString().str()
323                         : TargetCPU;
324   std::string FS = !FSAttr.hasAttribute(Attribute::None)
325                        ? FSAttr.getValueAsString().str()
326                        : TargetFS;
327 
328   auto &I = SubtargetMap[CPU + FS];
329   if (!I) {
330     // This needs to be done before we create a new subtarget since any
331     // creation will depend on the TM and the code generation flags on the
332     // function that reside in TargetOptions.
333     resetTargetOptions(F);
334     I = std::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
335                                             isLittle);
336   }
337   return I.get();
338 }
339 
340 void AArch64leTargetMachine::anchor() { }
341 
342 AArch64leTargetMachine::AArch64leTargetMachine(
343     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
344     const TargetOptions &Options, Optional<Reloc::Model> RM,
345     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
346     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
347 
348 void AArch64beTargetMachine::anchor() { }
349 
350 AArch64beTargetMachine::AArch64beTargetMachine(
351     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
352     const TargetOptions &Options, Optional<Reloc::Model> RM,
353     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
354     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
355 
356 namespace {
357 
358 /// AArch64 Code Generator Pass Configuration Options.
359 class AArch64PassConfig : public TargetPassConfig {
360 public:
361   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
362       : TargetPassConfig(TM, PM) {
363     if (TM.getOptLevel() != CodeGenOpt::None)
364       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
365   }
366 
367   AArch64TargetMachine &getAArch64TargetMachine() const {
368     return getTM<AArch64TargetMachine>();
369   }
370 
371   ScheduleDAGInstrs *
372   createMachineScheduler(MachineSchedContext *C) const override {
373     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
374     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
375     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
376     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
377     if (ST.hasFusion())
378       DAG->addMutation(createAArch64MacroFusionDAGMutation());
379     return DAG;
380   }
381 
382   ScheduleDAGInstrs *
383   createPostMachineScheduler(MachineSchedContext *C) const override {
384     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
385     if (ST.hasFusion()) {
386       // Run the Macro Fusion after RA again since literals are expanded from
387       // pseudos then (v. addPreSched2()).
388       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
389       DAG->addMutation(createAArch64MacroFusionDAGMutation());
390       return DAG;
391     }
392 
393     return nullptr;
394   }
395 
396   void addIRPasses()  override;
397   bool addPreISel() override;
398   bool addInstSelector() override;
399   bool addIRTranslator() override;
400   void addPreLegalizeMachineIR() override;
401   bool addLegalizeMachineIR() override;
402   bool addRegBankSelect() override;
403   void addPreGlobalInstructionSelect() override;
404   bool addGlobalInstructionSelect() override;
405   bool addILPOpts() override;
406   void addPreRegAlloc() override;
407   void addPostRegAlloc() override;
408   void addPreSched2() override;
409   void addPreEmitPass() override;
410 
411   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
412 };
413 
414 } // end anonymous namespace
415 
416 TargetTransformInfo
417 AArch64TargetMachine::getTargetTransformInfo(const Function &F) {
418   return TargetTransformInfo(AArch64TTIImpl(this, F));
419 }
420 
421 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
422   return new AArch64PassConfig(*this, PM);
423 }
424 
425 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
426   return getStandardCSEConfigForOpt(TM->getOptLevel());
427 }
428 
429 void AArch64PassConfig::addIRPasses() {
430   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
431   // ourselves.
432   addPass(createAtomicExpandPass());
433 
434   // Cmpxchg instructions are often used with a subsequent comparison to
435   // determine whether it succeeded. We can exploit existing control-flow in
436   // ldrex/strex loops to simplify this, but it needs tidying up.
437   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
438     addPass(createCFGSimplificationPass(1, true, true, false, true));
439 
440   // Run LoopDataPrefetch
441   //
442   // Run this before LSR to remove the multiplies involved in computing the
443   // pointer values N iterations ahead.
444   if (TM->getOptLevel() != CodeGenOpt::None) {
445     if (EnableLoopDataPrefetch)
446       addPass(createLoopDataPrefetchPass());
447     if (EnableFalkorHWPFFix)
448       addPass(createFalkorMarkStridedAccessesPass());
449   }
450 
451   TargetPassConfig::addIRPasses();
452 
453   // Match interleaved memory accesses to ldN/stN intrinsics.
454   if (TM->getOptLevel() != CodeGenOpt::None) {
455     addPass(createInterleavedLoadCombinePass());
456     addPass(createInterleavedAccessPass());
457   }
458 
459   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
460     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
461     // and lower a GEP with multiple indices to either arithmetic operations or
462     // multiple GEPs with single index.
463     addPass(createSeparateConstOffsetFromGEPPass(true));
464     // Call EarlyCSE pass to find and remove subexpressions in the lowered
465     // result.
466     addPass(createEarlyCSEPass());
467     // Do loop invariant code motion in case part of the lowered result is
468     // invariant.
469     addPass(createLICMPass());
470   }
471 
472   addPass(createAArch64StackTaggingPass(/* MergeInit = */ TM->getOptLevel() !=
473                                         CodeGenOpt::None));
474 
475   // Add Control Flow Guard checks.
476   if (TM->getTargetTriple().isOSWindows())
477     addPass(createCFGuardCheckPass());
478 }
479 
480 // Pass Pipeline Configuration
481 bool AArch64PassConfig::addPreISel() {
482   // Run promote constant before global merge, so that the promoted constants
483   // get a chance to be merged
484   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
485     addPass(createAArch64PromoteConstantPass());
486   // FIXME: On AArch64, this depends on the type.
487   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
488   // and the offset has to be a multiple of the related size in bytes.
489   if ((TM->getOptLevel() != CodeGenOpt::None &&
490        EnableGlobalMerge == cl::BOU_UNSET) ||
491       EnableGlobalMerge == cl::BOU_TRUE) {
492     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
493                                (EnableGlobalMerge == cl::BOU_UNSET);
494 
495     // Merging of extern globals is enabled by default on non-Mach-O as we
496     // expect it to be generally either beneficial or harmless. On Mach-O it
497     // is disabled as we emit the .subsections_via_symbols directive which
498     // means that merging extern globals is not safe.
499     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
500 
501     // FIXME: extern global merging is only enabled when we optimise for size
502     // because there are some regressions with it also enabled for performance.
503     if (!OnlyOptimizeForSize)
504       MergeExternalByDefault = false;
505 
506     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
507                                   MergeExternalByDefault));
508   }
509 
510   return false;
511 }
512 
513 bool AArch64PassConfig::addInstSelector() {
514   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
515 
516   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
517   // references to _TLS_MODULE_BASE_ as possible.
518   if (TM->getTargetTriple().isOSBinFormatELF() &&
519       getOptLevel() != CodeGenOpt::None)
520     addPass(createAArch64CleanupLocalDynamicTLSPass());
521 
522   return false;
523 }
524 
525 bool AArch64PassConfig::addIRTranslator() {
526   addPass(new IRTranslator());
527   return false;
528 }
529 
530 void AArch64PassConfig::addPreLegalizeMachineIR() {
531   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
532   addPass(createAArch64PreLegalizeCombiner(IsOptNone));
533 }
534 
535 bool AArch64PassConfig::addLegalizeMachineIR() {
536   addPass(new Legalizer());
537   return false;
538 }
539 
540 bool AArch64PassConfig::addRegBankSelect() {
541   addPass(new RegBankSelect());
542   return false;
543 }
544 
545 void AArch64PassConfig::addPreGlobalInstructionSelect() {
546   addPass(new Localizer());
547 }
548 
549 bool AArch64PassConfig::addGlobalInstructionSelect() {
550   addPass(new InstructionSelect());
551   return false;
552 }
553 
554 bool AArch64PassConfig::addILPOpts() {
555   if (EnableCondOpt)
556     addPass(createAArch64ConditionOptimizerPass());
557   if (EnableCCMP)
558     addPass(createAArch64ConditionalCompares());
559   if (EnableMCR)
560     addPass(&MachineCombinerID);
561   if (EnableCondBrTuning)
562     addPass(createAArch64CondBrTuning());
563   if (EnableEarlyIfConversion)
564     addPass(&EarlyIfConverterID);
565   if (EnableStPairSuppress)
566     addPass(createAArch64StorePairSuppressPass());
567   addPass(createAArch64SIMDInstrOptPass());
568   if (TM->getOptLevel() != CodeGenOpt::None)
569     addPass(createAArch64StackTaggingPreRAPass());
570   return true;
571 }
572 
573 void AArch64PassConfig::addPreRegAlloc() {
574   // Change dead register definitions to refer to the zero register.
575   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
576     addPass(createAArch64DeadRegisterDefinitions());
577 
578   // Use AdvSIMD scalar instructions whenever profitable.
579   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
580     addPass(createAArch64AdvSIMDScalar());
581     // The AdvSIMD pass may produce copies that can be rewritten to
582     // be register coalescer friendly.
583     addPass(&PeepholeOptimizerID);
584   }
585 }
586 
587 void AArch64PassConfig::addPostRegAlloc() {
588   // Remove redundant copy instructions.
589   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
590     addPass(createAArch64RedundantCopyEliminationPass());
591 
592   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
593     // Improve performance for some FP/SIMD code for A57.
594     addPass(createAArch64A57FPLoadBalancing());
595 }
596 
597 void AArch64PassConfig::addPreSched2() {
598   // Expand some pseudo instructions to allow proper scheduling.
599   addPass(createAArch64ExpandPseudoPass());
600   // Use load/store pair instructions when possible.
601   if (TM->getOptLevel() != CodeGenOpt::None) {
602     if (EnableLoadStoreOpt)
603       addPass(createAArch64LoadStoreOptimizationPass());
604   }
605 
606   // The AArch64SpeculationHardeningPass destroys dominator tree and natural
607   // loop info, which is needed for the FalkorHWPFFixPass and also later on.
608   // Therefore, run the AArch64SpeculationHardeningPass before the
609   // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
610   // info.
611   addPass(createAArch64SpeculationHardeningPass());
612 
613   if (TM->getOptLevel() != CodeGenOpt::None) {
614     if (EnableFalkorHWPFFix)
615       addPass(createFalkorHWPFFixPass());
616   }
617 }
618 
619 void AArch64PassConfig::addPreEmitPass() {
620   // Machine Block Placement might have created new opportunities when run
621   // at O3, where the Tail Duplication Threshold is set to 4 instructions.
622   // Run the load/store optimizer once more.
623   if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
624     addPass(createAArch64LoadStoreOptimizationPass());
625 
626   if (EnableA53Fix835769)
627     addPass(createAArch64A53Fix835769());
628 
629   if (EnableBranchTargets)
630     addPass(createAArch64BranchTargetsPass());
631 
632   // Relax conditional branch instructions if they're otherwise out of
633   // range of their destination.
634   if (BranchRelaxation)
635     addPass(&BranchRelaxationPassID);
636 
637   // Identify valid longjmp targets for Windows Control Flow Guard.
638   if (TM->getTargetTriple().isOSWindows())
639     addPass(createCFGuardLongjmpPass());
640 
641   if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
642     addPass(createAArch64CompressJumpTablesPass());
643 
644   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
645       TM->getTargetTriple().isOSBinFormatMachO())
646     addPass(createAArch64CollectLOHPass());
647 
648   // SVE bundles move prefixes with destructive operations.
649   addPass(createUnpackMachineBundles(nullptr));
650 }
651