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 // Function pointers are aligned to 8 bits (because the LSB stores the 145 // ARM/Thumb state). 146 Ret += "-Fi8"; 147 148 // ABIs other than APCS have 64 bit integers with natural alignment. 149 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS) 150 Ret += "-i64:64"; 151 152 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32 153 // bits, others to 64 bits. We always try to align to 64 bits. 154 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 155 Ret += "-f64:32:64"; 156 157 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others 158 // to 64. We always ty to give them natural alignment. 159 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 160 Ret += "-v64:32:64-v128:32:128"; 161 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16) 162 Ret += "-v128:64:128"; 163 164 // Try to align aggregates to 32 bits (the default is 64 bits, which has no 165 // particular hardware support on 32-bit ARM). 166 Ret += "-a:0:32"; 167 168 // Integer registers are 32 bits. 169 Ret += "-n32"; 170 171 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit 172 // aligned everywhere else. 173 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 174 Ret += "-S128"; 175 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS) 176 Ret += "-S64"; 177 else 178 Ret += "-S32"; 179 180 return Ret; 181 } 182 183 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 184 Optional<Reloc::Model> RM) { 185 if (!RM.hasValue()) 186 // Default relocation model on Darwin is PIC. 187 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static; 188 189 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI) 190 assert(TT.isOSBinFormatELF() && 191 "ROPI/RWPI currently only supported for ELF"); 192 193 // DynamicNoPIC is only used on darwin. 194 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin()) 195 return Reloc::Static; 196 197 return *RM; 198 } 199 200 /// Create an ARM architecture model. 201 /// 202 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 203 StringRef CPU, StringRef FS, 204 const TargetOptions &Options, 205 Optional<Reloc::Model> RM, 206 Optional<CodeModel::Model> CM, 207 CodeGenOpt::Level OL, bool isLittle) 208 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 209 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 210 getEffectiveCodeModel(CM, CodeModel::Small), OL), 211 TargetABI(computeTargetABI(TT, CPU, Options)), 212 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 213 214 // Default to triple-appropriate float ABI 215 if (Options.FloatABIType == FloatABI::Default) { 216 if (isTargetHardFloat()) 217 this->Options.FloatABIType = FloatABI::Hard; 218 else 219 this->Options.FloatABIType = FloatABI::Soft; 220 } 221 222 // Default to triple-appropriate EABI 223 if (Options.EABIVersion == EABI::Default || 224 Options.EABIVersion == EABI::Unknown) { 225 // musl is compatible with glibc with regard to EABI version 226 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 227 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 228 TargetTriple.getEnvironment() == Triple::MuslEABI || 229 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 230 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 231 this->Options.EABIVersion = EABI::GNU; 232 else 233 this->Options.EABIVersion = EABI::EABI5; 234 } 235 236 if (TT.isOSBinFormatMachO()) { 237 this->Options.TrapUnreachable = true; 238 this->Options.NoTrapAfterNoreturn = true; 239 } 240 241 initAsmInfo(); 242 } 243 244 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 245 246 const ARMSubtarget * 247 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 248 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 249 Attribute FSAttr = F.getFnAttribute("target-features"); 250 251 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 252 ? CPUAttr.getValueAsString().str() 253 : TargetCPU; 254 std::string FS = !FSAttr.hasAttribute(Attribute::None) 255 ? FSAttr.getValueAsString().str() 256 : TargetFS; 257 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. 263 bool SoftFloat = 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. 267 if (SoftFloat) 268 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 269 270 // Use the optminsize to identify the subtarget, but don't use it in the 271 // feature string. 272 std::string Key = CPU + FS; 273 if (F.hasMinSize()) 274 Key += "+minsize"; 275 276 auto &I = SubtargetMap[Key]; 277 if (!I) { 278 // This needs to be done before we create a new subtarget since any 279 // creation will depend on the TM and the code generation flags on the 280 // function that reside in TargetOptions. 281 resetTargetOptions(F); 282 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle, 283 F.hasMinSize()); 284 285 if (!I->isThumb() && !I->hasARMOps()) 286 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 287 "instructions, but the target does not support ARM mode execution."); 288 } 289 290 return I.get(); 291 } 292 293 TargetTransformInfo 294 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) { 295 return TargetTransformInfo(ARMTTIImpl(this, F)); 296 } 297 298 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 299 StringRef CPU, StringRef FS, 300 const TargetOptions &Options, 301 Optional<Reloc::Model> RM, 302 Optional<CodeModel::Model> CM, 303 CodeGenOpt::Level OL, bool JIT) 304 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 305 306 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 307 StringRef CPU, StringRef FS, 308 const TargetOptions &Options, 309 Optional<Reloc::Model> RM, 310 Optional<CodeModel::Model> CM, 311 CodeGenOpt::Level OL, bool JIT) 312 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 313 314 namespace { 315 316 /// ARM Code Generator Pass Configuration Options. 317 class ARMPassConfig : public TargetPassConfig { 318 public: 319 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 320 : TargetPassConfig(TM, PM) { 321 if (TM.getOptLevel() != CodeGenOpt::None) { 322 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(), 323 TM.getTargetFeatureString()); 324 if (STI.hasFeature(ARM::FeatureUseMISched)) 325 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 326 } 327 } 328 329 ARMBaseTargetMachine &getARMTargetMachine() const { 330 return getTM<ARMBaseTargetMachine>(); 331 } 332 333 ScheduleDAGInstrs * 334 createMachineScheduler(MachineSchedContext *C) const override { 335 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 336 // add DAG Mutations here. 337 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 338 if (ST.hasFusion()) 339 DAG->addMutation(createARMMacroFusionDAGMutation()); 340 return DAG; 341 } 342 343 ScheduleDAGInstrs * 344 createPostMachineScheduler(MachineSchedContext *C) const override { 345 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 346 // add DAG Mutations here. 347 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 348 if (ST.hasFusion()) 349 DAG->addMutation(createARMMacroFusionDAGMutation()); 350 return DAG; 351 } 352 353 void addIRPasses() override; 354 void addCodeGenPrepare() override; 355 bool addPreISel() override; 356 bool addInstSelector() override; 357 bool addIRTranslator() override; 358 bool addLegalizeMachineIR() override; 359 bool addRegBankSelect() override; 360 bool addGlobalInstructionSelect() override; 361 void addPreRegAlloc() override; 362 void addPreSched2() override; 363 void addPreEmitPass() override; 364 }; 365 366 class ARMExecutionDomainFix : public ExecutionDomainFix { 367 public: 368 static char ID; 369 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {} 370 StringRef getPassName() const override { 371 return "ARM Execution Domain Fix"; 372 } 373 }; 374 char ARMExecutionDomainFix::ID; 375 376 } // end anonymous namespace 377 378 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix", 379 "ARM Execution Domain Fix", false, false) 380 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 381 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix", 382 "ARM Execution Domain Fix", false, false) 383 384 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 385 return new ARMPassConfig(*this, PM); 386 } 387 388 void ARMPassConfig::addIRPasses() { 389 if (TM->Options.ThreadModel == ThreadModel::Single) 390 addPass(createLowerAtomicPass()); 391 else 392 addPass(createAtomicExpandPass()); 393 394 // Cmpxchg instructions are often used with a subsequent comparison to 395 // determine whether it succeeded. We can exploit existing control-flow in 396 // ldrex/strex loops to simplify this, but it needs tidying up. 397 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 398 addPass(createCFGSimplificationPass( 399 1, false, false, true, true, [this](const Function &F) { 400 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F); 401 return ST.hasAnyDataBarrier() && !ST.isThumb1Only(); 402 })); 403 404 TargetPassConfig::addIRPasses(); 405 406 // Run the parallel DSP pass. 407 if (getOptLevel() == CodeGenOpt::Aggressive) 408 addPass(createARMParallelDSPPass()); 409 410 // Match interleaved memory accesses to ldN/stN intrinsics. 411 if (TM->getOptLevel() != CodeGenOpt::None) 412 addPass(createInterleavedAccessPass()); 413 } 414 415 void ARMPassConfig::addCodeGenPrepare() { 416 if (getOptLevel() != CodeGenOpt::None) 417 addPass(createARMCodeGenPreparePass()); 418 TargetPassConfig::addCodeGenPrepare(); 419 } 420 421 bool ARMPassConfig::addPreISel() { 422 if ((TM->getOptLevel() != CodeGenOpt::None && 423 EnableGlobalMerge == cl::BOU_UNSET) || 424 EnableGlobalMerge == cl::BOU_TRUE) { 425 // FIXME: This is using the thumb1 only constant value for 426 // maximal global offset for merging globals. We may want 427 // to look into using the old value for non-thumb1 code of 428 // 4095 based on the TargetMachine, but this starts to become 429 // tricky when doing code gen per function. 430 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 431 (EnableGlobalMerge == cl::BOU_UNSET); 432 // Merging of extern globals is enabled by default on non-Mach-O as we 433 // expect it to be generally either beneficial or harmless. On Mach-O it 434 // is disabled as we emit the .subsections_via_symbols directive which 435 // means that merging extern globals is not safe. 436 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 437 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 438 MergeExternalByDefault)); 439 } 440 441 return false; 442 } 443 444 bool ARMPassConfig::addInstSelector() { 445 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 446 return false; 447 } 448 449 bool ARMPassConfig::addIRTranslator() { 450 addPass(new IRTranslator()); 451 return false; 452 } 453 454 bool ARMPassConfig::addLegalizeMachineIR() { 455 addPass(new Legalizer()); 456 return false; 457 } 458 459 bool ARMPassConfig::addRegBankSelect() { 460 addPass(new RegBankSelect()); 461 return false; 462 } 463 464 bool ARMPassConfig::addGlobalInstructionSelect() { 465 addPass(new InstructionSelect()); 466 return false; 467 } 468 469 void ARMPassConfig::addPreRegAlloc() { 470 if (getOptLevel() != CodeGenOpt::None) { 471 addPass(createMLxExpansionPass()); 472 473 if (EnableARMLoadStoreOpt) 474 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 475 476 if (!DisableA15SDOptimization) 477 addPass(createA15SDOptimizerPass()); 478 } 479 } 480 481 void ARMPassConfig::addPreSched2() { 482 if (getOptLevel() != CodeGenOpt::None) { 483 if (EnableARMLoadStoreOpt) 484 addPass(createARMLoadStoreOptimizationPass()); 485 486 addPass(new ARMExecutionDomainFix()); 487 addPass(createBreakFalseDeps()); 488 } 489 490 // Expand some pseudo instructions into multiple instructions to allow 491 // proper scheduling. 492 addPass(createARMExpandPseudoPass()); 493 494 if (getOptLevel() != CodeGenOpt::None) { 495 // in v8, IfConversion depends on Thumb instruction widths 496 addPass(createThumb2SizeReductionPass([this](const Function &F) { 497 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 498 })); 499 500 addPass(createIfConverter([](const MachineFunction &MF) { 501 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 502 })); 503 } 504 addPass(createThumb2ITBlockPass()); 505 } 506 507 void ARMPassConfig::addPreEmitPass() { 508 addPass(createThumb2SizeReductionPass()); 509 510 // Constant island pass work on unbundled instructions. 511 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 512 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 513 })); 514 515 // Don't optimize barriers at -O0. 516 if (getOptLevel() != CodeGenOpt::None) 517 addPass(createARMOptimizeBarriersPass()); 518 519 addPass(createARMConstantIslandPass()); 520 } 521