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 // Use the optminsize to identify the subtarget, but don't use it in the 267 // feature string. 268 std::string Key = CPU + FS; 269 if (F.optForMinSize()) 270 Key += "+minsize"; 271 272 auto &I = SubtargetMap[Key]; 273 if (!I) { 274 // This needs to be done before we create a new subtarget since any 275 // creation will depend on the TM and the code generation flags on the 276 // function that reside in TargetOptions. 277 resetTargetOptions(F); 278 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle, 279 F.optForMinSize()); 280 281 if (!I->isThumb() && !I->hasARMOps()) 282 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 283 "instructions, but the target does not support ARM mode execution."); 284 } 285 286 return I.get(); 287 } 288 289 TargetTransformInfo 290 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) { 291 return TargetTransformInfo(ARMTTIImpl(this, F)); 292 } 293 294 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 295 StringRef CPU, StringRef FS, 296 const TargetOptions &Options, 297 Optional<Reloc::Model> RM, 298 Optional<CodeModel::Model> CM, 299 CodeGenOpt::Level OL, bool JIT) 300 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 301 302 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 303 StringRef CPU, StringRef FS, 304 const TargetOptions &Options, 305 Optional<Reloc::Model> RM, 306 Optional<CodeModel::Model> CM, 307 CodeGenOpt::Level OL, bool JIT) 308 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 309 310 namespace { 311 312 /// ARM Code Generator Pass Configuration Options. 313 class ARMPassConfig : public TargetPassConfig { 314 public: 315 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 316 : TargetPassConfig(TM, PM) { 317 if (TM.getOptLevel() != CodeGenOpt::None) { 318 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(), 319 TM.getTargetFeatureString()); 320 if (STI.hasFeature(ARM::FeatureUseMISched)) 321 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 322 } 323 } 324 325 ARMBaseTargetMachine &getARMTargetMachine() const { 326 return getTM<ARMBaseTargetMachine>(); 327 } 328 329 ScheduleDAGInstrs * 330 createMachineScheduler(MachineSchedContext *C) const override { 331 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 332 // add DAG Mutations here. 333 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 334 if (ST.hasFusion()) 335 DAG->addMutation(createARMMacroFusionDAGMutation()); 336 return DAG; 337 } 338 339 ScheduleDAGInstrs * 340 createPostMachineScheduler(MachineSchedContext *C) const override { 341 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 342 // add DAG Mutations here. 343 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 344 if (ST.hasFusion()) 345 DAG->addMutation(createARMMacroFusionDAGMutation()); 346 return DAG; 347 } 348 349 void addIRPasses() override; 350 void addCodeGenPrepare() override; 351 bool addPreISel() override; 352 bool addInstSelector() override; 353 bool addIRTranslator() override; 354 bool addLegalizeMachineIR() override; 355 bool addRegBankSelect() override; 356 bool addGlobalInstructionSelect() override; 357 void addPreRegAlloc() override; 358 void addPreSched2() override; 359 void addPreEmitPass() override; 360 }; 361 362 class ARMExecutionDomainFix : public ExecutionDomainFix { 363 public: 364 static char ID; 365 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {} 366 StringRef getPassName() const override { 367 return "ARM Execution Domain Fix"; 368 } 369 }; 370 char ARMExecutionDomainFix::ID; 371 372 } // end anonymous namespace 373 374 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix", 375 "ARM Execution Domain Fix", false, false) 376 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 377 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix", 378 "ARM Execution Domain Fix", false, false) 379 380 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 381 return new ARMPassConfig(*this, PM); 382 } 383 384 void ARMPassConfig::addIRPasses() { 385 if (TM->Options.ThreadModel == ThreadModel::Single) 386 addPass(createLowerAtomicPass()); 387 else 388 addPass(createAtomicExpandPass()); 389 390 // Cmpxchg instructions are often used with a subsequent comparison to 391 // determine whether it succeeded. We can exploit existing control-flow in 392 // ldrex/strex loops to simplify this, but it needs tidying up. 393 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 394 addPass(createCFGSimplificationPass( 395 1, false, false, true, true, [this](const Function &F) { 396 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F); 397 return ST.hasAnyDataBarrier() && !ST.isThumb1Only(); 398 })); 399 400 TargetPassConfig::addIRPasses(); 401 402 // Match interleaved memory accesses to ldN/stN intrinsics. 403 if (TM->getOptLevel() != CodeGenOpt::None) 404 addPass(createInterleavedAccessPass()); 405 } 406 407 void ARMPassConfig::addCodeGenPrepare() { 408 if (getOptLevel() != CodeGenOpt::None) 409 addPass(createARMCodeGenPreparePass()); 410 TargetPassConfig::addCodeGenPrepare(); 411 } 412 413 bool ARMPassConfig::addPreISel() { 414 if (getOptLevel() != CodeGenOpt::None) 415 addPass(createARMParallelDSPPass()); 416 417 if ((TM->getOptLevel() != CodeGenOpt::None && 418 EnableGlobalMerge == cl::BOU_UNSET) || 419 EnableGlobalMerge == cl::BOU_TRUE) { 420 // FIXME: This is using the thumb1 only constant value for 421 // maximal global offset for merging globals. We may want 422 // to look into using the old value for non-thumb1 code of 423 // 4095 based on the TargetMachine, but this starts to become 424 // tricky when doing code gen per function. 425 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 426 (EnableGlobalMerge == cl::BOU_UNSET); 427 // Merging of extern globals is enabled by default on non-Mach-O as we 428 // expect it to be generally either beneficial or harmless. On Mach-O it 429 // is disabled as we emit the .subsections_via_symbols directive which 430 // means that merging extern globals is not safe. 431 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 432 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 433 MergeExternalByDefault)); 434 } 435 436 return false; 437 } 438 439 bool ARMPassConfig::addInstSelector() { 440 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 441 return false; 442 } 443 444 bool ARMPassConfig::addIRTranslator() { 445 addPass(new IRTranslator()); 446 return false; 447 } 448 449 bool ARMPassConfig::addLegalizeMachineIR() { 450 addPass(new Legalizer()); 451 return false; 452 } 453 454 bool ARMPassConfig::addRegBankSelect() { 455 addPass(new RegBankSelect()); 456 return false; 457 } 458 459 bool ARMPassConfig::addGlobalInstructionSelect() { 460 addPass(new InstructionSelect()); 461 return false; 462 } 463 464 void ARMPassConfig::addPreRegAlloc() { 465 if (getOptLevel() != CodeGenOpt::None) { 466 addPass(createMLxExpansionPass()); 467 468 if (EnableARMLoadStoreOpt) 469 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 470 471 if (!DisableA15SDOptimization) 472 addPass(createA15SDOptimizerPass()); 473 } 474 } 475 476 void ARMPassConfig::addPreSched2() { 477 if (getOptLevel() != CodeGenOpt::None) { 478 if (EnableARMLoadStoreOpt) 479 addPass(createARMLoadStoreOptimizationPass()); 480 481 addPass(new ARMExecutionDomainFix()); 482 addPass(createBreakFalseDeps()); 483 } 484 485 // Expand some pseudo instructions into multiple instructions to allow 486 // proper scheduling. 487 addPass(createARMExpandPseudoPass()); 488 489 if (getOptLevel() != CodeGenOpt::None) { 490 // in v8, IfConversion depends on Thumb instruction widths 491 addPass(createThumb2SizeReductionPass([this](const Function &F) { 492 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 493 })); 494 495 addPass(createIfConverter([](const MachineFunction &MF) { 496 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 497 })); 498 } 499 addPass(createThumb2ITBlockPass()); 500 } 501 502 void ARMPassConfig::addPreEmitPass() { 503 addPass(createThumb2SizeReductionPass()); 504 505 // Constant island pass work on unbundled instructions. 506 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 507 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 508 })); 509 510 // Don't optimize barriers at -O0. 511 if (getOptLevel() != CodeGenOpt::None) 512 addPass(createARMOptimizeBarriersPass()); 513 514 addPass(createARMConstantIslandPass()); 515 } 516