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