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 "ARMSubtarget.h"
15 #include "ARMMacroFusion.h"
16 #include "ARMTargetMachine.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/ExecutionDepsFix.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 initializeARMExecutionDepsFixPass(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 initializeARMConstantIslandsPass(Registry);
93 initializeARMExecutionDepsFixPass(Registry);
96 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
97 if (TT.isOSBinFormatMachO())
98 return llvm::make_unique<TargetLoweringObjectFileMachO>();
100 return llvm::make_unique<TargetLoweringObjectFileCOFF>();
101 return llvm::make_unique<ARMElfTargetObjectFile>();
104 static ARMBaseTargetMachine::ARMABI
105 computeTargetABI(const Triple &TT, StringRef CPU,
106 const TargetOptions &Options) {
107 StringRef ABIName = Options.MCOptions.getABIName();
110 ABIName = ARM::computeDefaultTargetABI(TT, CPU);
112 if (ABIName == "aapcs16")
113 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
114 else if (ABIName.startswith("aapcs"))
115 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
116 else if (ABIName.startswith("apcs"))
117 return ARMBaseTargetMachine::ARM_ABI_APCS;
119 llvm_unreachable("Unhandled/unknown ABI Name!");
120 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
123 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
124 const TargetOptions &Options,
126 auto ABI = computeTargetABI(TT, CPU, Options);
136 Ret += DataLayout::getManglingComponent(TT);
138 // Pointers are 32 bits and aligned to 32 bits.
141 // ABIs other than APCS have 64 bit integers with natural alignment.
142 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
145 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
146 // bits, others to 64 bits. We always try to align to 64 bits.
147 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
150 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
151 // to 64. We always ty to give them natural alignment.
152 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
153 Ret += "-v64:32:64-v128:32:128";
154 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
155 Ret += "-v128:64:128";
157 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
158 // particular hardware support on 32-bit ARM).
161 // Integer registers are 32 bits.
164 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
165 // aligned everywhere else.
166 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
168 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
176 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
177 Optional<Reloc::Model> RM) {
179 // Default relocation model on Darwin is PIC.
180 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
182 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
183 assert(TT.isOSBinFormatELF() &&
184 "ROPI/RWPI currently only supported for ELF");
186 // DynamicNoPIC is only used on darwin.
187 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
188 return Reloc::Static;
193 /// Create an ARM architecture model.
195 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
196 StringRef CPU, StringRef FS,
197 const TargetOptions &Options,
198 Optional<Reloc::Model> RM,
200 CodeGenOpt::Level OL, bool isLittle)
201 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
202 CPU, FS, Options, getEffectiveRelocModel(TT, RM), CM,
204 TargetABI(computeTargetABI(TT, CPU, Options)),
205 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) {
207 // Default to triple-appropriate float ABI
208 if (Options.FloatABIType == FloatABI::Default) {
209 if (TargetTriple.getEnvironment() == Triple::GNUEABIHF ||
210 TargetTriple.getEnvironment() == Triple::MuslEABIHF ||
211 TargetTriple.getEnvironment() == Triple::EABIHF ||
212 TargetTriple.isOSWindows() ||
213 TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
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;
236 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
239 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
240 Attribute CPUAttr = F.getFnAttribute("target-cpu");
241 Attribute FSAttr = F.getFnAttribute("target-features");
243 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
244 ? CPUAttr.getValueAsString().str()
246 std::string FS = !FSAttr.hasAttribute(Attribute::None)
247 ? FSAttr.getValueAsString().str()
250 // FIXME: This is related to the code below to reset the target options,
251 // we need to know whether or not the soft float flag is set on the
252 // function before we can generate a subtarget. We also need to use
253 // it as a key for the subtarget since that can be the only difference
254 // between two functions.
256 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
257 // If the soft float attribute is set on the function turn on the soft float
258 // subtarget feature.
260 FS += FS.empty() ? "+soft-float" : ",+soft-float";
262 auto &I = SubtargetMap[CPU + FS];
264 // This needs to be done before we create a new subtarget since any
265 // creation will depend on the TM and the code generation flags on the
266 // function that reside in TargetOptions.
267 resetTargetOptions(F);
268 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
273 TargetIRAnalysis ARMBaseTargetMachine::getTargetIRAnalysis() {
274 return TargetIRAnalysis([this](const Function &F) {
275 return TargetTransformInfo(ARMTTIImpl(this, F));
280 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
281 StringRef CPU, StringRef FS,
282 const TargetOptions &Options,
283 Optional<Reloc::Model> RM,
285 CodeGenOpt::Level OL)
286 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
288 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
289 StringRef CPU, StringRef FS,
290 const TargetOptions &Options,
291 Optional<Reloc::Model> RM,
293 CodeGenOpt::Level OL)
294 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
298 /// ARM Code Generator Pass Configuration Options.
299 class ARMPassConfig : public TargetPassConfig {
301 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
302 : TargetPassConfig(TM, PM) {}
304 ARMBaseTargetMachine &getARMTargetMachine() const {
305 return getTM<ARMBaseTargetMachine>();
309 createMachineScheduler(MachineSchedContext *C) const override {
310 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
311 // add DAG Mutations here.
312 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
314 DAG->addMutation(createARMMacroFusionDAGMutation());
319 createPostMachineScheduler(MachineSchedContext *C) const override {
320 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
321 // add DAG Mutations here.
322 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
324 DAG->addMutation(createARMMacroFusionDAGMutation());
328 void addIRPasses() override;
329 bool addPreISel() override;
330 bool addInstSelector() override;
331 #ifdef LLVM_BUILD_GLOBAL_ISEL
332 bool addIRTranslator() override;
333 bool addLegalizeMachineIR() override;
334 bool addRegBankSelect() override;
335 bool addGlobalInstructionSelect() override;
337 void addPreRegAlloc() override;
338 void addPreSched2() override;
339 void addPreEmitPass() override;
342 class ARMExecutionDepsFix : public ExecutionDepsFix {
345 ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
346 StringRef getPassName() const override {
347 return "ARM Execution Dependency Fix";
350 char ARMExecutionDepsFix::ID;
352 } // end anonymous namespace
354 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
355 "ARM Execution Dependency Fix", false, false)
357 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
358 return new ARMPassConfig(*this, PM);
361 void ARMPassConfig::addIRPasses() {
362 if (TM->Options.ThreadModel == ThreadModel::Single)
363 addPass(createLowerAtomicPass());
365 addPass(createAtomicExpandPass());
367 // Cmpxchg instructions are often used with a subsequent comparison to
368 // determine whether it succeeded. We can exploit existing control-flow in
369 // ldrex/strex loops to simplify this, but it needs tidying up.
370 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
371 addPass(createCFGSimplificationPass(-1, [this](const Function &F) {
372 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
373 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
376 TargetPassConfig::addIRPasses();
378 // Match interleaved memory accesses to ldN/stN intrinsics.
379 if (TM->getOptLevel() != CodeGenOpt::None)
380 addPass(createInterleavedAccessPass());
383 bool ARMPassConfig::addPreISel() {
384 if ((TM->getOptLevel() != CodeGenOpt::None &&
385 EnableGlobalMerge == cl::BOU_UNSET) ||
386 EnableGlobalMerge == cl::BOU_TRUE) {
387 // FIXME: This is using the thumb1 only constant value for
388 // maximal global offset for merging globals. We may want
389 // to look into using the old value for non-thumb1 code of
390 // 4095 based on the TargetMachine, but this starts to become
391 // tricky when doing code gen per function.
392 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
393 (EnableGlobalMerge == cl::BOU_UNSET);
394 // Merging of extern globals is enabled by default on non-Mach-O as we
395 // expect it to be generally either beneficial or harmless. On Mach-O it
396 // is disabled as we emit the .subsections_via_symbols directive which
397 // means that merging extern globals is not safe.
398 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
399 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
400 MergeExternalByDefault));
406 bool ARMPassConfig::addInstSelector() {
407 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
411 #ifdef LLVM_BUILD_GLOBAL_ISEL
412 bool ARMPassConfig::addIRTranslator() {
413 addPass(new IRTranslator());
417 bool ARMPassConfig::addLegalizeMachineIR() {
418 addPass(new Legalizer());
422 bool ARMPassConfig::addRegBankSelect() {
423 addPass(new RegBankSelect());
427 bool ARMPassConfig::addGlobalInstructionSelect() {
428 addPass(new InstructionSelect());
433 void ARMPassConfig::addPreRegAlloc() {
434 if (getOptLevel() != CodeGenOpt::None) {
435 addPass(createMLxExpansionPass());
437 if (EnableARMLoadStoreOpt)
438 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
440 if (!DisableA15SDOptimization)
441 addPass(createA15SDOptimizerPass());
445 void ARMPassConfig::addPreSched2() {
446 if (getOptLevel() != CodeGenOpt::None) {
447 if (EnableARMLoadStoreOpt)
448 addPass(createARMLoadStoreOptimizationPass());
450 addPass(new ARMExecutionDepsFix());
453 // Expand some pseudo instructions into multiple instructions to allow
454 // proper scheduling.
455 addPass(createARMExpandPseudoPass());
457 if (getOptLevel() != CodeGenOpt::None) {
458 // in v8, IfConversion depends on Thumb instruction widths
459 addPass(createThumb2SizeReductionPass([this](const Function &F) {
460 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
463 addPass(createIfConverter([](const MachineFunction &MF) {
464 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
467 addPass(createThumb2ITBlockPass());
470 void ARMPassConfig::addPreEmitPass() {
471 addPass(createThumb2SizeReductionPass());
473 // Constant island pass work on unbundled instructions.
474 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
475 return MF.getSubtarget<ARMSubtarget>().isThumb2();
478 // Don't optimize barriers at -O0.
479 if (getOptLevel() != CodeGenOpt::None)
480 addPass(createARMOptimizeBarriersPass());
482 addPass(createARMConstantIslandPass());