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/MachineScheduler.h"
41 #include "llvm/CodeGen/Passes.h"
42 #include "llvm/CodeGen/TargetPassConfig.h"
43 #include "llvm/IR/Attributes.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Support/CodeGen.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/TargetParser.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Scalar.h"
62 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
63 cl::desc("Inhibit optimization of S->D register accesses on A15"),
67 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
68 cl::desc("Run SimplifyCFG after expanding atomic operations"
69 " to make use of cmpxchg flow-based information"),
73 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
74 cl::desc("Enable ARM load/store optimization pass"),
77 // FIXME: Unify control over GlobalMerge.
78 static cl::opt<cl::boolOrDefault>
79 EnableGlobalMerge("arm-global-merge", cl::Hidden,
80 cl::desc("Enable the global merge pass"));
83 void initializeARMExecutionDepsFixPass(PassRegistry&);
86 extern "C" void LLVMInitializeARMTarget() {
87 // Register the target.
88 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
89 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget());
90 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
91 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget());
93 PassRegistry &Registry = *PassRegistry::getPassRegistry();
94 initializeGlobalISel(Registry);
95 initializeARMLoadStoreOptPass(Registry);
96 initializeARMPreAllocLoadStoreOptPass(Registry);
97 initializeARMConstantIslandsPass(Registry);
98 initializeARMExecutionDepsFixPass(Registry);
101 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
102 if (TT.isOSBinFormatMachO())
103 return llvm::make_unique<TargetLoweringObjectFileMachO>();
104 if (TT.isOSWindows())
105 return llvm::make_unique<TargetLoweringObjectFileCOFF>();
106 return llvm::make_unique<ARMElfTargetObjectFile>();
109 static ARMBaseTargetMachine::ARMABI
110 computeTargetABI(const Triple &TT, StringRef CPU,
111 const TargetOptions &Options) {
112 if (Options.MCOptions.getABIName() == "aapcs16")
113 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
114 else if (Options.MCOptions.getABIName().startswith("aapcs"))
115 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
116 else if (Options.MCOptions.getABIName().startswith("apcs"))
117 return ARMBaseTargetMachine::ARM_ABI_APCS;
119 assert(Options.MCOptions.getABIName().empty() &&
120 "Unknown target-abi option!");
122 ARMBaseTargetMachine::ARMABI TargetABI =
123 ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
125 unsigned ArchKind = ARM::parseCPUArch(CPU);
126 StringRef ArchName = ARM::getArchName(ArchKind);
127 // FIXME: This is duplicated code from the front end and should be unified.
128 if (TT.isOSBinFormatMachO()) {
129 if (TT.getEnvironment() == Triple::EABI ||
130 (TT.getOS() == Triple::UnknownOS && TT.isOSBinFormatMachO()) ||
131 ARM::parseArchProfile(ArchName) == ARM::PK_M) {
132 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
133 } else if (TT.isWatchABI()) {
134 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS16;
136 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
138 } else if (TT.isOSWindows()) {
139 // FIXME: this is invalid for WindowsCE
140 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
142 // Select the default based on the platform.
143 switch (TT.getEnvironment()) {
144 case Triple::Android:
145 case Triple::GNUEABI:
146 case Triple::GNUEABIHF:
147 case Triple::MuslEABI:
148 case Triple::MuslEABIHF:
151 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
154 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
158 TargetABI = ARMBaseTargetMachine::ARM_ABI_APCS;
160 TargetABI = ARMBaseTargetMachine::ARM_ABI_AAPCS;
168 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
169 const TargetOptions &Options,
171 auto ABI = computeTargetABI(TT, CPU, Options);
181 Ret += DataLayout::getManglingComponent(TT);
183 // Pointers are 32 bits and aligned to 32 bits.
186 // ABIs other than APCS have 64 bit integers with natural alignment.
187 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
190 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
191 // bits, others to 64 bits. We always try to align to 64 bits.
192 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
195 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
196 // to 64. We always ty to give them natural alignment.
197 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
198 Ret += "-v64:32:64-v128:32:128";
199 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
200 Ret += "-v128:64:128";
202 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
203 // particular hardware support on 32-bit ARM).
206 // Integer registers are 32 bits.
209 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
210 // aligned everywhere else.
211 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
213 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
221 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
222 Optional<Reloc::Model> RM) {
224 // Default relocation model on Darwin is PIC.
225 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
227 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
228 assert(TT.isOSBinFormatELF() &&
229 "ROPI/RWPI currently only supported for ELF");
231 // DynamicNoPIC is only used on darwin.
232 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
233 return Reloc::Static;
238 /// Create an ARM architecture model.
240 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
241 StringRef CPU, StringRef FS,
242 const TargetOptions &Options,
243 Optional<Reloc::Model> RM,
245 CodeGenOpt::Level OL, bool isLittle)
246 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
247 CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
249 TargetABI(computeTargetABI(TT, CPU, Options)),
250 TLOF(createTLOF(getTargetTriple())),
251 Subtarget(TT, CPU, FS, *this, isLittle), isLittle(isLittle) {
253 // Default to triple-appropriate float ABI
254 if (Options.FloatABIType == FloatABI::Default)
255 this->Options.FloatABIType =
256 Subtarget.isTargetHardFloat() ? FloatABI::Hard : FloatABI::Soft;
258 // Default to triple-appropriate EABI
259 if (Options.EABIVersion == EABI::Default ||
260 Options.EABIVersion == EABI::Unknown) {
261 // musl is compatible with glibc with regard to EABI version
262 if (Subtarget.isTargetGNUAEABI() || Subtarget.isTargetMuslAEABI())
263 this->Options.EABIVersion = EABI::GNU;
265 this->Options.EABIVersion = EABI::EABI5;
269 if (!Subtarget.isThumb() && !Subtarget.hasARMOps())
270 report_fatal_error("CPU: '" + Subtarget.getCPUString() + "' does not "
271 "support ARM mode execution!");
274 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
276 #ifdef LLVM_BUILD_GLOBAL_ISEL
279 struct ARMGISelActualAccessor : public GISelAccessor {
280 std::unique_ptr<CallLowering> CallLoweringInfo;
281 std::unique_ptr<InstructionSelector> InstSelector;
282 std::unique_ptr<LegalizerInfo> Legalizer;
283 std::unique_ptr<RegisterBankInfo> RegBankInfo;
285 const CallLowering *getCallLowering() const override {
286 return CallLoweringInfo.get();
289 const InstructionSelector *getInstructionSelector() const override {
290 return InstSelector.get();
293 const LegalizerInfo *getLegalizerInfo() const override {
294 return Legalizer.get();
297 const RegisterBankInfo *getRegBankInfo() const override {
298 return RegBankInfo.get();
302 } // end anonymous namespace
306 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
307 Attribute CPUAttr = F.getFnAttribute("target-cpu");
308 Attribute FSAttr = F.getFnAttribute("target-features");
310 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
311 ? CPUAttr.getValueAsString().str()
313 std::string FS = !FSAttr.hasAttribute(Attribute::None)
314 ? FSAttr.getValueAsString().str()
317 // FIXME: This is related to the code below to reset the target options,
318 // we need to know whether or not the soft float flag is set on the
319 // function before we can generate a subtarget. We also need to use
320 // it as a key for the subtarget since that can be the only difference
321 // between two functions.
323 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
324 // If the soft float attribute is set on the function turn on the soft float
325 // subtarget feature.
327 FS += FS.empty() ? "+soft-float" : ",+soft-float";
329 auto &I = SubtargetMap[CPU + FS];
331 // This needs to be done before we create a new subtarget since any
332 // creation will depend on the TM and the code generation flags on the
333 // function that reside in TargetOptions.
334 resetTargetOptions(F);
335 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
337 #ifndef LLVM_BUILD_GLOBAL_ISEL
338 GISelAccessor *GISel = new GISelAccessor();
340 ARMGISelActualAccessor *GISel = new ARMGISelActualAccessor();
341 GISel->CallLoweringInfo.reset(new ARMCallLowering(*I->getTargetLowering()));
342 GISel->Legalizer.reset(new ARMLegalizerInfo(*I));
344 auto *RBI = new ARMRegisterBankInfo(*I->getRegisterInfo());
346 // FIXME: At this point, we can't rely on Subtarget having RBI.
347 // It's awkward to mix passing RBI and the Subtarget; should we pass
349 GISel->InstSelector.reset(createARMInstructionSelector(*this, *I, *RBI));
351 GISel->RegBankInfo.reset(RBI);
353 I->setGISelAccessor(*GISel);
358 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
359 return TargetIRAnalysis([this](const Function &F) {
360 return TargetTransformInfo(ARMTTIImpl(this, F));
365 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
366 StringRef CPU, StringRef FS,
367 const TargetOptions &Options,
368 Optional<Reloc::Model> RM,
370 CodeGenOpt::Level OL)
371 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
373 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
374 StringRef CPU, StringRef FS,
375 const TargetOptions &Options,
376 Optional<Reloc::Model> RM,
378 CodeGenOpt::Level OL)
379 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
383 /// ARM Code Generator Pass Configuration Options.
384 class ARMPassConfig : public TargetPassConfig {
386 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
387 : TargetPassConfig(TM, PM) {}
389 ARMBaseTargetMachine &getARMTargetMachine() const {
390 return getTM<ARMBaseTargetMachine>();
394 createMachineScheduler(MachineSchedContext *C) const override {
395 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
396 // add DAG Mutations here.
401 createPostMachineScheduler(MachineSchedContext *C) const override {
402 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
403 // add DAG Mutations here.
407 void addIRPasses() override;
408 bool addPreISel() override;
409 bool addInstSelector() override;
410 #ifdef LLVM_BUILD_GLOBAL_ISEL
411 bool addIRTranslator() override;
412 bool addLegalizeMachineIR() override;
413 bool addRegBankSelect() override;
414 bool addGlobalInstructionSelect() override;
416 void addPreRegAlloc() override;
417 void addPreSched2() override;
418 void addPreEmitPass() override;
421 class ARMExecutionDepsFix : public ExecutionDepsFix {
424 ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
425 StringRef getPassName() const override {
426 return "ARM Execution Dependency Fix";
429 char ARMExecutionDepsFix::ID;
431 } // end anonymous namespace
433 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
434 "ARM Execution Dependency Fix", false, false)
436 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
437 return new ARMPassConfig(*this, PM);
440 void ARMPassConfig::addIRPasses() {
441 if (TM->Options.ThreadModel == ThreadModel::Single)
442 addPass(createLowerAtomicPass());
444 addPass(createAtomicExpandPass());
446 // Cmpxchg instructions are often used with a subsequent comparison to
447 // determine whether it succeeded. We can exploit existing control-flow in
448 // ldrex/strex loops to simplify this, but it needs tidying up.
449 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
450 addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
451 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
452 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
455 TargetPassConfig::addIRPasses();
457 // Match interleaved memory accesses to ldN/stN intrinsics.
458 if (TM->getOptLevel() != CodeGenOpt::None)
459 addPass(createInterleavedAccessPass());
462 bool ARMPassConfig::addPreISel() {
463 if ((TM->getOptLevel() != CodeGenOpt::None &&
464 EnableGlobalMerge == cl::BOU_UNSET) ||
465 EnableGlobalMerge == cl::BOU_TRUE) {
466 // FIXME: This is using the thumb1 only constant value for
467 // maximal global offset for merging globals. We may want
468 // to look into using the old value for non-thumb1 code of
469 // 4095 based on the TargetMachine, but this starts to become
470 // tricky when doing code gen per function.
471 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
472 (EnableGlobalMerge == cl::BOU_UNSET);
473 // Merging of extern globals is enabled by default on non-Mach-O as we
474 // expect it to be generally either beneficial or harmless. On Mach-O it
475 // is disabled as we emit the .subsections_via_symbols directive which
476 // means that merging extern globals is not safe.
477 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
478 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
479 MergeExternalByDefault));
485 bool ARMPassConfig::addInstSelector() {
486 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
490 #ifdef LLVM_BUILD_GLOBAL_ISEL
491 bool ARMPassConfig::addIRTranslator() {
492 addPass(new IRTranslator());
496 bool ARMPassConfig::addLegalizeMachineIR() {
497 addPass(new Legalizer());
501 bool ARMPassConfig::addRegBankSelect() {
502 addPass(new RegBankSelect());
506 bool ARMPassConfig::addGlobalInstructionSelect() {
507 addPass(new InstructionSelect());
512 void ARMPassConfig::addPreRegAlloc() {
513 if (getOptLevel() != CodeGenOpt::None) {
514 addPass(createMLxExpansionPass());
516 if (EnableARMLoadStoreOpt)
517 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
519 if (!DisableA15SDOptimization)
520 addPass(createA15SDOptimizerPass());
524 void ARMPassConfig::addPreSched2() {
525 if (getOptLevel() != CodeGenOpt::None) {
526 if (EnableARMLoadStoreOpt)
527 addPass(createARMLoadStoreOptimizationPass());
529 addPass(new ARMExecutionDepsFix());
532 // Expand some pseudo instructions into multiple instructions to allow
533 // proper scheduling.
534 addPass(createARMExpandPseudoPass());
536 if (getOptLevel() != CodeGenOpt::None) {
537 // in v8, IfConversion depends on Thumb instruction widths
538 addPass(createThumb2SizeReductionPass([this](const Function &F) {
539 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
542 addPass(createIfConverter([](const MachineFunction &MF) {
543 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
546 addPass(createThumb2ITBlockPass());
549 void ARMPassConfig::addPreEmitPass() {
550 addPass(createThumb2SizeReductionPass());
552 // Constant island pass work on unbundled instructions.
553 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
554 return MF.getSubtarget<ARMSubtarget>().isThumb2();
557 // Don't optimize barriers at -O0.
558 if (getOptLevel() != CodeGenOpt::None)
559 addPass(createARMOptimizeBarriersPass());
561 addPass(createARMConstantIslandPass());