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 "AArch64CallLowering.h"
15 #include "AArch64InstructionSelector.h"
16 #include "AArch64LegalizerInfo.h"
17 #include "AArch64RegisterBankInfo.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "AArch64TargetTransformInfo.h"
22 #include "MCTargetDesc/AArch64MCTargetDesc.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/TargetTransformInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
29 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
30 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
31 #include "llvm/CodeGen/MachineScheduler.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/CodeGen/TargetPassConfig.h"
34 #include "llvm/IR/Attributes.h"
35 #include "llvm/IR/Function.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/Scalar.h"
49 static cl::opt<bool> EnableCCMP("aarch64-enable-ccmp",
50 cl::desc("Enable the CCMP formation pass"),
51 cl::init(true), cl::Hidden);
53 static cl::opt<bool> EnableMCR("aarch64-enable-mcr",
54 cl::desc("Enable the machine combiner pass"),
55 cl::init(true), cl::Hidden);
57 static cl::opt<bool> EnableStPairSuppress("aarch64-enable-stp-suppress",
58 cl::desc("Suppress STP for AArch64"),
59 cl::init(true), cl::Hidden);
61 static cl::opt<bool> EnableAdvSIMDScalar(
62 "aarch64-enable-simd-scalar",
63 cl::desc("Enable use of AdvSIMD scalar integer instructions"),
64 cl::init(false), cl::Hidden);
67 EnablePromoteConstant("aarch64-enable-promote-const",
68 cl::desc("Enable the promote constant pass"),
69 cl::init(true), cl::Hidden);
71 static cl::opt<bool> EnableCollectLOH(
72 "aarch64-enable-collect-loh",
73 cl::desc("Enable the pass that emits the linker optimization hints (LOH)"),
74 cl::init(true), cl::Hidden);
77 EnableDeadRegisterElimination("aarch64-enable-dead-defs", cl::Hidden,
78 cl::desc("Enable the pass that removes dead"
79 " definitons and replaces stores to"
80 " them with stores to the zero"
84 static cl::opt<bool> EnableRedundantCopyElimination(
85 "aarch64-enable-copyelim",
86 cl::desc("Enable the redundant copy elimination pass"), cl::init(true),
89 static cl::opt<bool> EnableLoadStoreOpt("aarch64-enable-ldst-opt",
90 cl::desc("Enable the load/store pair"
91 " optimization pass"),
92 cl::init(true), cl::Hidden);
94 static cl::opt<bool> EnableAtomicTidy(
95 "aarch64-enable-atomic-cfg-tidy", cl::Hidden,
96 cl::desc("Run SimplifyCFG after expanding atomic operations"
97 " to make use of cmpxchg flow-based information"),
101 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden,
102 cl::desc("Run early if-conversion"),
106 EnableCondOpt("aarch64-enable-condopt",
107 cl::desc("Enable the condition optimizer pass"),
108 cl::init(true), cl::Hidden);
111 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden,
112 cl::desc("Work around Cortex-A53 erratum 835769"),
116 EnableAddressTypePromotion("aarch64-enable-type-promotion", cl::Hidden,
117 cl::desc("Enable the type promotion pass"),
121 EnableGEPOpt("aarch64-enable-gep-opt", cl::Hidden,
122 cl::desc("Enable optimizations on complex GEPs"),
126 BranchRelaxation("aarch64-enable-branch-relax", cl::Hidden, cl::init(true),
127 cl::desc("Relax out of range conditional branches"));
129 // FIXME: Unify control over GlobalMerge.
130 static cl::opt<cl::boolOrDefault>
131 EnableGlobalMerge("aarch64-enable-global-merge", cl::Hidden,
132 cl::desc("Enable the global merge pass"));
135 EnableLoopDataPrefetch("aarch64-enable-loop-data-prefetch", cl::Hidden,
136 cl::desc("Enable the loop data prefetch pass"),
139 extern "C" void LLVMInitializeAArch64Target() {
140 // Register the target.
141 RegisterTargetMachine<AArch64leTargetMachine> X(getTheAArch64leTarget());
142 RegisterTargetMachine<AArch64beTargetMachine> Y(getTheAArch64beTarget());
143 RegisterTargetMachine<AArch64leTargetMachine> Z(getTheARM64Target());
144 auto PR = PassRegistry::getPassRegistry();
145 initializeGlobalISel(*PR);
146 initializeAArch64A53Fix835769Pass(*PR);
147 initializeAArch64A57FPLoadBalancingPass(*PR);
148 initializeAArch64AddressTypePromotionPass(*PR);
149 initializeAArch64AdvSIMDScalarPass(*PR);
150 initializeAArch64CollectLOHPass(*PR);
151 initializeAArch64ConditionalComparesPass(*PR);
152 initializeAArch64ConditionOptimizerPass(*PR);
153 initializeAArch64DeadRegisterDefinitionsPass(*PR);
154 initializeAArch64ExpandPseudoPass(*PR);
155 initializeAArch64LoadStoreOptPass(*PR);
156 initializeAArch64VectorByElementOptPass(*PR);
157 initializeAArch64PromoteConstantPass(*PR);
158 initializeAArch64RedundantCopyEliminationPass(*PR);
159 initializeAArch64StorePairSuppressPass(*PR);
160 initializeLDTLSCleanupPass(*PR);
163 //===----------------------------------------------------------------------===//
164 // AArch64 Lowering public interface.
165 //===----------------------------------------------------------------------===//
166 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
167 if (TT.isOSBinFormatMachO())
168 return llvm::make_unique<AArch64_MachoTargetObjectFile>();
170 return llvm::make_unique<AArch64_ELFTargetObjectFile>();
173 // Helper function to build a DataLayout string
174 static std::string computeDataLayout(const Triple &TT,
175 const MCTargetOptions &Options,
177 if (Options.getABIName() == "ilp32")
178 return "e-m:e-p:32:32-i8:8-i16:16-i64:64-S128";
179 if (TT.isOSBinFormatMachO())
180 return "e-m:o-i64:64-i128:128-n32:64-S128";
182 return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
183 return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128";
186 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
187 Optional<Reloc::Model> RM) {
188 // AArch64 Darwin is always PIC.
191 // On ELF platforms the default static relocation model has a smart enough
192 // linker to cope with referencing external symbols defined in a shared
193 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC.
194 if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC)
195 return Reloc::Static;
199 /// Create an AArch64 architecture model.
201 AArch64TargetMachine::AArch64TargetMachine(
202 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
203 const TargetOptions &Options, Optional<Reloc::Model> RM,
204 CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian)
205 // This nested ternary is horrible, but DL needs to be properly
206 // initialized before TLInfo is constructed.
207 : LLVMTargetMachine(T, computeDataLayout(TT, Options.MCOptions,
209 TT, CPU, FS, Options,
210 getEffectiveRelocModel(TT, RM), CM, OL),
211 TLOF(createTLOF(getTargetTriple())),
212 isLittle(LittleEndian) {
216 AArch64TargetMachine::~AArch64TargetMachine() = default;
218 #ifdef LLVM_BUILD_GLOBAL_ISEL
221 struct AArch64GISelActualAccessor : public GISelAccessor {
222 std::unique_ptr<CallLowering> CallLoweringInfo;
223 std::unique_ptr<InstructionSelector> InstSelector;
224 std::unique_ptr<LegalizerInfo> Legalizer;
225 std::unique_ptr<RegisterBankInfo> RegBankInfo;
227 const CallLowering *getCallLowering() const override {
228 return CallLoweringInfo.get();
231 const InstructionSelector *getInstructionSelector() const override {
232 return InstSelector.get();
235 const LegalizerInfo *getLegalizerInfo() const override {
236 return Legalizer.get();
239 const RegisterBankInfo *getRegBankInfo() const override {
240 return RegBankInfo.get();
244 } // end anonymous namespace
247 const AArch64Subtarget *
248 AArch64TargetMachine::getSubtargetImpl(const Function &F) const {
249 Attribute CPUAttr = F.getFnAttribute("target-cpu");
250 Attribute FSAttr = F.getFnAttribute("target-features");
252 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
253 ? CPUAttr.getValueAsString().str()
255 std::string FS = !FSAttr.hasAttribute(Attribute::None)
256 ? FSAttr.getValueAsString().str()
259 auto &I = SubtargetMap[CPU + FS];
261 // This needs to be done before we create a new subtarget since any
262 // creation will depend on the TM and the code generation flags on the
263 // function that reside in TargetOptions.
264 resetTargetOptions(F);
265 I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this,
267 #ifndef LLVM_BUILD_GLOBAL_ISEL
268 GISelAccessor *GISel = new GISelAccessor();
270 AArch64GISelActualAccessor *GISel =
271 new AArch64GISelActualAccessor();
272 GISel->CallLoweringInfo.reset(
273 new AArch64CallLowering(*I->getTargetLowering()));
274 GISel->Legalizer.reset(new AArch64LegalizerInfo());
276 auto *RBI = new AArch64RegisterBankInfo(*I->getRegisterInfo());
278 // FIXME: At this point, we can't rely on Subtarget having RBI.
279 // It's awkward to mix passing RBI and the Subtarget; should we pass
281 GISel->InstSelector.reset(new AArch64InstructionSelector(*this, *I, *RBI));
283 GISel->RegBankInfo.reset(RBI);
285 I->setGISelAccessor(*GISel);
290 void AArch64leTargetMachine::anchor() { }
292 AArch64leTargetMachine::AArch64leTargetMachine(
293 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
294 const TargetOptions &Options, Optional<Reloc::Model> RM,
295 CodeModel::Model CM, CodeGenOpt::Level OL)
296 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
298 void AArch64beTargetMachine::anchor() { }
300 AArch64beTargetMachine::AArch64beTargetMachine(
301 const Target &T, const Triple &TT, StringRef CPU, StringRef FS,
302 const TargetOptions &Options, Optional<Reloc::Model> RM,
303 CodeModel::Model CM, CodeGenOpt::Level OL)
304 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
308 /// AArch64 Code Generator Pass Configuration Options.
309 class AArch64PassConfig : public TargetPassConfig {
311 AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM)
312 : TargetPassConfig(TM, PM) {
313 if (TM->getOptLevel() != CodeGenOpt::None)
314 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
317 AArch64TargetMachine &getAArch64TargetMachine() const {
318 return getTM<AArch64TargetMachine>();
322 createMachineScheduler(MachineSchedContext *C) const override {
323 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
324 DAG->addMutation(createLoadClusterDAGMutation(DAG->TII, DAG->TRI));
325 DAG->addMutation(createStoreClusterDAGMutation(DAG->TII, DAG->TRI));
326 DAG->addMutation(createMacroFusionDAGMutation(DAG->TII));
330 void addIRPasses() override;
331 bool addPreISel() override;
332 bool addInstSelector() override;
333 #ifdef LLVM_BUILD_GLOBAL_ISEL
334 bool addIRTranslator() override;
335 bool addLegalizeMachineIR() override;
336 bool addRegBankSelect() override;
337 bool addGlobalInstructionSelect() override;
339 bool addILPOpts() override;
340 void addPreRegAlloc() override;
341 void addPostRegAlloc() override;
342 void addPreSched2() override;
343 void addPreEmitPass() override;
346 } // end anonymous namespace
348 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() {
349 return TargetIRAnalysis([this](const Function &F) {
350 return TargetTransformInfo(AArch64TTIImpl(this, F));
354 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) {
355 return new AArch64PassConfig(this, PM);
358 void AArch64PassConfig::addIRPasses() {
359 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg
361 addPass(createAtomicExpandPass(TM));
363 // Cmpxchg instructions are often used with a subsequent comparison to
364 // determine whether it succeeded. We can exploit existing control-flow in
365 // ldrex/strex loops to simplify this, but it needs tidying up.
366 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
367 addPass(createCFGSimplificationPass());
369 // Run LoopDataPrefetch
371 // Run this before LSR to remove the multiplies involved in computing the
372 // pointer values N iterations ahead.
373 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch)
374 addPass(createLoopDataPrefetchPass());
376 TargetPassConfig::addIRPasses();
378 // Match interleaved memory accesses to ldN/stN intrinsics.
379 if (TM->getOptLevel() != CodeGenOpt::None)
380 addPass(createInterleavedAccessPass(TM));
382 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) {
383 // Call SeparateConstOffsetFromGEP pass to extract constants within indices
384 // and lower a GEP with multiple indices to either arithmetic operations or
385 // multiple GEPs with single index.
386 addPass(createSeparateConstOffsetFromGEPPass(TM, true));
387 // Call EarlyCSE pass to find and remove subexpressions in the lowered
389 addPass(createEarlyCSEPass());
390 // Do loop invariant code motion in case part of the lowered result is
392 addPass(createLICMPass());
396 // Pass Pipeline Configuration
397 bool AArch64PassConfig::addPreISel() {
398 // Run promote constant before global merge, so that the promoted constants
399 // get a chance to be merged
400 if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant)
401 addPass(createAArch64PromoteConstantPass());
402 // FIXME: On AArch64, this depends on the type.
403 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
404 // and the offset has to be a multiple of the related size in bytes.
405 if ((TM->getOptLevel() != CodeGenOpt::None &&
406 EnableGlobalMerge == cl::BOU_UNSET) ||
407 EnableGlobalMerge == cl::BOU_TRUE) {
408 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
409 (EnableGlobalMerge == cl::BOU_UNSET);
410 addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize));
413 if (TM->getOptLevel() != CodeGenOpt::None && EnableAddressTypePromotion)
414 addPass(createAArch64AddressTypePromotionPass());
419 bool AArch64PassConfig::addInstSelector() {
420 addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel()));
422 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many
423 // references to _TLS_MODULE_BASE_ as possible.
424 if (TM->getTargetTriple().isOSBinFormatELF() &&
425 getOptLevel() != CodeGenOpt::None)
426 addPass(createAArch64CleanupLocalDynamicTLSPass());
431 #ifdef LLVM_BUILD_GLOBAL_ISEL
432 bool AArch64PassConfig::addIRTranslator() {
433 addPass(new IRTranslator());
437 bool AArch64PassConfig::addLegalizeMachineIR() {
438 addPass(new Legalizer());
442 bool AArch64PassConfig::addRegBankSelect() {
443 addPass(new RegBankSelect());
447 bool AArch64PassConfig::addGlobalInstructionSelect() {
448 addPass(new InstructionSelect());
453 bool AArch64PassConfig::addILPOpts() {
455 addPass(createAArch64ConditionOptimizerPass());
457 addPass(createAArch64ConditionalCompares());
459 addPass(&MachineCombinerID);
460 if (EnableEarlyIfConversion)
461 addPass(&EarlyIfConverterID);
462 if (EnableStPairSuppress)
463 addPass(createAArch64StorePairSuppressPass());
464 addPass(createAArch64VectorByElementOptPass());
468 void AArch64PassConfig::addPreRegAlloc() {
469 // Change dead register definitions to refer to the zero register.
470 if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination)
471 addPass(createAArch64DeadRegisterDefinitions());
473 // Use AdvSIMD scalar instructions whenever profitable.
474 if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) {
475 addPass(createAArch64AdvSIMDScalar());
476 // The AdvSIMD pass may produce copies that can be rewritten to
477 // be register coaleascer friendly.
478 addPass(&PeepholeOptimizerID);
482 void AArch64PassConfig::addPostRegAlloc() {
483 // Remove redundant copy instructions.
484 if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination)
485 addPass(createAArch64RedundantCopyEliminationPass());
487 if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc())
488 // Improve performance for some FP/SIMD code for A57.
489 addPass(createAArch64A57FPLoadBalancing());
492 void AArch64PassConfig::addPreSched2() {
493 // Expand some pseudo instructions to allow proper scheduling.
494 addPass(createAArch64ExpandPseudoPass());
495 // Use load/store pair instructions when possible.
496 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt)
497 addPass(createAArch64LoadStoreOptimizationPass());
500 void AArch64PassConfig::addPreEmitPass() {
501 if (EnableA53Fix835769)
502 addPass(createAArch64A53Fix835769());
503 // Relax conditional branch instructions if they're otherwise out of
504 // range of their destination.
505 if (BranchRelaxation)
506 addPass(&BranchRelaxationPassID);
508 if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH &&
509 TM->getTargetTriple().isOSBinFormatMachO())
510 addPass(createAArch64CollectLOHPass());