1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===//
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 "ARMCallLowering.h"
15 #include "ARMLegalizerInfo.h"
16 #ifdef LLVM_BUILD_GLOBAL_ISEL
17 #include "ARMRegisterBankInfo.h"
19 #include "ARMSubtarget.h"
20 #include "ARMTargetMachine.h"
21 #include "ARMTargetObjectFile.h"
22 #include "ARMTargetTransformInfo.h"
23 #include "MCTargetDesc/ARMMCTargetDesc.h"
24 #include "llvm/ADT/Optional.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/CodeGen/ExecutionDepsFix.h"
30 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
31 #include "llvm/CodeGen/GlobalISel/GISelAccessor.h"
32 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
33 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
34 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
35 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
36 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
37 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
38 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/Passes.h"
41 #include "llvm/CodeGen/TargetPassConfig.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/CodeGen.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/TargetParser.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Transforms/Scalar.h"
61 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
62 cl::desc("Inhibit optimization of S->D register accesses on A15"),
66 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
67 cl::desc("Run SimplifyCFG after expanding atomic operations"
68 " to make use of cmpxchg flow-based information"),
72 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
73 cl::desc("Enable ARM load/store optimization pass"),
76 // FIXME: Unify control over GlobalMerge.
77 static cl::opt<cl::boolOrDefault>
78 EnableGlobalMerge("arm-global-merge", cl::Hidden,
79 cl::desc("Enable the global merge pass"));
82 void initializeARMExecutionDepsFixPass(PassRegistry&);
85 extern "C" void LLVMInitializeARMTarget() {
86 // Register the target.
87 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
88 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
89 RegisterTargetMachine<ThumbLETargetMachine> A(getTheThumbLETarget());
90 RegisterTargetMachine<ThumbBETargetMachine> B(getTheThumbBETarget());
92 PassRegistry &Registry = *PassRegistry::getPassRegistry();
93 initializeGlobalISel(Registry);
94 initializeARMLoadStoreOptPass(Registry);
95 initializeARMPreAllocLoadStoreOptPass(Registry);
96 initializeARMConstantIslandsPass(Registry);
97 initializeARMExecutionDepsFixPass(Registry);
100 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
101 if (TT.isOSBinFormatMachO())
102 return llvm::make_unique<TargetLoweringObjectFileMachO>();
103 if (TT.isOSWindows())
104 return llvm::make_unique<TargetLoweringObjectFileCOFF>();
105 return llvm::make_unique<ARMElfTargetObjectFile>();
108 static ARMBaseTargetMachine::ARMABI
109 computeTargetABI(const Triple &TT, StringRef CPU,
110 const TargetOptions &Options) {
111 if (Options.MCOptions.getABIName() == "aapcs16")
112 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
113 else if (Options.MCOptions.getABIName().startswith("aapcs"))
114 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
115 else if (Options.MCOptions.getABIName().startswith("apcs"))
116 return ARMBaseTargetMachine::ARM_ABI_APCS;
118 assert(Options.MCOptions.getABIName().empty() &&
119 "Unknown target-abi option!");
121 ARMBaseTargetMachine::ARMABI TargetABI =
122 ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
124 unsigned ArchKind = ARM::parseCPUArch(CPU);
125 StringRef ArchName = ARM::getArchName(ArchKind);
126 // FIXME: This is duplicated code from the front end and should be unified.
127 if (TT.isOSBinFormatMachO()) {
128 if (TT.getEnvironment() == Triple::EABI ||
129 (TT.getOS() == Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
130 ARM::parseArchProfile(ArchName) == ARM::PK_M) {
131 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
132 } else if (TT.isWatchABI()) {
133 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
135 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
137 } else if (TT.isOSWindows()) {
138 // FIXME: this is invalid for WindowsCE
139 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
141 // Select the default based on the platform.
142 switch (TT.getEnvironment()) {
143 case Triple::Android:
144 case Triple::GNUEABI:
145 case Triple::GNUEABIHF:
146 case Triple::MuslEABI:
147 case Triple::MuslEABIHF:
150 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
153 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
157 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
159 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
167 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
168 const TargetOptions &Options,
170 auto ABI = computeTargetABI(TT, CPU, Options);
180 Ret += DataLayout::getManglingComponent(TT);
182 // Pointers are 32 bits and aligned to 32 bits.
185 // ABIs other than APCS have 64 bit integers with natural alignment.
186 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
189 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
190 // bits, others to 64 bits. We always try to align to 64 bits.
191 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
194 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
195 // to 64. We always ty to give them natural alignment.
196 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
197 Ret += "-v64:32:64-v128:32:128";
198 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
199 Ret += "-v128:64:128";
201 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
202 // particular hardware support on 32-bit ARM).
205 // Integer registers are 32 bits.
208 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
209 // aligned everywhere else.
210 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
212 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
220 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
221 Optional<Reloc::Model> RM) {
223 // Default relocation model on Darwin is PIC.
224 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
226 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
227 assert(TT.isOSBinFormatELF() &&
228 "ROPI/RWPI currently only supported for ELF");
230 // DynamicNoPIC is only used on darwin.
231 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
232 return Reloc::Static;
237 /// Create an ARM architecture model.
239 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
240 StringRef CPU, StringRef FS,
241 const TargetOptions &Options,
242 Optional<Reloc::Model> RM,
244 CodeGenOpt::Level OL, bool isLittle)
245 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
246 CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
248 TargetABI(computeTargetABI(TT, CPU, Options)),
249 TLOF(createTLOF(getTargetTriple())),
250 Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
252 // Default to triple-appropriate float ABI
253 if (Options.FloatABIType == FloatABI::Default)
254 this->Options.FloatABIType =
255 Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
257 // Default to triple-appropriate EABI
258 if (Options.EABIVersion == EABI::Default ||
259 Options.EABIVersion == EABI::Unknown) {
260 // musl is compatible with glibc with regard to EABI version
261 if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
262 this->Options.EABIVersion = EABI::GNU;
264 this->Options.EABIVersion = EABI::EABI5;
268 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
270 #ifdef LLVM_BUILD_GLOBAL_ISEL
273 struct ARMGISelActualAccessor : public GISelAccessor {
274 std::unique_ptr<CallLowering> CallLoweringInfo;
275 std::unique_ptr<InstructionSelector> InstSelector;
276 std::unique_ptr<LegalizerInfo> Legalizer;
277 std::unique_ptr<RegisterBankInfo> RegBankInfo;
279 const CallLowering *getCallLowering() const override {
280 return CallLoweringInfo.get();
283 const InstructionSelector *getInstructionSelector() const override {
284 return InstSelector.get();
287 const LegalizerInfo *getLegalizerInfo() const override {
288 return Legalizer.get();
291 const RegisterBankInfo *getRegBankInfo() const override {
292 return RegBankInfo.get();
296 } // end anonymous namespace
300 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
301 Attribute CPUAttr = F.getFnAttribute("target-cpu");
302 Attribute FSAttr = F.getFnAttribute("target-features");
304 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
305 ? CPUAttr.getValueAsString().str()
307 std::string FS = !FSAttr.hasAttribute(Attribute::None)
308 ? FSAttr.getValueAsString().str()
311 // FIXME: This is related to the code below to reset the target options,
312 // we need to know whether or not the soft float flag is set on the
313 // function before we can generate a subtarget. We also need to use
314 // it as a key for the subtarget since that can be the only difference
315 // between two functions.
317 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
318 // If the soft float attribute is set on the function turn on the soft float
319 // subtarget feature.
321 FS += FS.empty() ? "+soft-float" : ",+soft-float";
323 auto &I = SubtargetMap[CPU + FS];
325 // This needs to be done before we create a new subtarget since any
326 // creation will depend on the TM and the code generation flags on the
327 // function that reside in TargetOptions.
328 resetTargetOptions(F);
329 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
331 #ifndef LLVM_BUILD_GLOBAL_ISEL
332 GISelAccessor *GISel = new GISelAccessor();
334 ARMGISelActualAccessor *GISel = new ARMGISelActualAccessor();
335 GISel->CallLoweringInfo.reset(new ARMCallLowering(*I->getTargetLowering()));
336 GISel->Legalizer.reset(new ARMLegalizerInfo(*I));
338 auto *RBI = new ARMRegisterBankInfo(*I->getRegisterInfo());
340 // FIXME: At this point, we can't rely on Subtarget having RBI.
341 // It's awkward to mix passing RBI and the Subtarget; should we pass
343 GISel->InstSelector.reset(createARMInstructionSelector(*this, *I, *RBI));
345 GISel->RegBankInfo.reset(RBI);
347 I->setGISelAccessor(*GISel);
352 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
353 return TargetIRAnalysis([this](const Function &F) {
354 return TargetTransformInfo(ARMTTIImpl(this, F));
358 void ARMTargetMachine::anchor() {}
360 ARMTargetMachine::ARMTargetMachine(const Target &T, const Triple &TT,
361 StringRef CPU, StringRef FS,
362 const TargetOptions &Options,
363 Optional<Reloc::Model> RM,
364 CodeModel::Model CM, CodeGenOpt::Level OL,
366 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
368 if (!Subtarget.hasARMOps())
369 report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
370 "support ARM mode execution!");
373 void ARMLETargetMachine::anchor() {}
375 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
376 StringRef CPU, StringRef FS,
377 const TargetOptions &Options,
378 Optional<Reloc::Model> RM,
380 CodeGenOpt::Level OL)
381 : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
383 void ARMBETargetMachine::anchor() {}
385 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
386 StringRef CPU, StringRef FS,
387 const TargetOptions &Options,
388 Optional<Reloc::Model> RM,
390 CodeGenOpt::Level OL)
391 : ARMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
393 void ThumbTargetMachine::anchor() {}
395 ThumbTargetMachine::ThumbTargetMachine(const Target &T, const Triple &TT,
396 StringRef CPU, StringRef FS,
397 const TargetOptions &Options,
398 Optional<Reloc::Model> RM,
400 CodeGenOpt::Level OL, bool isLittle)
401 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, isLittle) {
405 void ThumbLETargetMachine::anchor() {}
407 ThumbLETargetMachine::ThumbLETargetMachine(const Target &T, const Triple &TT,
408 StringRef CPU, StringRef FS,
409 const TargetOptions &Options,
410 Optional<Reloc::Model> RM,
412 CodeGenOpt::Level OL)
413 : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
415 void ThumbBETargetMachine::anchor() {}
417 ThumbBETargetMachine::ThumbBETargetMachine(const Target &T, const Triple &TT,
418 StringRef CPU, StringRef FS,
419 const TargetOptions &Options,
420 Optional<Reloc::Model> RM,
422 CodeGenOpt::Level OL)
423 : ThumbTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
427 /// ARM Code Generator Pass Configuration Options.
428 class ARMPassConfig : public TargetPassConfig {
430 ARMPassConfig(ARMBaseTargetMachine *TM, PassManagerBase &PM)
431 : TargetPassConfig(TM, PM) {}
433 ARMBaseTargetMachine &getARMTargetMachine() const {
434 return getTM<ARMBaseTargetMachine>();
437 void addIRPasses() override;
438 bool addPreISel() override;
439 bool addInstSelector() override;
440 #ifdef LLVM_BUILD_GLOBAL_ISEL
441 bool addIRTranslator() override;
442 bool addLegalizeMachineIR() override;
443 bool addRegBankSelect() override;
444 bool addGlobalInstructionSelect() override;
446 void addPreRegAlloc() override;
447 void addPreSched2() override;
448 void addPreEmitPass() override;
451 class ARMExecutionDepsFix : public ExecutionDepsFix {
454 ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
455 StringRef getPassName() const override {
456 return "ARM Execution Dependency Fix";
459 char ARMExecutionDepsFix::ID;
461 } // end anonymous namespace
463 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
464 "ARM Execution Dependency Fix", false, false)
466 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
467 return new ARMPassConfig(this, PM);
470 void ARMPassConfig::addIRPasses() {
471 if (TM->Options.ThreadModel == ThreadModel::Single)
472 addPass(createLowerAtomicPass());
474 addPass(createAtomicExpandPass());
476 // Cmpxchg instructions are often used with a subsequent comparison to
477 // determine whether it succeeded. We can exploit existing control-flow in
478 // ldrex/strex loops to simplify this, but it needs tidying up.
479 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
480 addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
481 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
482 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
485 TargetPassConfig::addIRPasses();
487 // Match interleaved memory accesses to ldN/stN intrinsics.
488 if (TM->getOptLevel() != CodeGenOpt::None)
489 addPass(createInterleavedAccessPass());
492 bool ARMPassConfig::addPreISel() {
493 if ((TM->getOptLevel() != CodeGenOpt::None &&
494 EnableGlobalMerge == cl::BOU_UNSET) ||
495 EnableGlobalMerge == cl::BOU_TRUE) {
496 // FIXME: This is using the thumb1 only constant value for
497 // maximal global offset for merging globals. We may want
498 // to look into using the old value for non-thumb1 code of
499 // 4095 based on the TargetMachine, but this starts to become
500 // tricky when doing code gen per function.
501 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
502 (EnableGlobalMerge == cl::BOU_UNSET);
503 // Merging of extern globals is enabled by default on non-Mach-O as we
504 // expect it to be generally either beneficial or harmless. On Mach-O it
505 // is disabled as we emit the .subsections_via_symbols directive which
506 // means that merging extern globals is not safe.
507 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
508 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
509 MergeExternalByDefault));
515 bool ARMPassConfig::addInstSelector() {
516 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
520 #ifdef LLVM_BUILD_GLOBAL_ISEL
521 bool ARMPassConfig::addIRTranslator() {
522 addPass(new IRTranslator());
526 bool ARMPassConfig::addLegalizeMachineIR() {
527 addPass(new Legalizer());
531 bool ARMPassConfig::addRegBankSelect() {
532 addPass(new RegBankSelect());
536 bool ARMPassConfig::addGlobalInstructionSelect() {
537 addPass(new InstructionSelect());
542 void ARMPassConfig::addPreRegAlloc() {
543 if (getOptLevel() != CodeGenOpt::None) {
544 addPass(createMLxExpansionPass());
546 if (EnableARMLoadStoreOpt)
547 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
549 if (!DisableA15SDOptimization)
550 addPass(createA15SDOptimizerPass());
554 void ARMPassConfig::addPreSched2() {
555 if (getOptLevel() != CodeGenOpt::None) {
556 if (EnableARMLoadStoreOpt)
557 addPass(createARMLoadStoreOptimizationPass());
559 addPass(new ARMExecutionDepsFix());
562 // Expand some pseudo instructions into multiple instructions to allow
563 // proper scheduling.
564 addPass(createARMExpandPseudoPass());
566 if (getOptLevel() != CodeGenOpt::None) {
567 // in v8, IfConversion depends on Thumb instruction widths
568 addPass(createThumb2SizeReductionPass([this](const Function &F) {
569 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
572 addPass(createIfConverter([](const MachineFunction &MF) {
573 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
576 addPass(createThumb2ITBlockPass());
579 void ARMPassConfig::addPreEmitPass() {
580 addPass(createThumb2SizeReductionPass());
582 // Constant island pass work on unbundled instructions.
583 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
584 return MF.getSubtarget<ARMSubtarget>().isThumb2();
587 // Don't optimize barriers at -O0.
588 if (getOptLevel() != CodeGenOpt::None)
589 addPass(createARMOptimizeBarriersPass());
591 addPass(createARMConstantIslandPass());