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/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/TargetLoweringObjectFile.h"
38 #include "llvm/CodeGen/TargetPassConfig.h"
39 #include "llvm/IR/Attributes.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/Pass.h"
43 #include "llvm/Support/CodeGen.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/TargetParser.h"
47 #include "llvm/Support/TargetRegistry.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);
94 initializeARMExpandPseudoPass(Registry);
95 initializeThumb2SizeReducePass(Registry);
98 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
99 if (TT.isOSBinFormatMachO())
100 return llvm::make_unique<TargetLoweringObjectFileMachO>();
101 if (TT.isOSWindows())
102 return llvm::make_unique<TargetLoweringObjectFileCOFF>();
103 return llvm::make_unique<ARMElfTargetObjectFile>();
106 static ARMBaseTargetMachine::ARMABI
107 computeTargetABI(const Triple &TT, StringRef CPU,
108 const TargetOptions &Options) {
109 StringRef ABIName = Options.MCOptions.getABIName();
112 ABIName = ARM::computeDefaultTargetABI(TT, CPU);
114 if (ABIName == "aapcs16")
115 return ARMBaseTargetMachine::ARM_ABI_AAPCS16;
116 else if (ABIName.startswith("aapcs"))
117 return ARMBaseTargetMachine::ARM_ABI_AAPCS;
118 else if (ABIName.startswith("apcs"))
119 return ARMBaseTargetMachine::ARM_ABI_APCS;
121 llvm_unreachable("Unhandled/unknown ABI Name!");
122 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN;
125 static std::string computeDataLayout(const Triple &TT, StringRef CPU,
126 const TargetOptions &Options,
128 auto ABI = computeTargetABI(TT, CPU, Options);
138 Ret += DataLayout::getManglingComponent(TT);
140 // Pointers are 32 bits and aligned to 32 bits.
143 // ABIs other than APCS have 64 bit integers with natural alignment.
144 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS)
147 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32
148 // bits, others to 64 bits. We always try to align to 64 bits.
149 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
152 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others
153 // to 64. We always ty to give them natural alignment.
154 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS)
155 Ret += "-v64:32:64-v128:32:128";
156 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16)
157 Ret += "-v128:64:128";
159 // Try to align aggregates to 32 bits (the default is 64 bits, which has no
160 // particular hardware support on 32-bit ARM).
163 // Integer registers are 32 bits.
166 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit
167 // aligned everywhere else.
168 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
170 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS)
178 static Reloc::Model getEffectiveRelocModel(const Triple &TT,
179 Optional<Reloc::Model> RM) {
181 // Default relocation model on Darwin is PIC.
182 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static;
184 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI)
185 assert(TT.isOSBinFormatELF() &&
186 "ROPI/RWPI currently only supported for ELF");
188 // DynamicNoPIC is only used on darwin.
189 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin())
190 return Reloc::Static;
195 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) {
198 return CodeModel::Small;
201 /// Create an ARM architecture model.
203 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT,
204 StringRef CPU, StringRef FS,
205 const TargetOptions &Options,
206 Optional<Reloc::Model> RM,
207 Optional<CodeModel::Model> CM,
208 CodeGenOpt::Level OL, bool isLittle)
209 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
210 CPU, FS, Options, getEffectiveRelocModel(TT, RM),
211 getEffectiveCodeModel(CM), OL),
212 TargetABI(computeTargetABI(TT, CPU, Options)),
213 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) {
215 // Default to triple-appropriate float ABI
216 if (Options.FloatABIType == FloatABI::Default) {
217 if (TargetTriple.getEnvironment() == Triple::GNUEABIHF ||
218 TargetTriple.getEnvironment() == Triple::MuslEABIHF ||
219 TargetTriple.getEnvironment() == Triple::EABIHF ||
220 TargetTriple.isOSWindows() ||
221 TargetABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16)
222 this->Options.FloatABIType = FloatABI::Hard;
224 this->Options.FloatABIType = FloatABI::Soft;
227 // Default to triple-appropriate EABI
228 if (Options.EABIVersion == EABI::Default ||
229 Options.EABIVersion == EABI::Unknown) {
230 // musl is compatible with glibc with regard to EABI version
231 if ((TargetTriple.getEnvironment() == Triple::GNUEABI ||
232 TargetTriple.getEnvironment() == Triple::GNUEABIHF ||
233 TargetTriple.getEnvironment() == Triple::MuslEABI ||
234 TargetTriple.getEnvironment() == Triple::MuslEABIHF) &&
235 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin()))
236 this->Options.EABIVersion = EABI::GNU;
238 this->Options.EABIVersion = EABI::EABI5;
244 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default;
247 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const {
248 Attribute CPUAttr = F.getFnAttribute("target-cpu");
249 Attribute FSAttr = F.getFnAttribute("target-features");
251 std::string CPU = !CPUAttr.hasAttribute(Attribute::None)
252 ? CPUAttr.getValueAsString().str()
254 std::string FS = !FSAttr.hasAttribute(Attribute::None)
255 ? FSAttr.getValueAsString().str()
258 // FIXME: This is related to the code below to reset the target options,
259 // we need to know whether or not the soft float flag is set on the
260 // function before we can generate a subtarget. We also need to use
261 // it as a key for the subtarget since that can be the only difference
262 // between two functions.
264 F.getFnAttribute("use-soft-float").getValueAsString() == "true";
265 // If the soft float attribute is set on the function turn on the soft float
266 // subtarget feature.
268 FS += FS.empty() ? "+soft-float" : ",+soft-float";
270 auto &I = SubtargetMap[CPU + FS];
272 // This needs to be done before we create a new subtarget since any
273 // creation will depend on the TM and the code generation flags on the
274 // function that reside in TargetOptions.
275 resetTargetOptions(F);
276 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle);
278 if (!I->isThumb() && !I->hasARMOps())
279 F.getContext().emitError("Function '" + F.getName() + "' uses ARM "
280 "instructions, but the target does not support ARM mode execution.");
287 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) {
288 return TargetTransformInfo(ARMTTIImpl(this, F));
291 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT,
292 StringRef CPU, StringRef FS,
293 const TargetOptions &Options,
294 Optional<Reloc::Model> RM,
295 Optional<CodeModel::Model> CM,
296 CodeGenOpt::Level OL, bool JIT)
297 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
299 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT,
300 StringRef CPU, StringRef FS,
301 const TargetOptions &Options,
302 Optional<Reloc::Model> RM,
303 Optional<CodeModel::Model> CM,
304 CodeGenOpt::Level OL, bool JIT)
305 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
309 /// ARM Code Generator Pass Configuration Options.
310 class ARMPassConfig : public TargetPassConfig {
312 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM)
313 : TargetPassConfig(TM, PM) {
314 if (TM.getOptLevel() != CodeGenOpt::None) {
315 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(),
316 TM.getTargetFeatureString());
317 if (STI.hasFeature(ARM::FeatureUseMISched))
318 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID);
322 ARMBaseTargetMachine &getARMTargetMachine() const {
323 return getTM<ARMBaseTargetMachine>();
327 createMachineScheduler(MachineSchedContext *C) const override {
328 ScheduleDAGMILive *DAG = createGenericSchedLive(C);
329 // add DAG Mutations here.
330 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
332 DAG->addMutation(createARMMacroFusionDAGMutation());
337 createPostMachineScheduler(MachineSchedContext *C) const override {
338 ScheduleDAGMI *DAG = createGenericSchedPostRA(C);
339 // add DAG Mutations here.
340 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>();
342 DAG->addMutation(createARMMacroFusionDAGMutation());
346 void addIRPasses() override;
347 bool addPreISel() override;
348 bool addInstSelector() override;
349 bool addIRTranslator() override;
350 bool addLegalizeMachineIR() override;
351 bool addRegBankSelect() override;
352 bool addGlobalInstructionSelect() override;
353 void addPreRegAlloc() override;
354 void addPreSched2() override;
355 void addPreEmitPass() override;
358 class ARMExecutionDepsFix : public ExecutionDepsFix {
361 ARMExecutionDepsFix() : ExecutionDepsFix(ID, ARM::DPRRegClass) {}
362 StringRef getPassName() const override {
363 return "ARM Execution Dependency Fix";
366 char ARMExecutionDepsFix::ID;
368 } // end anonymous namespace
370 INITIALIZE_PASS(ARMExecutionDepsFix, "arm-execution-deps-fix",
371 "ARM Execution Dependency Fix", false, false)
373 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) {
374 return new ARMPassConfig(*this, PM);
377 void ARMPassConfig::addIRPasses() {
378 if (TM->Options.ThreadModel == ThreadModel::Single)
379 addPass(createLowerAtomicPass());
381 addPass(createAtomicExpandPass());
383 // Cmpxchg instructions are often used with a subsequent comparison to
384 // determine whether it succeeded. We can exploit existing control-flow in
385 // ldrex/strex loops to simplify this, but it needs tidying up.
386 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy)
387 addPass(createCFGSimplificationPass(
388 1, false, false, true, true, [this](const Function &F) {
389 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F);
390 return ST.hasAnyDataBarrier() && !ST.isThumb1Only();
393 TargetPassConfig::addIRPasses();
395 // Match interleaved memory accesses to ldN/stN intrinsics.
396 if (TM->getOptLevel() != CodeGenOpt::None)
397 addPass(createInterleavedAccessPass());
400 bool ARMPassConfig::addPreISel() {
401 if ((TM->getOptLevel() != CodeGenOpt::None &&
402 EnableGlobalMerge == cl::BOU_UNSET) ||
403 EnableGlobalMerge == cl::BOU_TRUE) {
404 // FIXME: This is using the thumb1 only constant value for
405 // maximal global offset for merging globals. We may want
406 // to look into using the old value for non-thumb1 code of
407 // 4095 based on the TargetMachine, but this starts to become
408 // tricky when doing code gen per function.
409 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) &&
410 (EnableGlobalMerge == cl::BOU_UNSET);
411 // Merging of extern globals is enabled by default on non-Mach-O as we
412 // expect it to be generally either beneficial or harmless. On Mach-O it
413 // is disabled as we emit the .subsections_via_symbols directive which
414 // means that merging extern globals is not safe.
415 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO();
416 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize,
417 MergeExternalByDefault));
423 bool ARMPassConfig::addInstSelector() {
424 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel()));
428 bool ARMPassConfig::addIRTranslator() {
429 addPass(new IRTranslator());
433 bool ARMPassConfig::addLegalizeMachineIR() {
434 addPass(new Legalizer());
438 bool ARMPassConfig::addRegBankSelect() {
439 addPass(new RegBankSelect());
443 bool ARMPassConfig::addGlobalInstructionSelect() {
444 addPass(new InstructionSelect());
448 void ARMPassConfig::addPreRegAlloc() {
449 if (getOptLevel() != CodeGenOpt::None) {
450 addPass(createMLxExpansionPass());
452 if (EnableARMLoadStoreOpt)
453 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true));
455 if (!DisableA15SDOptimization)
456 addPass(createA15SDOptimizerPass());
460 void ARMPassConfig::addPreSched2() {
461 if (getOptLevel() != CodeGenOpt::None) {
462 if (EnableARMLoadStoreOpt)
463 addPass(createARMLoadStoreOptimizationPass());
465 addPass(new ARMExecutionDepsFix());
468 // Expand some pseudo instructions into multiple instructions to allow
469 // proper scheduling.
470 addPass(createARMExpandPseudoPass());
472 if (getOptLevel() != CodeGenOpt::None) {
473 // in v8, IfConversion depends on Thumb instruction widths
474 addPass(createThumb2SizeReductionPass([this](const Function &F) {
475 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT();
478 addPass(createIfConverter([](const MachineFunction &MF) {
479 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only();
482 addPass(createThumb2ITBlockPass());
485 void ARMPassConfig::addPreEmitPass() {
486 addPass(createThumb2SizeReductionPass());
488 // Constant island pass work on unbundled instructions.
489 addPass(createUnpackMachineBundles([](const MachineFunction &MF) {
490 return MF.getSubtarget<ARMSubtarget>().isThumb2();
493 // Don't optimize barriers at -O0.
494 if (getOptLevel() != CodeGenOpt::None)
495 addPass(createARMOptimizeBarriersPass());
497 addPass(createARMConstantIslandPass());