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