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 //===----------------------------------------------------------------------===//
13 #include "ARMTargetMachine.h"
15 #include "ARMMacroFusion.h"
16 #include "ARMSubtarget.h"
17 #include "ARMTargetObjectFile.h"
18 #include "ARMTargetTransformInfo.h"
19 #include "MCTargetDesc/ARMMCTargetDesc.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/CodeGen/ExecutionDomainFix.h"
26 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
27 #include "llvm/CodeGen/GlobalISel/IRTranslator.h"
28 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
29 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
30 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
31 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
32 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
33 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
34 #include "llvm/CodeGen/MachineFunction.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/DataLayout.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/TargetParser.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/Scalar.h"
57 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden,
58 cl::desc("Inhibit optimization of S->D register accesses on A15"),
62 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden,
63 cl::desc("Run SimplifyCFG after expanding atomic operations"
64 " to make use of cmpxchg flow-based information"),
68 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden,
69 cl::desc("Enable ARM load/store optimization pass"),
72 // FIXME: Unify control over GlobalMerge.
73 static cl::opt<cl::boolOrDefault>
74 EnableGlobalMerge("arm-global-merge", cl::Hidden,
75 cl::desc("Enable the global merge pass"));
78 void initializeARMExecutionDomainFixPass(PassRegistry&);
81 extern "C" void LLVMInitializeARMTarget() {
82 // Register the target.
83 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget());
84 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget());
85 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget());
86 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget());
88 PassRegistry &Registry = *PassRegistry::getPassRegistry();
89 initializeGlobalISel(Registry);
90 initializeARMLoadStoreOptPass(Registry);
91 initializeARMPreAllocLoadStoreOptPass(Registry);
92 initializeARMParallelDSPPass(Registry);
93 initializeARMCodeGenPreparePass(Registry);
94 initializeARMConstantIslandsPass(Registry);
95 initializeARMExecutionDomainFixPass(Registry);
96 initializeARMExpandPseudoPass(Registry);
97 initializeThumb2SizeReducePass(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 StringRef ABIName = Options.MCOptions.getABIName();
114 ABIName = ARM::computeDefaultTargetABI(TT, CPU);
116 if (ABIName == "aapcs16")
117 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
118 else if (ABIName.startswith("aapcs"))
119 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
120 else if (ABIName.startswith("apcs"))
121 return ARMBaseTargetMachine::ARM_ABI_APCS;
123 llvm_unreachable("Unhandled/unknown ABI Name!");
124 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
127 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
128 const TargetOptions &Options,
130 auto ABI = computeTargetABI(TT, CPU, Options);
140 Ret += DataLayout::getManglingComponent(TT);
142 // Pointers are 32 bits and aligned to 32 bits.
145 // ABIs other than APCS have 64 bit integers with natural alignment.
146 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
149 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
150 // bits, others to 64 bits. We always try to align to 64 bits.
151 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
154 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
155 // to 64. We always ty to give them natural alignment.
156 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
157 Ret += "-v64:32:64-v128:32:128";
158 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
159 Ret += "-v128:64:128";
161 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
162 // particular hardware support on 32-bit ARM).
165 // Integer registers are 32 bits.
168 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
169 // aligned everywhere else.
170 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
172 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
180 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
181 Optional<Reloc::Model> RM) {
183 // Default relocation model on Darwin is PIC.
184 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
186 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
187 assert(TT.isOSBinFormatELF() &&
188 "ROPI/RWPI currently only supported for ELF");
190 // DynamicNoPIC is only used on darwin.
191 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
192 return Reloc::Static;
197 /// Create an ARM architecture model.
199 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
200 StringRef CPU, StringRef FS,
201 const TargetOptions &Options,
202 Optional<Reloc::Model> RM,
203 Optional<CodeModel::Model> CM,
204 CodeGenOpt::Level OL, bool isLittle)
205 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
206 CPU, FS, Options, getEffectiveRelocModel(TT, RM),
207 getEffectiveCodeModel(CM, CodeModel::Small), OL),
208 TargetABI(computeTargetABI(TT, CPU, Options)),
209 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) {
211 // Default to triple-appropriate float ABI
212 if (Options.FloatABIType == FloatABI::Default) {
213 if (isTargetHardFloat())
214 this->Options.FloatABIType = FloatABI::Hard;
216 this->Options.FloatABIType = FloatABI::Soft;
219 // Default to triple-appropriate EABI
220 if (Options.EABIVersion == EABI::Default ||
221 Options.EABIVersion == EABI::Unknown) {
222 // musl is compatible with glibc with regard to EABI version
223 if ((TargetTriple.getEnvironment() == Triple::GNUEABI ||
224 TargetTriple.getEnvironment() == Triple::GNUEABIHF ||
225 TargetTriple.getEnvironment() == Triple::MuslEABI ||
226 TargetTriple.getEnvironment() == Triple::MuslEABIHF) &&
227 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin()))
228 this->Options.EABIVersion = EABI::GNU;
230 this->Options.EABIVersion = EABI::EABI5;
233 if (TT.isOSBinFormatMachO()) {
234 this->Options.TrapUnreachable = true;
235 this->Options.NoTrapAfterNoreturn = true;
241 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
244 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
245 Attribute CPUAttr = F.getFnAttribute("target-cpu");
246 Attribute FSAttr = F.getFnAttribute("target-features");
248 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
249 ? CPUAttr.getValueAsString().str()
251 std::string FS = !FSAttr.hasAttribute(Attribute::None)
252 ? FSAttr.getValueAsString().str()
255 // FIXME: This is related to the code below to reset the target options,
256 // we need to know whether or not the soft float flag is set on the
257 // function before we can generate a subtarget. We also need to use
258 // it as a key for the subtarget since that can be the only difference
259 // between two functions.
261 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
262 // If the soft float attribute is set on the function turn on the soft float
263 // subtarget feature.
265 FS += FS.empty() ? "+soft-float" : ",+soft-float";
267 auto &I = SubtargetMap[CPU + FS];
269 // This needs to be done before we create a new subtarget since any
270 // creation will depend on the TM and the code generation flags on the
271 // function that reside in TargetOptions.
272 resetTargetOptions(F);
273 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
275 if (!I->isThumb() && !I->hasARMOps())
276 F.getContext().emitError("Function '" + F.getName() + "' uses ARM "
277 "instructions, but the target does not support ARM mode execution.");
284 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) {
285 return TargetTransformInfo(ARMTTIImpl(this, F));
288 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
289 StringRef CPU, StringRef FS,
290 const TargetOptions &Options,
291 Optional<Reloc::Model> RM,
292 Optional<CodeModel::Model> CM,
293 CodeGenOpt::Level OL, bool JIT)
294 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
296 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
297 StringRef CPU, StringRef FS,
298 const TargetOptions &Options,
299 Optional<Reloc::Model> RM,
300 Optional<CodeModel::Model> CM,
301 CodeGenOpt::Level OL, bool JIT)
302 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
306 /// ARM Code Generator Pass Configuration Options.
307 class ARMPassConfig : public TargetPassConfig {
309 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
310 : TargetPassConfig(TM, PM) {
311 if (TM.getOptLevel() != CodeGenOpt::None) {
312 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(),
313 TM.getTargetFeatureString());
314 if (STI.hasFeature(ARM::FeatureUseMISched))
315 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
319 ARMBaseTargetMachine &getARMTargetMachine() const {
320 return getTM<ARMBaseTargetMachine>();
324 createMachineScheduler(MachineSchedContext *C) const override {
325 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
326 // add DAG Mutations here.
327 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
329 DAG->addMutation(createARMMacroFusionDAGMutation());
334 createPostMachineScheduler(MachineSchedContext *C) const override {
335 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
336 // add DAG Mutations here.
337 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
339 DAG->addMutation(createARMMacroFusionDAGMutation());
343 void addIRPasses() override;
344 void addCodeGenPrepare() override;
345 bool addPreISel() override;
346 bool addInstSelector() override;
347 bool addIRTranslator() override;
348 bool addLegalizeMachineIR() override;
349 bool addRegBankSelect() override;
350 bool addGlobalInstructionSelect() override;
351 void addPreRegAlloc() override;
352 void addPreSched2() override;
353 void addPreEmitPass() override;
356 class ARMExecutionDomainFix : public ExecutionDomainFix {
359 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {}
360 StringRef getPassName() const override {
361 return "ARM Execution Domain Fix";
364 char ARMExecutionDomainFix::ID;
366 } // end anonymous namespace
368 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix",
369 "ARM Execution Domain Fix", false, false)
370 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis)
371 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix",
372 "ARM Execution Domain Fix", false, false)
374 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
375 return new ARMPassConfig(*this, PM);
378 void ARMPassConfig::addIRPasses() {
379 if (TM->Options.ThreadModel == ThreadModel::Single)
380 addPass(createLowerAtomicPass());
382 addPass(createAtomicExpandPass());
384 // Cmpxchg instructions are often used with a subsequent comparison to
385 // determine whether it succeeded. We can exploit existing control-flow in
386 // ldrex/strex loops to simplify this, but it needs tidying up.
387 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
388 addPass(createCFGSimplificationPass(
389 1, false, false, true, true, [this](const Function &F) {
390 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
391 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
394 TargetPassConfig::addIRPasses();
396 // Match interleaved memory accesses to ldN/stN intrinsics.
397 if (TM->getOptLevel() != CodeGenOpt::None)
398 addPass(createInterleavedAccessPass());
401 void ARMPassConfig::addCodeGenPrepare() {
402 if (getOptLevel() != CodeGenOpt::None)
403 addPass(createARMCodeGenPreparePass());
404 TargetPassConfig::addCodeGenPrepare();
407 bool ARMPassConfig::addPreISel() {
408 if (getOptLevel() != CodeGenOpt::None)
409 addPass(createARMParallelDSPPass());
411 if ((TM->getOptLevel() != CodeGenOpt::None &&
412 EnableGlobalMerge == cl::BOU_UNSET) ||
413 EnableGlobalMerge == cl::BOU_TRUE) {
414 // FIXME: This is using the thumb1 only constant value for
415 // maximal global offset for merging globals. We may want
416 // to look into using the old value for non-thumb1 code of
417 // 4095 based on the TargetMachine, but this starts to become
418 // tricky when doing code gen per function.
419 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
420 (EnableGlobalMerge == cl::BOU_UNSET);
421 // Merging of extern globals is enabled by default on non-Mach-O as we
422 // expect it to be generally either beneficial or harmless. On Mach-O it
423 // is disabled as we emit the .subsections_via_symbols directive which
424 // means that merging extern globals is not safe.
425 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
426 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
427 MergeExternalByDefault));
433 bool ARMPassConfig::addInstSelector() {
434 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
438 bool ARMPassConfig::addIRTranslator() {
439 addPass(new IRTranslator());
443 bool ARMPassConfig::addLegalizeMachineIR() {
444 addPass(new Legalizer());
448 bool ARMPassConfig::addRegBankSelect() {
449 addPass(new RegBankSelect());
453 bool ARMPassConfig::addGlobalInstructionSelect() {
454 addPass(new InstructionSelect());
458 void ARMPassConfig::addPreRegAlloc() {
459 if (getOptLevel() != CodeGenOpt::None) {
460 addPass(createMLxExpansionPass());
462 if (EnableARMLoadStoreOpt)
463 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
465 if (!DisableA15SDOptimization)
466 addPass(createA15SDOptimizerPass());
470 void ARMPassConfig::addPreSched2() {
471 if (getOptLevel() != CodeGenOpt::None) {
472 if (EnableARMLoadStoreOpt)
473 addPass(createARMLoadStoreOptimizationPass());
475 addPass(new ARMExecutionDomainFix());
476 addPass(createBreakFalseDeps());
479 // Expand some pseudo instructions into multiple instructions to allow
480 // proper scheduling.
481 addPass(createARMExpandPseudoPass());
483 if (getOptLevel() != CodeGenOpt::None) {
484 // in v8, IfConversion depends on Thumb instruction widths
485 addPass(createThumb2SizeReductionPass([this](const Function &F) {
486 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
489 addPass(createIfConverter([](const MachineFunction &MF) {
490 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
493 addPass(createThumb2ITBlockPass());
496 void ARMPassConfig::addPreEmitPass() {
497 addPass(createThumb2SizeReductionPass());
499 // Constant island pass work on unbundled instructions.
500 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
501 return MF.getSubtarget<ARMSubtarget>().isThumb2();
504 // Don't optimize barriers at -O0.
505 if (getOptLevel() != CodeGenOpt::None)
506 addPass(createARMOptimizeBarriersPass());
508 addPass(createARMConstantIslandPass());