1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // 10 //===----------------------------------------------------------------------===// 11 12 #include "ARMTargetMachine.h" 13 #include "ARM.h" 14 #include "ARMMacroFusion.h" 15 #include "ARMSubtarget.h" 16 #include "ARMTargetObjectFile.h" 17 #include "ARMTargetTransformInfo.h" 18 #include "MCTargetDesc/ARMMCTargetDesc.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/CodeGen/ExecutionDomainFix.h" 25 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 26 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 27 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" 28 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h" 29 #include "llvm/CodeGen/GlobalISel/Legalizer.h" 30 #include "llvm/CodeGen/GlobalISel/LegalizerInfo.h" 31 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h" 32 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 33 #include "llvm/CodeGen/MachineFunction.h" 34 #include "llvm/CodeGen/MachineScheduler.h" 35 #include "llvm/CodeGen/Passes.h" 36 #include "llvm/CodeGen/TargetPassConfig.h" 37 #include "llvm/IR/Attributes.h" 38 #include "llvm/IR/DataLayout.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/CodeGen.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/TargetParser.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Target/TargetLoweringObjectFile.h" 47 #include "llvm/Target/TargetOptions.h" 48 #include "llvm/Transforms/Scalar.h" 49 #include <cassert> 50 #include <memory> 51 #include <string> 52 53 using namespace llvm; 54 55 static cl::opt<bool> 56 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden, 57 cl::desc("Inhibit optimization of S->D register accesses on A15"), 58 cl::init(false)); 59 60 static cl::opt<bool> 61 EnableAtomicTidy("arm-atomic-cfg-tidy", cl::Hidden, 62 cl::desc("Run SimplifyCFG after expanding atomic operations" 63 " to make use of cmpxchg flow-based information"), 64 cl::init(true)); 65 66 static cl::opt<bool> 67 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden, 68 cl::desc("Enable ARM load/store optimization pass"), 69 cl::init(true)); 70 71 // FIXME: Unify control over GlobalMerge. 72 static cl::opt<cl::boolOrDefault> 73 EnableGlobalMerge("arm-global-merge", cl::Hidden, 74 cl::desc("Enable the global merge pass")); 75 76 namespace llvm { 77 void initializeARMExecutionDomainFixPass(PassRegistry&); 78 } 79 80 extern "C" void LLVMInitializeARMTarget() { 81 // Register the target. 82 RegisterTargetMachine<ARMLETargetMachine> X(getTheARMLETarget()); 83 RegisterTargetMachine<ARMLETargetMachine> A(getTheThumbLETarget()); 84 RegisterTargetMachine<ARMBETargetMachine> Y(getTheARMBETarget()); 85 RegisterTargetMachine<ARMBETargetMachine> B(getTheThumbBETarget()); 86 87 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 88 initializeGlobalISel(Registry); 89 initializeARMLoadStoreOptPass(Registry); 90 initializeARMPreAllocLoadStoreOptPass(Registry); 91 initializeARMParallelDSPPass(Registry); 92 initializeARMCodeGenPreparePass(Registry); 93 initializeARMConstantIslandsPass(Registry); 94 initializeARMExecutionDomainFixPass(Registry); 95 initializeARMExpandPseudoPass(Registry); 96 initializeThumb2SizeReducePass(Registry); 97 } 98 99 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 100 if (TT.isOSBinFormatMachO()) 101 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 102 if (TT.isOSWindows()) 103 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 104 return llvm::make_unique<ARMElfTargetObjectFile>(); 105 } 106 107 static ARMBaseTargetMachine::ARMABI 108 computeTargetABI(const Triple &TT, StringRef CPU, 109 const TargetOptions &Options) { 110 StringRef ABIName = Options.MCOptions.getABIName(); 111 112 if (ABIName.empty()) 113 ABIName = ARM::computeDefaultTargetABI(TT, CPU); 114 115 if (ABIName == "aapcs16") 116 return ARMBaseTargetMachine::ARM_ABI_AAPCS16; 117 else if (ABIName.startswith("aapcs")) 118 return ARMBaseTargetMachine::ARM_ABI_AAPCS; 119 else if (ABIName.startswith("apcs")) 120 return ARMBaseTargetMachine::ARM_ABI_APCS; 121 122 llvm_unreachable("Unhandled/unknown ABI Name!"); 123 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN; 124 } 125 126 static std::string computeDataLayout(const Triple &TT, StringRef CPU, 127 const TargetOptions &Options, 128 bool isLittle) { 129 auto ABI = computeTargetABI(TT, CPU, Options); 130 std::string Ret; 131 132 if (isLittle) 133 // Little endian. 134 Ret += "e"; 135 else 136 // Big endian. 137 Ret += "E"; 138 139 Ret += DataLayout::getManglingComponent(TT); 140 141 // Pointers are 32 bits and aligned to 32 bits. 142 Ret += "-p:32:32"; 143 144 // ABIs other than APCS have 64 bit integers with natural alignment. 145 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS) 146 Ret += "-i64:64"; 147 148 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32 149 // bits, others to 64 bits. We always try to align to 64 bits. 150 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 151 Ret += "-f64:32:64"; 152 153 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others 154 // to 64. We always ty to give them natural alignment. 155 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 156 Ret += "-v64:32:64-v128:32:128"; 157 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16) 158 Ret += "-v128:64:128"; 159 160 // Try to align aggregates to 32 bits (the default is 64 bits, which has no 161 // particular hardware support on 32-bit ARM). 162 Ret += "-a:0:32"; 163 164 // Integer registers are 32 bits. 165 Ret += "-n32"; 166 167 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit 168 // aligned everywhere else. 169 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 170 Ret += "-S128"; 171 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS) 172 Ret += "-S64"; 173 else 174 Ret += "-S32"; 175 176 return Ret; 177 } 178 179 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 180 Optional<Reloc::Model> RM) { 181 if (!RM.hasValue()) 182 // Default relocation model on Darwin is PIC. 183 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static; 184 185 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI) 186 assert(TT.isOSBinFormatELF() && 187 "ROPI/RWPI currently only supported for ELF"); 188 189 // DynamicNoPIC is only used on darwin. 190 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin()) 191 return Reloc::Static; 192 193 return *RM; 194 } 195 196 /// Create an ARM architecture model. 197 /// 198 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 199 StringRef CPU, StringRef FS, 200 const TargetOptions &Options, 201 Optional<Reloc::Model> RM, 202 Optional<CodeModel::Model> CM, 203 CodeGenOpt::Level OL, bool isLittle) 204 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 205 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 206 getEffectiveCodeModel(CM, CodeModel::Small), OL), 207 TargetABI(computeTargetABI(TT, CPU, Options)), 208 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 209 210 // Default to triple-appropriate float ABI 211 if (Options.FloatABIType == FloatABI::Default) { 212 if (isTargetHardFloat()) 213 this->Options.FloatABIType = FloatABI::Hard; 214 else 215 this->Options.FloatABIType = FloatABI::Soft; 216 } 217 218 // Default to triple-appropriate EABI 219 if (Options.EABIVersion == EABI::Default || 220 Options.EABIVersion == EABI::Unknown) { 221 // musl is compatible with glibc with regard to EABI version 222 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 223 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 224 TargetTriple.getEnvironment() == Triple::MuslEABI || 225 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 226 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 227 this->Options.EABIVersion = EABI::GNU; 228 else 229 this->Options.EABIVersion = EABI::EABI5; 230 } 231 232 if (TT.isOSBinFormatMachO()) { 233 this->Options.TrapUnreachable = true; 234 this->Options.NoTrapAfterNoreturn = true; 235 } 236 237 initAsmInfo(); 238 } 239 240 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 241 242 const ARMSubtarget * 243 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 244 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 245 Attribute FSAttr = F.getFnAttribute("target-features"); 246 247 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 248 ? CPUAttr.getValueAsString().str() 249 : TargetCPU; 250 std::string FS = !FSAttr.hasAttribute(Attribute::None) 251 ? FSAttr.getValueAsString().str() 252 : TargetFS; 253 254 // FIXME: This is related to the code below to reset the target options, 255 // we need to know whether or not the soft float flag is set on the 256 // function before we can generate a subtarget. We also need to use 257 // it as a key for the subtarget since that can be the only difference 258 // between two functions. 259 bool SoftFloat = 260 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 261 // If the soft float attribute is set on the function turn on the soft float 262 // subtarget feature. 263 if (SoftFloat) 264 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 265 266 auto &I = SubtargetMap[CPU + FS]; 267 if (!I) { 268 // This needs to be done before we create a new subtarget since any 269 // creation will depend on the TM and the code generation flags on the 270 // function that reside in TargetOptions. 271 resetTargetOptions(F); 272 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle); 273 274 if (!I->isThumb() && !I->hasARMOps()) 275 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 276 "instructions, but the target does not support ARM mode execution."); 277 } 278 279 return I.get(); 280 } 281 282 TargetTransformInfo 283 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) { 284 return TargetTransformInfo(ARMTTIImpl(this, F)); 285 } 286 287 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 288 StringRef CPU, StringRef FS, 289 const TargetOptions &Options, 290 Optional<Reloc::Model> RM, 291 Optional<CodeModel::Model> CM, 292 CodeGenOpt::Level OL, bool JIT) 293 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 294 295 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 296 StringRef CPU, StringRef FS, 297 const TargetOptions &Options, 298 Optional<Reloc::Model> RM, 299 Optional<CodeModel::Model> CM, 300 CodeGenOpt::Level OL, bool JIT) 301 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 302 303 namespace { 304 305 /// ARM Code Generator Pass Configuration Options. 306 class ARMPassConfig : public TargetPassConfig { 307 public: 308 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 309 : TargetPassConfig(TM, PM) { 310 if (TM.getOptLevel() != CodeGenOpt::None) { 311 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(), 312 TM.getTargetFeatureString()); 313 if (STI.hasFeature(ARM::FeatureUseMISched)) 314 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 315 } 316 } 317 318 ARMBaseTargetMachine &getARMTargetMachine() const { 319 return getTM<ARMBaseTargetMachine>(); 320 } 321 322 ScheduleDAGInstrs * 323 createMachineScheduler(MachineSchedContext *C) const override { 324 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 325 // add DAG Mutations here. 326 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 327 if (ST.hasFusion()) 328 DAG->addMutation(createARMMacroFusionDAGMutation()); 329 return DAG; 330 } 331 332 ScheduleDAGInstrs * 333 createPostMachineScheduler(MachineSchedContext *C) const override { 334 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 335 // add DAG Mutations here. 336 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 337 if (ST.hasFusion()) 338 DAG->addMutation(createARMMacroFusionDAGMutation()); 339 return DAG; 340 } 341 342 void addIRPasses() override; 343 void addCodeGenPrepare() override; 344 bool addPreISel() override; 345 bool addInstSelector() override; 346 bool addIRTranslator() override; 347 bool addLegalizeMachineIR() override; 348 bool addRegBankSelect() override; 349 bool addGlobalInstructionSelect() override; 350 void addPreRegAlloc() override; 351 void addPreSched2() override; 352 void addPreEmitPass() override; 353 }; 354 355 class ARMExecutionDomainFix : public ExecutionDomainFix { 356 public: 357 static char ID; 358 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {} 359 StringRef getPassName() const override { 360 return "ARM Execution Domain Fix"; 361 } 362 }; 363 char ARMExecutionDomainFix::ID; 364 365 } // end anonymous namespace 366 367 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix", 368 "ARM Execution Domain Fix", false, false) 369 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 370 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix", 371 "ARM Execution Domain Fix", false, false) 372 373 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 374 return new ARMPassConfig(*this, PM); 375 } 376 377 void ARMPassConfig::addIRPasses() { 378 if (TM->Options.ThreadModel == ThreadModel::Single) 379 addPass(createLowerAtomicPass()); 380 else 381 addPass(createAtomicExpandPass()); 382 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(); 391 })); 392 393 TargetPassConfig::addIRPasses(); 394 395 // Match interleaved memory accesses to ldN/stN intrinsics. 396 if (TM->getOptLevel() != CodeGenOpt::None) 397 addPass(createInterleavedAccessPass()); 398 } 399 400 void ARMPassConfig::addCodeGenPrepare() { 401 if (getOptLevel() != CodeGenOpt::None) 402 addPass(createARMCodeGenPreparePass()); 403 TargetPassConfig::addCodeGenPrepare(); 404 } 405 406 bool ARMPassConfig::addPreISel() { 407 if (getOptLevel() != CodeGenOpt::None) 408 addPass(createARMParallelDSPPass()); 409 410 if ((TM->getOptLevel() != CodeGenOpt::None && 411 EnableGlobalMerge == cl::BOU_UNSET) || 412 EnableGlobalMerge == cl::BOU_TRUE) { 413 // FIXME: This is using the thumb1 only constant value for 414 // maximal global offset for merging globals. We may want 415 // to look into using the old value for non-thumb1 code of 416 // 4095 based on the TargetMachine, but this starts to become 417 // tricky when doing code gen per function. 418 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 419 (EnableGlobalMerge == cl::BOU_UNSET); 420 // Merging of extern globals is enabled by default on non-Mach-O as we 421 // expect it to be generally either beneficial or harmless. On Mach-O it 422 // is disabled as we emit the .subsections_via_symbols directive which 423 // means that merging extern globals is not safe. 424 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 425 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 426 MergeExternalByDefault)); 427 } 428 429 return false; 430 } 431 432 bool ARMPassConfig::addInstSelector() { 433 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 434 return false; 435 } 436 437 bool ARMPassConfig::addIRTranslator() { 438 addPass(new IRTranslator()); 439 return false; 440 } 441 442 bool ARMPassConfig::addLegalizeMachineIR() { 443 addPass(new Legalizer()); 444 return false; 445 } 446 447 bool ARMPassConfig::addRegBankSelect() { 448 addPass(new RegBankSelect()); 449 return false; 450 } 451 452 bool ARMPassConfig::addGlobalInstructionSelect() { 453 addPass(new InstructionSelect()); 454 return false; 455 } 456 457 void ARMPassConfig::addPreRegAlloc() { 458 if (getOptLevel() != CodeGenOpt::None) { 459 addPass(createMLxExpansionPass()); 460 461 if (EnableARMLoadStoreOpt) 462 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 463 464 if (!DisableA15SDOptimization) 465 addPass(createA15SDOptimizerPass()); 466 } 467 } 468 469 void ARMPassConfig::addPreSched2() { 470 if (getOptLevel() != CodeGenOpt::None) { 471 if (EnableARMLoadStoreOpt) 472 addPass(createARMLoadStoreOptimizationPass()); 473 474 addPass(new ARMExecutionDomainFix()); 475 addPass(createBreakFalseDeps()); 476 } 477 478 // Expand some pseudo instructions into multiple instructions to allow 479 // proper scheduling. 480 addPass(createARMExpandPseudoPass()); 481 482 if (getOptLevel() != CodeGenOpt::None) { 483 // in v8, IfConversion depends on Thumb instruction widths 484 addPass(createThumb2SizeReductionPass([this](const Function &F) { 485 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 486 })); 487 488 addPass(createIfConverter([](const MachineFunction &MF) { 489 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 490 })); 491 } 492 addPass(createThumb2ITBlockPass()); 493 } 494 495 void ARMPassConfig::addPreEmitPass() { 496 addPass(createThumb2SizeReductionPass()); 497 498 // Constant island pass work on unbundled instructions. 499 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 500 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 501 })); 502 503 // Don't optimize barriers at -O0. 504 if (getOptLevel() != CodeGenOpt::None) 505 addPass(createARMOptimizeBarriersPass()); 506 507 addPass(createARMConstantIslandPass()); 508 } 509