1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 //===----------------------------------------------------------------------===//
14 #include "AArch64MacroFusion.h"
15 #include "AArch64Subtarget.h"
16 #include "AArch64TargetMachine.h"
17 #include "AArch64TargetObjectFile.h"
18 #include "AArch64TargetTransformInfo.h"
19 #include "MCTargetDesc/AArch64MCTargetDesc.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
24 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
25 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
26 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
27 #include "llvm/CodeGen/MachineScheduler.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/TargetPassConfig.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/MC/MCTargetOptions.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Support/CodeGen.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/Transforms/Scalar.h"
45 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
46 cl::desc("Enable the CCMP formation pass"),
47 cl::init(true), cl::Hidden);
49 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
50 cl::desc("Enable the machine combiner pass"),
51 cl::init(true), cl::Hidden);
53 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
54 cl::desc("Suppress STP for AArch64"),
55 cl::init(true), cl::Hidden);
57 static cl::opt<bool> EnableAdvSIMDScalar(
58 "aarch64-enable-simd-scalar",
59 cl::desc("Enable use of AdvSIMD scalar integer instructions"),
60 cl::init(false), cl::Hidden);
63 EnablePromoteConstant("aarch64-enable-promote-const",
64 cl::desc("Enable the promote constant pass"),
65 cl::init(true), cl::Hidden);
67 static cl::opt<bool> EnableCollectLOH(
68 "aarch64-enable-collect-loh",
69 cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
70 cl::init(true), cl::Hidden);
73 EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
74 cl::desc("Enable the pass that removes dead"
75 " definitons and replaces stores to"
76 " them with stores to the zero"
80 static cl::opt<bool> EnableRedundantCopyElimination(
81 "aarch64-enable-copyelim",
82 cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
85 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
86 cl::desc("Enable the load/store pair"
87 " optimization pass"),
88 cl::init(true), cl::Hidden);
90 static cl::opt<bool> EnableAtomicTidy(
91 "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
92 cl::desc("Run SimplifyCFG after expanding atomic operations"
93 " to make use of cmpxchg flow-based information"),
97 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
98 cl::desc("Run early if-conversion"),
102 EnableCondOpt("aarch64-enable-condopt",
103 cl::desc("Enable the condition optimizer pass"),
104 cl::init(true), cl::Hidden);
107 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
108 cl::desc("Work around Cortex-A53 erratum 835769"),
112 EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
113 cl::desc("Enable optimizations on complex GEPs"),
117 BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
118 cl::desc("Relax out of range conditional branches"));
120 // FIXME: Unify control over GlobalMerge.
121 static cl::opt<cl::boolOrDefault>
122 EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
123 cl::desc("Enable the global merge pass"));
126 EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
127 cl::desc("Enable the loop data prefetch pass"),
130 static cl::opt<int> EnableGlobalISelAtO(
131 "aarch64-enable-global-isel-at-O", cl::Hidden,
132 cl::desc("Enable GlobalISel at or below an opt level (-1 to disable)"),
135 extern "C" void LLVMInitializeAArch64Target() {
136 // Register the target.
137 RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
138 RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
139 RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
140 auto PR = PassRegistry::getPassRegistry();
141 initializeGlobalISel(*PR);
142 initializeAArch64A53Fix835769Pass(*PR);
143 initializeAArch64A57FPLoadBalancingPass(*PR);
144 initializeAArch64AdvSIMDScalarPass(*PR);
145 initializeAArch64CollectLOHPass(*PR);
146 initializeAArch64ConditionalComparesPass(*PR);
147 initializeAArch64ConditionOptimizerPass(*PR);
148 initializeAArch64DeadRegisterDefinitionsPass(*PR);
149 initializeAArch64ExpandPseudoPass(*PR);
150 initializeAArch64LoadStoreOptPass(*PR);
151 initializeAArch64VectorByElementOptPass(*PR);
152 initializeAArch64PromoteConstantPass(*PR);
153 initializeAArch64RedundantCopyEliminationPass(*PR);
154 initializeAArch64StorePairSuppressPass(*PR);
155 initializeLDTLSCleanupPass(*PR);
158 //===----------------------------------------------------------------------===//
159 // AArch64 Lowering public interface.
160 //===----------------------------------------------------------------------===//
161 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
162 if (TT.isOSBinFormatMachO())
163 return llvm::make_unique<AArch64_MachoTargetObjectFile>();
165 return llvm::make_unique<AArch64_ELFTargetObjectFile>();
168 // Helper function to build a DataLayout string
169 static std::string computeDataLayout(const Triple &TT,
170 const MCTargetOptions &Options,
172 if (Options.getABIName() == "ilp32")
173 return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
174 if (TT.isOSBinFormatMachO())
175 return "e-m:o-i64:64-i128:128-n32:64-S128";
177 return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
178 return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
181 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
182 Optional<Reloc::Model> RM) {
183 // AArch64 Darwin is always PIC.
186 // On ELF platforms the default static relocation model has a smart enough
187 // linker to cope with referencing external symbols defined in a shared
188 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
189 if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
190 return Reloc::Static;
194 /// Create an AArch64 architecture model.
196 AArch64TargetMachine::AArch64TargetMachine(
197 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
198 const TargetOptions &Options, Optional<Reloc::Model> RM,
199 CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian)
200 // This nested ternary is horrible, but DL needs to be properly
201 // initialized before TLInfo is constructed.
202 : LLVMTargetMachine(T, computeDataLayout(TT, Options.MCOptions,
204 TT, CPU, FS, Options,
205 getEffectiveRelocModel(TT, RM), CM, OL),
206 TLOF(createTLOF(getTargetTriple())),
207 isLittle(LittleEndian) {
211 AArch64TargetMachine::~AArch64TargetMachine() = default;
213 const AArch64Subtarget *
214 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
215 Attribute CPUAttr = F.getFnAttribute("target-cpu");
216 Attribute FSAttr = F.getFnAttribute("target-features");
217 bool ForCodeSize = F.optForSize();
219 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
220 ? CPUAttr.getValueAsString().str()
222 std::string FS = !FSAttr.hasAttribute(Attribute::None)
223 ? FSAttr.getValueAsString().str()
225 std::string ForCodeSizeStr =
226 std::string(ForCodeSize ? "+" : "-") + "forcodesize";
228 auto &I = SubtargetMap[CPU + FS + ForCodeSizeStr];
230 // This needs to be done before we create a new subtarget since any
231 // creation will depend on the TM and the code generation flags on the
232 // function that reside in TargetOptions.
233 resetTargetOptions(F);
234 I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
235 isLittle, ForCodeSize);
240 void AArch64leTargetMachine::anchor() { }
242 AArch64leTargetMachine::AArch64leTargetMachine(
243 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
244 const TargetOptions &Options, Optional<Reloc::Model> RM,
245 CodeModel::Model CM, CodeGenOpt::Level OL)
246 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
248 void AArch64beTargetMachine::anchor() { }
250 AArch64beTargetMachine::AArch64beTargetMachine(
251 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
252 const TargetOptions &Options, Optional<Reloc::Model> RM,
253 CodeModel::Model CM, CodeGenOpt::Level OL)
254 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
258 /// AArch64 Code Generator Pass Configuration Options.
259 class AArch64PassConfig : public TargetPassConfig {
261 AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
262 : TargetPassConfig(TM, PM) {
263 if (TM->getOptLevel() != CodeGenOpt::None)
264 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
267 AArch64TargetMachine &getAArch64TargetMachine() const {
268 return getTM<AArch64TargetMachine>();
272 createMachineScheduler(MachineSchedContext *C) const override {
273 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
274 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
275 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
276 DAG->addMutation(createAArch64MacroFusionDAGMutation());
281 createPostMachineScheduler(MachineSchedContext *C) const override {
282 const AArch64Subtarget &ST = C->MF->getSubtarget<AArch64Subtarget>();
283 if (ST.hasFuseLiterals()) {
284 // Run the Macro Fusion after RA again since literals are expanded from
285 // pseudos then (v. addPreSched2()).
286 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
287 DAG->addMutation(createAArch64MacroFusionDAGMutation());
294 void addIRPasses() override;
295 bool addPreISel() override;
296 bool addInstSelector() override;
297 #ifdef LLVM_BUILD_GLOBAL_ISEL
298 bool addIRTranslator() override;
299 bool addLegalizeMachineIR() override;
300 bool addRegBankSelect() override;
301 bool addGlobalInstructionSelect() override;
303 bool addILPOpts() override;
304 void addPreRegAlloc() override;
305 void addPostRegAlloc() override;
306 void addPreSched2() override;
307 void addPreEmitPass() override;
309 bool isGlobalISelEnabled() const override;
312 } // end anonymous namespace
314 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
315 return TargetIRAnalysis([this](const Function &F) {
316 return TargetTransformInfo(AArch64TTIImpl(this, F));
320 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
321 return new AArch64PassConfig(this, PM);
324 void AArch64PassConfig::addIRPasses() {
325 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
327 addPass(createAtomicExpandPass(TM));
329 // Cmpxchg instructions are often used with a subsequent comparison to
330 // determine whether it succeeded. We can exploit existing control-flow in
331 // ldrex/strex loops to simplify this, but it needs tidying up.
332 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
333 addPass(createCFGSimplificationPass());
335 // Run LoopDataPrefetch
337 // Run this before LSR to remove the multiplies involved in computing the
338 // pointer values N iterations ahead.
339 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
340 addPass(createLoopDataPrefetchPass());
342 TargetPassConfig::addIRPasses();
344 // Match interleaved memory accesses to ldN/stN intrinsics.
345 if (TM->getOptLevel() != CodeGenOpt::None)
346 addPass(createInterleavedAccessPass(TM));
348 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
349 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
350 // and lower a GEP with multiple indices to either arithmetic operations or
351 // multiple GEPs with single index.
352 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
353 // Call EarlyCSE pass to find and remove subexpressions in the lowered
355 addPass(createEarlyCSEPass());
356 // Do loop invariant code motion in case part of the lowered result is
358 addPass(createLICMPass());
362 // Pass Pipeline Configuration
363 bool AArch64PassConfig::addPreISel() {
364 // Run promote constant before global merge, so that the promoted constants
365 // get a chance to be merged
366 if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
367 addPass(createAArch64PromoteConstantPass());
368 // FIXME: On AArch64, this depends on the type.
369 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
370 // and the offset has to be a multiple of the related size in bytes.
371 if ((TM->getOptLevel() != CodeGenOpt::None &&
372 EnableGlobalMerge == cl::BOU_UNSET) ||
373 EnableGlobalMerge == cl::BOU_TRUE) {
374 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
375 (EnableGlobalMerge == cl::BOU_UNSET);
376 addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
382 bool AArch64PassConfig::addInstSelector() {
383 addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
385 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
386 // references to _TLS_MODULE_BASE_ as possible.
387 if (TM->getTargetTriple().isOSBinFormatELF() &&
388 getOptLevel() != CodeGenOpt::None)
389 addPass(createAArch64CleanupLocalDynamicTLSPass());
394 #ifdef LLVM_BUILD_GLOBAL_ISEL
395 bool AArch64PassConfig::addIRTranslator() {
396 addPass(new IRTranslator());
400 bool AArch64PassConfig::addLegalizeMachineIR() {
401 addPass(new Legalizer());
405 bool AArch64PassConfig::addRegBankSelect() {
406 addPass(new RegBankSelect());
410 bool AArch64PassConfig::addGlobalInstructionSelect() {
411 addPass(new InstructionSelect());
416 bool AArch64PassConfig::isGlobalISelEnabled() const {
417 return TM->getOptLevel() <= EnableGlobalISelAtO;
420 bool AArch64PassConfig::addILPOpts() {
422 addPass(createAArch64ConditionOptimizerPass());
424 addPass(createAArch64ConditionalCompares());
426 addPass(&MachineCombinerID);
427 if (EnableEarlyIfConversion)
428 addPass(&EarlyIfConverterID);
429 if (EnableStPairSuppress)
430 addPass(createAArch64StorePairSuppressPass());
431 addPass(createAArch64VectorByElementOptPass());
435 void AArch64PassConfig::addPreRegAlloc() {
436 // Change dead register definitions to refer to the zero register.
437 if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
438 addPass(createAArch64DeadRegisterDefinitions());
440 // Use AdvSIMD scalar instructions whenever profitable.
441 if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
442 addPass(createAArch64AdvSIMDScalar());
443 // The AdvSIMD pass may produce copies that can be rewritten to
444 // be register coaleascer friendly.
445 addPass(&PeepholeOptimizerID);
449 void AArch64PassConfig::addPostRegAlloc() {
450 // Remove redundant copy instructions.
451 if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
452 addPass(createAArch64RedundantCopyEliminationPass());
454 if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
455 // Improve performance for some FP/SIMD code for A57.
456 addPass(createAArch64A57FPLoadBalancing());
459 void AArch64PassConfig::addPreSched2() {
460 // Expand some pseudo instructions to allow proper scheduling.
461 addPass(createAArch64ExpandPseudoPass());
462 // Use load/store pair instructions when possible.
463 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
464 addPass(createAArch64LoadStoreOptimizationPass());
467 void AArch64PassConfig::addPreEmitPass() {
468 if (EnableA53Fix835769)
469 addPass(createAArch64A53Fix835769());
470 // Relax conditional branch instructions if they're otherwise out of
471 // range of their destination.
472 if (BranchRelaxation)
473 addPass(&BranchRelaxationPassID);
475 if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
476 TM->getTargetTriple().isOSBinFormatMachO())
477 addPass(createAArch64CollectLOHPass());