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 "AArch64MachineFunctionInfo.h"
15 #include "AArch64MacroFusion.h"
16 #include "AArch64Subtarget.h"
17 #include "AArch64TargetObjectFile.h"
18 #include "AArch64TargetTransformInfo.h"
19 #include "MCTargetDesc/AArch64MCTargetDesc.h"
20 #include "TargetInfo/AArch64TargetInfo.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/CodeGen/CSEConfigBase.h"
25 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
26 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
27 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
28 #include "llvm/CodeGen/GlobalISel/LoadStoreOpt.h"
29 #include "llvm/CodeGen/GlobalISel/Localizer.h"
30 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
31 #include "llvm/CodeGen/MIRParser/MIParser.h"
32 #include "llvm/CodeGen/MachineScheduler.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/CodeGen/TargetPassConfig.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCTargetOptions.h"
40 #include "llvm/MC/TargetRegistry.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Target/TargetLoweringObjectFile.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Transforms/CFGuard.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include <memory>
49 #include <string>
50 
51 using namespace llvm;
52 
53 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
54                                 cl::desc("Enable the CCMP formation pass"),
55                                 cl::init(true), cl::Hidden);
56 
57 static cl::opt<bool>
58     EnableCondBrTuning("aarch64-enable-cond-br-tune",
59                        cl::desc("Enable the conditional branch tuning pass"),
60                        cl::init(true), cl::Hidden);
61 
62 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
63                                cl::desc("Enable the machine combiner pass"),
64                                cl::init(true), cl::Hidden);
65 
66 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
67                                           cl::desc("Suppress STP for AArch64"),
68                                           cl::init(true), cl::Hidden);
69 
70 static cl::opt<bool> EnableAdvSIMDScalar(
71     "aarch64-enable-simd-scalar",
72     cl::desc("Enable use of AdvSIMD scalar integer instructions"),
73     cl::init(false), cl::Hidden);
74 
75 static cl::opt<bool>
76     EnablePromoteConstant("aarch64-enable-promote-const",
77                           cl::desc("Enable the promote constant pass"),
78                           cl::init(true), cl::Hidden);
79 
80 static cl::opt<bool> EnableCollectLOH(
81     "aarch64-enable-collect-loh",
82     cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
83     cl::init(true), cl::Hidden);
84 
85 static cl::opt<bool>
86     EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
87                                   cl::desc("Enable the pass that removes dead"
88                                            " definitons and replaces stores to"
89                                            " them with stores to the zero"
90                                            " register"),
91                                   cl::init(true));
92 
93 static cl::opt<bool> EnableRedundantCopyElimination(
94     "aarch64-enable-copyelim",
95     cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
96     cl::Hidden);
97 
98 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
99                                         cl::desc("Enable the load/store pair"
100                                                  " optimization pass"),
101                                         cl::init(true), cl::Hidden);
102 
103 static cl::opt<bool> EnableAtomicTidy(
104     "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
105     cl::desc("Run SimplifyCFG after expanding atomic operations"
106              " to make use of cmpxchg flow-based information"),
107     cl::init(true));
108 
109 static cl::opt<bool>
110 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
111                         cl::desc("Run early if-conversion"),
112                         cl::init(true));
113 
114 static cl::opt<bool>
115     EnableCondOpt("aarch64-enable-condopt",
116                   cl::desc("Enable the condition optimizer pass"),
117                   cl::init(true), cl::Hidden);
118 
119 static cl::opt<bool>
120 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
121                 cl::desc("Work around Cortex-A53 erratum 835769"),
122                 cl::init(false));
123 
124 static cl::opt<bool>
125     EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
126                  cl::desc("Enable optimizations on complex GEPs"),
127                  cl::init(false));
128 
129 static cl::opt<bool>
130     BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
131                      cl::desc("Relax out of range conditional branches"));
132 
133 static cl::opt<bool> EnableCompressJumpTables(
134     "aarch64-enable-compress-jump-tables", cl::Hidden, cl::init(true),
135     cl::desc("Use smallest entry possible for jump tables"));
136 
137 // FIXME: Unify control over GlobalMerge.
138 static cl::opt<cl::boolOrDefault>
139     EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
140                       cl::desc("Enable the global merge pass"));
141 
142 static cl::opt<bool>
143     EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
144                            cl::desc("Enable the loop data prefetch pass"),
145                            cl::init(true));
146 
147 static cl::opt<int> EnableGlobalISelAtO(
148     "aarch64-enable-global-isel-at-O", cl::Hidden,
149     cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
150     cl::init(0));
151 
152 static cl::opt<bool>
153     EnableSVEIntrinsicOpts("aarch64-enable-sve-intrinsic-opts", cl::Hidden,
154                            cl::desc("Enable SVE intrinsic opts"),
155                            cl::init(true));
156 
157 static cl::opt<bool> EnableFalkorHWPFFix("aarch64-enable-falkor-hwpf-fix",
158                                          cl::init(true), cl::Hidden);
159 
160 static cl::opt<bool>
161     EnableBranchTargets("aarch64-enable-branch-targets", cl::Hidden,
162                         cl::desc("Enable the AArch64 branch target pass"),
163                         cl::init(true));
164 
165 static cl::opt<unsigned> SVEVectorBitsMaxOpt(
166     "aarch64-sve-vector-bits-max",
167     cl::desc("Assume SVE vector registers are at most this big, "
168              "with zero meaning no maximum size is assumed."),
169     cl::init(0), cl::Hidden);
170 
171 static cl::opt<unsigned> SVEVectorBitsMinOpt(
172     "aarch64-sve-vector-bits-min",
173     cl::desc("Assume SVE vector registers are at least this big, "
174              "with zero meaning no minimum size is assumed."),
175     cl::init(0), cl::Hidden);
176 
177 extern cl::opt<bool> EnableHomogeneousPrologEpilog;
178 
179 static cl::opt<bool> EnableGISelLoadStoreOptPreLegal(
180     "aarch64-enable-gisel-ldst-prelegal",
181     cl::desc("Enable GlobalISel's pre-legalizer load/store optimization pass"),
182     cl::init(true), cl::Hidden);
183 
184 static cl::opt<bool> EnableGISelLoadStoreOptPostLegal(
185     "aarch64-enable-gisel-ldst-postlegal",
186     cl::desc("Enable GlobalISel's post-legalizer load/store optimization pass"),
187     cl::init(false), cl::Hidden);
188 
189 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAArch64Target() {
190   // Register the target.
191   RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
192   RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
193   RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
194   RegisterTargetMachine<AArch64leTargetMachine> W(getTheARM64_32Target());
195   RegisterTargetMachine<AArch64leTargetMachine> V(getTheAArch64_32Target());
196   auto PR = PassRegistry::getPassRegistry();
197   initializeGlobalISel(*PR);
198   initializeAArch64A53Fix835769Pass(*PR);
199   initializeAArch64A57FPLoadBalancingPass(*PR);
200   initializeAArch64AdvSIMDScalarPass(*PR);
201   initializeAArch64BranchTargetsPass(*PR);
202   initializeAArch64CollectLOHPass(*PR);
203   initializeAArch64CompressJumpTablesPass(*PR);
204   initializeAArch64ConditionalComparesPass(*PR);
205   initializeAArch64ConditionOptimizerPass(*PR);
206   initializeAArch64DeadRegisterDefinitionsPass(*PR);
207   initializeAArch64ExpandPseudoPass(*PR);
208   initializeAArch64LoadStoreOptPass(*PR);
209   initializeAArch64MIPeepholeOptPass(*PR);
210   initializeAArch64SIMDInstrOptPass(*PR);
211   initializeAArch64O0PreLegalizerCombinerPass(*PR);
212   initializeAArch64PreLegalizerCombinerPass(*PR);
213   initializeAArch64PostLegalizerCombinerPass(*PR);
214   initializeAArch64PostLegalizerLoweringPass(*PR);
215   initializeAArch64PostSelectOptimizePass(*PR);
216   initializeAArch64PromoteConstantPass(*PR);
217   initializeAArch64RedundantCopyEliminationPass(*PR);
218   initializeAArch64StorePairSuppressPass(*PR);
219   initializeFalkorHWPFFixPass(*PR);
220   initializeFalkorMarkStridedAccessesLegacyPass(*PR);
221   initializeLDTLSCleanupPass(*PR);
222   initializeSVEIntrinsicOptsPass(*PR);
223   initializeAArch64SpeculationHardeningPass(*PR);
224   initializeAArch64SLSHardeningPass(*PR);
225   initializeAArch64StackTaggingPass(*PR);
226   initializeAArch64StackTaggingPreRAPass(*PR);
227   initializeAArch64LowerHomogeneousPrologEpilogPass(*PR);
228 }
229 
230 //===----------------------------------------------------------------------===//
231 // AArch64 Lowering public interface.
232 //===----------------------------------------------------------------------===//
233 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
234   if (TT.isOSBinFormatMachO())
235     return std::make_unique<AArch64_MachoTargetObjectFile>();
236   if (TT.isOSBinFormatCOFF())
237     return std::make_unique<AArch64_COFFTargetObjectFile>();
238 
239   return std::make_unique<AArch64_ELFTargetObjectFile>();
240 }
241 
242 // Helper function to build a DataLayout string
243 static std::string computeDataLayout(const Triple &TT,
244                                      const MCTargetOptions &Options,
245                                      bool LittleEndian) {
246   if (TT.isOSBinFormatMachO()) {
247     if (TT.getArch() == Triple::aarch64_32)
248       return "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128";
249     return "e-m:o-i64:64-i128:128-n32:64-S128";
250   }
251   if (TT.isOSBinFormatCOFF())
252     return "e-m:w-p:64:64-i32:32-i64:64-i128:128-n32:64-S128";
253   std::string Endian = LittleEndian ? "e" : "E";
254   std::string Ptr32 = TT.getEnvironment() == Triple::GNUILP32 ? "-p:32:32" : "";
255   return Endian + "-m:e" + Ptr32 +
256          "-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
257 }
258 
259 static StringRef computeDefaultCPU(const Triple &TT, StringRef CPU) {
260   if (CPU.empty() && TT.isArm64e())
261     return "apple-a12";
262   return CPU;
263 }
264 
265 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
266                                            Optional<Reloc::Model> RM) {
267   // AArch64 Darwin and Windows are always PIC.
268   if (TT.isOSDarwin() || TT.isOSWindows())
269     return Reloc::PIC_;
270   // On ELF platforms the default static relocation model has a smart enough
271   // linker to cope with referencing external symbols defined in a shared
272   // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
273   if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
274     return Reloc::Static;
275   return *RM;
276 }
277 
278 static CodeModel::Model
279 getEffectiveAArch64CodeModel(const Triple &TT, Optional<CodeModel::Model> CM,
280                              bool JIT) {
281   if (CM) {
282     if (*CM != CodeModel::Small && *CM != CodeModel::Tiny &&
283         *CM != CodeModel::Large) {
284       report_fatal_error(
285           "Only small, tiny and large code models are allowed on AArch64");
286     } else if (*CM == CodeModel::Tiny && !TT.isOSBinFormatELF())
287       report_fatal_error("tiny code model is only supported on ELF");
288     return *CM;
289   }
290   // The default MCJIT memory managers make no guarantees about where they can
291   // find an executable page; JITed code needs to be able to refer to globals
292   // no matter how far away they are.
293   // We should set the CodeModel::Small for Windows ARM64 in JIT mode,
294   // since with large code model LLVM generating 4 MOV instructions, and
295   // Windows doesn't support relocating these long branch (4 MOVs).
296   if (JIT && !TT.isOSWindows())
297     return CodeModel::Large;
298   return CodeModel::Small;
299 }
300 
301 /// Create an AArch64 architecture model.
302 ///
303 AArch64TargetMachine::AArch64TargetMachine(const Target &T, const Triple &TT,
304                                            StringRef CPU, StringRef FS,
305                                            const TargetOptions &Options,
306                                            Optional<Reloc::Model> RM,
307                                            Optional<CodeModel::Model> CM,
308                                            CodeGenOpt::Level OL, bool JIT,
309                                            bool LittleEndian)
310     : LLVMTargetMachine(T,
311                         computeDataLayout(TT, Options.MCOptions, LittleEndian),
312                         TT, computeDefaultCPU(TT, CPU), FS, Options,
313                         getEffectiveRelocModel(TT, RM),
314                         getEffectiveAArch64CodeModel(TT, CM, JIT), OL),
315       TLOF(createTLOF(getTargetTriple())), isLittle(LittleEndian) {
316   initAsmInfo();
317 
318   if (TT.isOSBinFormatMachO()) {
319     this->Options.TrapUnreachable = true;
320     this->Options.NoTrapAfterNoreturn = true;
321   }
322 
323   if (getMCAsmInfo()->usesWindowsCFI()) {
324     // Unwinding can get confused if the last instruction in an
325     // exception-handling region (function, funclet, try block, etc.)
326     // is a call.
327     //
328     // FIXME: We could elide the trap if the next instruction would be in
329     // the same region anyway.
330     this->Options.TrapUnreachable = true;
331   }
332 
333   if (this->Options.TLSSize == 0) // default
334     this->Options.TLSSize = 24;
335   if ((getCodeModel() == CodeModel::Small ||
336        getCodeModel() == CodeModel::Kernel) &&
337       this->Options.TLSSize > 32)
338     // for the small (and kernel) code model, the maximum TLS size is 4GiB
339     this->Options.TLSSize = 32;
340   else if (getCodeModel() == CodeModel::Tiny && this->Options.TLSSize > 24)
341     // for the tiny code model, the maximum TLS size is 1MiB (< 16MiB)
342     this->Options.TLSSize = 24;
343 
344   // Enable GlobalISel at or below EnableGlobalISelAt0, unless this is
345   // MachO/CodeModel::Large, which GlobalISel does not support.
346   if (getOptLevel() <= EnableGlobalISelAtO &&
347       TT.getArch() != Triple::aarch64_32 &&
348       TT.getEnvironment() != Triple::GNUILP32 &&
349       !(getCodeModel() == CodeModel::Large && TT.isOSBinFormatMachO())) {
350     setGlobalISel(true);
351     setGlobalISelAbort(GlobalISelAbortMode::Disable);
352   }
353 
354   // AArch64 supports the MachineOutliner.
355   setMachineOutliner(true);
356 
357   // AArch64 supports default outlining behaviour.
358   setSupportsDefaultOutlining(true);
359 
360   // AArch64 supports the debug entry values.
361   setSupportsDebugEntryValues(true);
362 }
363 
364 AArch64TargetMachine::~AArch64TargetMachine() = default;
365 
366 const AArch64Subtarget *
367 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
368   Attribute CPUAttr = F.getFnAttribute("target-cpu");
369   Attribute TuneAttr = F.getFnAttribute("tune-cpu");
370   Attribute FSAttr = F.getFnAttribute("target-features");
371 
372   std::string CPU =
373       CPUAttr.isValid() ? CPUAttr.getValueAsString().str() : TargetCPU;
374   std::string TuneCPU =
375       TuneAttr.isValid() ? TuneAttr.getValueAsString().str() : CPU;
376   std::string FS =
377       FSAttr.isValid() ? FSAttr.getValueAsString().str() : TargetFS;
378 
379   SmallString<512> Key;
380 
381   unsigned MinSVEVectorSize = 0;
382   unsigned MaxSVEVectorSize = 0;
383   Attribute VScaleRangeAttr = F.getFnAttribute(Attribute::VScaleRange);
384   if (VScaleRangeAttr.isValid()) {
385     Optional<unsigned> VScaleMax = VScaleRangeAttr.getVScaleRangeMax();
386     MinSVEVectorSize = VScaleRangeAttr.getVScaleRangeMin() * 128;
387     MaxSVEVectorSize = VScaleMax ? VScaleMax.getValue() * 128 : 0;
388   } else {
389     MinSVEVectorSize = SVEVectorBitsMinOpt;
390     MaxSVEVectorSize = SVEVectorBitsMaxOpt;
391   }
392 
393   assert(MinSVEVectorSize % 128 == 0 &&
394          "SVE requires vector length in multiples of 128!");
395   assert(MaxSVEVectorSize % 128 == 0 &&
396          "SVE requires vector length in multiples of 128!");
397   assert((MaxSVEVectorSize >= MinSVEVectorSize || MaxSVEVectorSize == 0) &&
398          "Minimum SVE vector size should not be larger than its maximum!");
399 
400   // Sanitize user input in case of no asserts
401   if (MaxSVEVectorSize == 0)
402     MinSVEVectorSize = (MinSVEVectorSize / 128) * 128;
403   else {
404     MinSVEVectorSize =
405         (std::min(MinSVEVectorSize, MaxSVEVectorSize) / 128) * 128;
406     MaxSVEVectorSize =
407         (std::max(MinSVEVectorSize, MaxSVEVectorSize) / 128) * 128;
408   }
409 
410   Key += "SVEMin";
411   Key += std::to_string(MinSVEVectorSize);
412   Key += "SVEMax";
413   Key += std::to_string(MaxSVEVectorSize);
414   Key += CPU;
415   Key += TuneCPU;
416   Key += FS;
417 
418   auto &I = SubtargetMap[Key];
419   if (!I) {
420     // This needs to be done before we create a new subtarget since any
421     // creation will depend on the TM and the code generation flags on the
422     // function that reside in TargetOptions.
423     resetTargetOptions(F);
424     I = std::make_unique<AArch64Subtarget>(TargetTriple, CPU, TuneCPU, FS,
425                                            *this, isLittle, MinSVEVectorSize,
426                                            MaxSVEVectorSize);
427   }
428   return I.get();
429 }
430 
431 void AArch64leTargetMachine::anchor() { }
432 
433 AArch64leTargetMachine::AArch64leTargetMachine(
434     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
435     const TargetOptions &Options, Optional<Reloc::Model> RM,
436     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
437     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, true) {}
438 
439 void AArch64beTargetMachine::anchor() { }
440 
441 AArch64beTargetMachine::AArch64beTargetMachine(
442     const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
443     const TargetOptions &Options, Optional<Reloc::Model> RM,
444     Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT)
445     : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, JIT, false) {}
446 
447 namespace {
448 
449 /// AArch64 Code Generator Pass Configuration Options.
450 class AArch64PassConfig : public TargetPassConfig {
451 public:
452   AArch64PassConfig(AArch64TargetMachine &TM, PassManagerBase &PM)
453       : TargetPassConfig(TM, PM) {
454     if (TM.getOptLevel() != CodeGenOpt::None)
455       substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
456   }
457 
458   AArch64TargetMachine &getAArch64TargetMachine() const {
459     return getTM<AArch64TargetMachine>();
460   }
461 
462   ScheduleDAGInstrs *
463   createMachineScheduler(MachineSchedContext *C) const override {
464     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
465     ScheduleDAGMILive *DAG = createGenericSchedLive(C);
466     DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
467     DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
468     if (ST.hasFusion())
469       DAG->addMutation(createAArch64MacroFusionDAGMutation());
470     return DAG;
471   }
472 
473   ScheduleDAGInstrs *
474   createPostMachineScheduler(MachineSchedContext *C) const override {
475     const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
476     if (ST.hasFusion()) {
477       // Run the Macro Fusion after RA again since literals are expanded from
478       // pseudos then (v. addPreSched2()).
479       ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
480       DAG->addMutation(createAArch64MacroFusionDAGMutation());
481       return DAG;
482     }
483 
484     return nullptr;
485   }
486 
487   void addIRPasses()  override;
488   bool addPreISel() override;
489   void addCodeGenPrepare() override;
490   bool addInstSelector() override;
491   bool addIRTranslator() override;
492   void addPreLegalizeMachineIR() override;
493   bool addLegalizeMachineIR() override;
494   void addPreRegBankSelect() override;
495   bool addRegBankSelect() override;
496   void addPreGlobalInstructionSelect() override;
497   bool addGlobalInstructionSelect() override;
498   void addMachineSSAOptimization() override;
499   bool addILPOpts() override;
500   void addPreRegAlloc() override;
501   void addPostRegAlloc() override;
502   void addPreSched2() override;
503   void addPreEmitPass() override;
504   void addPreEmitPass2() override;
505 
506   std::unique_ptr<CSEConfigBase> getCSEConfig() const override;
507 };
508 
509 } // end anonymous namespace
510 
511 TargetTransformInfo
512 AArch64TargetMachine::getTargetTransformInfo(const Function &F) {
513   return TargetTransformInfo(AArch64TTIImpl(this, F));
514 }
515 
516 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
517   return new AArch64PassConfig(*this, PM);
518 }
519 
520 std::unique_ptr<CSEConfigBase> AArch64PassConfig::getCSEConfig() const {
521   return getStandardCSEConfigForOpt(TM->getOptLevel());
522 }
523 
524 void AArch64PassConfig::addIRPasses() {
525   // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
526   // ourselves.
527   addPass(createAtomicExpandPass());
528 
529   // Expand any SVE vector library calls that we can't code generate directly.
530   if (EnableSVEIntrinsicOpts && TM->getOptLevel() == CodeGenOpt::Aggressive)
531     addPass(createSVEIntrinsicOptsPass());
532 
533   // Cmpxchg instructions are often used with a subsequent comparison to
534   // determine whether it succeeded. We can exploit existing control-flow in
535   // ldrex/strex loops to simplify this, but it needs tidying up.
536   if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
537     addPass(createCFGSimplificationPass(SimplifyCFGOptions()
538                                             .forwardSwitchCondToPhi(true)
539                                             .convertSwitchToLookupTable(true)
540                                             .needCanonicalLoops(false)
541                                             .hoistCommonInsts(true)
542                                             .sinkCommonInsts(true)));
543 
544   // Run LoopDataPrefetch
545   //
546   // Run this before LSR to remove the multiplies involved in computing the
547   // pointer values N iterations ahead.
548   if (TM->getOptLevel() != CodeGenOpt::None) {
549     if (EnableLoopDataPrefetch)
550       addPass(createLoopDataPrefetchPass());
551     if (EnableFalkorHWPFFix)
552       addPass(createFalkorMarkStridedAccessesPass());
553   }
554 
555   TargetPassConfig::addIRPasses();
556 
557   addPass(createAArch64StackTaggingPass(
558       /*IsOptNone=*/TM->getOptLevel() == CodeGenOpt::None));
559 
560   // Match interleaved memory accesses to ldN/stN intrinsics.
561   if (TM->getOptLevel() != CodeGenOpt::None) {
562     addPass(createInterleavedLoadCombinePass());
563     addPass(createInterleavedAccessPass());
564   }
565 
566   if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
567     // Call SeparateConstOffsetFromGEP pass to extract constants within indices
568     // and lower a GEP with multiple indices to either arithmetic operations or
569     // multiple GEPs with single index.
570     addPass(createSeparateConstOffsetFromGEPPass(true));
571     // Call EarlyCSE pass to find and remove subexpressions in the lowered
572     // result.
573     addPass(createEarlyCSEPass());
574     // Do loop invariant code motion in case part of the lowered result is
575     // invariant.
576     addPass(createLICMPass());
577   }
578 
579   // Add Control Flow Guard checks.
580   if (TM->getTargetTriple().isOSWindows())
581     addPass(createCFGuardCheckPass());
582 }
583 
584 // Pass Pipeline Configuration
585 bool AArch64PassConfig::addPreISel() {
586   // Run promote constant before global merge, so that the promoted constants
587   // get a chance to be merged
588   if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
589     addPass(createAArch64PromoteConstantPass());
590   // FIXME: On AArch64, this depends on the type.
591   // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
592   // and the offset has to be a multiple of the related size in bytes.
593   if ((TM->getOptLevel() != CodeGenOpt::None &&
594        EnableGlobalMerge == cl::BOU_UNSET) ||
595       EnableGlobalMerge == cl::BOU_TRUE) {
596     bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
597                                (EnableGlobalMerge == cl::BOU_UNSET);
598 
599     // Merging of extern globals is enabled by default on non-Mach-O as we
600     // expect it to be generally either beneficial or harmless. On Mach-O it
601     // is disabled as we emit the .subsections_via_symbols directive which
602     // means that merging extern globals is not safe.
603     bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
604 
605     // FIXME: extern global merging is only enabled when we optimise for size
606     // because there are some regressions with it also enabled for performance.
607     if (!OnlyOptimizeForSize)
608       MergeExternalByDefault = false;
609 
610     addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize,
611                                   MergeExternalByDefault));
612   }
613 
614   return false;
615 }
616 
617 void AArch64PassConfig::addCodeGenPrepare() {
618   if (getOptLevel() != CodeGenOpt::None)
619     addPass(createTypePromotionPass());
620   TargetPassConfig::addCodeGenPrepare();
621 }
622 
623 bool AArch64PassConfig::addInstSelector() {
624   addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
625 
626   // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
627   // references to _TLS_MODULE_BASE_ as possible.
628   if (TM->getTargetTriple().isOSBinFormatELF() &&
629       getOptLevel() != CodeGenOpt::None)
630     addPass(createAArch64CleanupLocalDynamicTLSPass());
631 
632   return false;
633 }
634 
635 bool AArch64PassConfig::addIRTranslator() {
636   addPass(new IRTranslator(getOptLevel()));
637   return false;
638 }
639 
640 void AArch64PassConfig::addPreLegalizeMachineIR() {
641   if (getOptLevel() == CodeGenOpt::None)
642     addPass(createAArch64O0PreLegalizerCombiner());
643   else {
644     addPass(createAArch64PreLegalizerCombiner());
645     if (EnableGISelLoadStoreOptPreLegal)
646       addPass(new LoadStoreOpt());
647   }
648 }
649 
650 bool AArch64PassConfig::addLegalizeMachineIR() {
651   addPass(new Legalizer());
652   return false;
653 }
654 
655 void AArch64PassConfig::addPreRegBankSelect() {
656   bool IsOptNone = getOptLevel() == CodeGenOpt::None;
657   if (!IsOptNone) {
658     addPass(createAArch64PostLegalizerCombiner(IsOptNone));
659     if (EnableGISelLoadStoreOptPostLegal)
660       addPass(new LoadStoreOpt());
661   }
662   addPass(createAArch64PostLegalizerLowering());
663 }
664 
665 bool AArch64PassConfig::addRegBankSelect() {
666   addPass(new RegBankSelect());
667   return false;
668 }
669 
670 void AArch64PassConfig::addPreGlobalInstructionSelect() {
671   addPass(new Localizer());
672 }
673 
674 bool AArch64PassConfig::addGlobalInstructionSelect() {
675   addPass(new InstructionSelect(getOptLevel()));
676   if (getOptLevel() != CodeGenOpt::None)
677     addPass(createAArch64PostSelectOptimize());
678   return false;
679 }
680 
681 void AArch64PassConfig::addMachineSSAOptimization() {
682   // Run default MachineSSAOptimization first.
683   TargetPassConfig::addMachineSSAOptimization();
684 
685   if (TM->getOptLevel() != CodeGenOpt::None)
686     addPass(createAArch64MIPeepholeOptPass());
687 }
688 
689 bool AArch64PassConfig::addILPOpts() {
690   if (EnableCondOpt)
691     addPass(createAArch64ConditionOptimizerPass());
692   if (EnableCCMP)
693     addPass(createAArch64ConditionalCompares());
694   if (EnableMCR)
695     addPass(&MachineCombinerID);
696   if (EnableCondBrTuning)
697     addPass(createAArch64CondBrTuning());
698   if (EnableEarlyIfConversion)
699     addPass(&EarlyIfConverterID);
700   if (EnableStPairSuppress)
701     addPass(createAArch64StorePairSuppressPass());
702   addPass(createAArch64SIMDInstrOptPass());
703   if (TM->getOptLevel() != CodeGenOpt::None)
704     addPass(createAArch64StackTaggingPreRAPass());
705   return true;
706 }
707 
708 void AArch64PassConfig::addPreRegAlloc() {
709   // Change dead register definitions to refer to the zero register.
710   if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
711     addPass(createAArch64DeadRegisterDefinitions());
712 
713   // Use AdvSIMD scalar instructions whenever profitable.
714   if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
715     addPass(createAArch64AdvSIMDScalar());
716     // The AdvSIMD pass may produce copies that can be rewritten to
717     // be register coalescer friendly.
718     addPass(&PeepholeOptimizerID);
719   }
720 }
721 
722 void AArch64PassConfig::addPostRegAlloc() {
723   // Remove redundant copy instructions.
724   if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
725     addPass(createAArch64RedundantCopyEliminationPass());
726 
727   if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
728     // Improve performance for some FP/SIMD code for A57.
729     addPass(createAArch64A57FPLoadBalancing());
730 }
731 
732 void AArch64PassConfig::addPreSched2() {
733   // Lower homogeneous frame instructions
734   if (EnableHomogeneousPrologEpilog)
735     addPass(createAArch64LowerHomogeneousPrologEpilogPass());
736   // Expand some pseudo instructions to allow proper scheduling.
737   addPass(createAArch64ExpandPseudoPass());
738   // Use load/store pair instructions when possible.
739   if (TM->getOptLevel() != CodeGenOpt::None) {
740     if (EnableLoadStoreOpt)
741       addPass(createAArch64LoadStoreOptimizationPass());
742   }
743 
744   // The AArch64SpeculationHardeningPass destroys dominator tree and natural
745   // loop info, which is needed for the FalkorHWPFFixPass and also later on.
746   // Therefore, run the AArch64SpeculationHardeningPass before the
747   // FalkorHWPFFixPass to avoid recomputing dominator tree and natural loop
748   // info.
749   addPass(createAArch64SpeculationHardeningPass());
750 
751   addPass(createAArch64IndirectThunks());
752   addPass(createAArch64SLSHardeningPass());
753 
754   if (TM->getOptLevel() != CodeGenOpt::None) {
755     if (EnableFalkorHWPFFix)
756       addPass(createFalkorHWPFFixPass());
757   }
758 }
759 
760 void AArch64PassConfig::addPreEmitPass() {
761   // Machine Block Placement might have created new opportunities when run
762   // at O3, where the Tail Duplication Threshold is set to 4 instructions.
763   // Run the load/store optimizer once more.
764   if (TM->getOptLevel() >= CodeGenOpt::Aggressive && EnableLoadStoreOpt)
765     addPass(createAArch64LoadStoreOptimizationPass());
766 
767   if (EnableA53Fix835769)
768     addPass(createAArch64A53Fix835769());
769 
770   if (EnableBranchTargets)
771     addPass(createAArch64BranchTargetsPass());
772 
773   // Relax conditional branch instructions if they're otherwise out of
774   // range of their destination.
775   if (BranchRelaxation)
776     addPass(&BranchRelaxationPassID);
777 
778   if (TM->getTargetTriple().isOSWindows()) {
779     // Identify valid longjmp targets for Windows Control Flow Guard.
780     addPass(createCFGuardLongjmpPass());
781     // Identify valid eh continuation targets for Windows EHCont Guard.
782     addPass(createEHContGuardCatchretPass());
783   }
784 
785   if (TM->getOptLevel() != CodeGenOpt::None && EnableCompressJumpTables)
786     addPass(createAArch64CompressJumpTablesPass());
787 
788   if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
789       TM->getTargetTriple().isOSBinFormatMachO())
790     addPass(createAArch64CollectLOHPass());
791 }
792 
793 void AArch64PassConfig::addPreEmitPass2() {
794   // SVE bundles move prefixes with destructive operations. BLR_RVMARKER pseudo
795   // instructions are lowered to bundles as well.
796   addPass(createUnpackMachineBundles(nullptr));
797 }
798 
799 yaml::MachineFunctionInfo *
800 AArch64TargetMachine::createDefaultFuncInfoYAML() const {
801   return new yaml::AArch64FunctionInfo();
802 }
803 
804 yaml::MachineFunctionInfo *
805 AArch64TargetMachine::convertFuncInfoToYAML(const MachineFunction &MF) const {
806   const auto *MFI = MF.getInfo<AArch64FunctionInfo>();
807   return new yaml::AArch64FunctionInfo(*MFI);
808 }
809 
810 bool AArch64TargetMachine::parseMachineFunctionInfo(
811     const yaml::MachineFunctionInfo &MFI, PerFunctionMIParsingState &PFS,
812     SMDiagnostic &Error, SMRange &SourceRange) const {
813   const auto &YamlMFI =
814       reinterpret_cast<const yaml::AArch64FunctionInfo &>(MFI);
815   MachineFunction &MF = PFS.MF;
816   MF.getInfo<AArch64FunctionInfo>()->initializeBaseYamlFields(YamlMFI);
817   return false;
818 }
819