1 //===-- ARMTargetMachine.cpp - Define TargetMachine for ARM ---------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ARMTargetMachine.h" 14 #include "ARM.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/ExecutionDomainFix.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" 50 #include <cassert> 51 #include <memory> 52 #include <string> 53 54 using namespace llvm; 55 56 static cl::opt<bool> 57 DisableA15SDOptimization("disable-a15-sd-optimization", cl::Hidden, 58 cl::desc("Inhibit optimization of S->D register accesses on A15"), 59 cl::init(false)); 60 61 static cl::opt<bool> 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"), 65 cl::init(true)); 66 67 static cl::opt<bool> 68 EnableARMLoadStoreOpt("arm-load-store-opt", cl::Hidden, 69 cl::desc("Enable ARM load/store optimization pass"), 70 cl::init(true)); 71 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")); 76 77 namespace llvm { 78 void initializeARMExecutionDomainFixPass(PassRegistry&); 79 } 80 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()); 87 88 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 89 initializeGlobalISel(Registry); 90 initializeARMLoadStoreOptPass(Registry); 91 initializeARMPreAllocLoadStoreOptPass(Registry); 92 initializeARMParallelDSPPass(Registry); 93 initializeARMCodeGenPreparePass(Registry); 94 initializeARMConstantIslandsPass(Registry); 95 initializeARMExecutionDomainFixPass(Registry); 96 initializeARMExpandPseudoPass(Registry); 97 initializeThumb2SizeReducePass(Registry); 98 } 99 100 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 101 if (TT.isOSBinFormatMachO()) 102 return llvm::make_unique<TargetLoweringObjectFileMachO>(); 103 if (TT.isOSWindows()) 104 return llvm::make_unique<TargetLoweringObjectFileCOFF>(); 105 return llvm::make_unique<ARMElfTargetObjectFile>(); 106 } 107 108 static ARMBaseTargetMachine::ARMABI 109 computeTargetABI(const Triple &TT, StringRef CPU, 110 const TargetOptions &Options) { 111 StringRef ABIName = Options.MCOptions.getABIName(); 112 113 if (ABIName.empty()) 114 ABIName = ARM::computeDefaultTargetABI(TT, CPU); 115 116 if (ABIName == "aapcs16") 117 return ARMBaseTargetMachine::ARM_ABI_AAPCS16; 118 else if (ABIName.startswith("aapcs")) 119 return ARMBaseTargetMachine::ARM_ABI_AAPCS; 120 else if (ABIName.startswith("apcs")) 121 return ARMBaseTargetMachine::ARM_ABI_APCS; 122 123 llvm_unreachable("Unhandled/unknown ABI Name!"); 124 return ARMBaseTargetMachine::ARM_ABI_UNKNOWN; 125 } 126 127 static std::string computeDataLayout(const Triple &TT, StringRef CPU, 128 const TargetOptions &Options, 129 bool isLittle) { 130 auto ABI = computeTargetABI(TT, CPU, Options); 131 std::string Ret; 132 133 if (isLittle) 134 // Little endian. 135 Ret += "e"; 136 else 137 // Big endian. 138 Ret += "E"; 139 140 Ret += DataLayout::getManglingComponent(TT); 141 142 // Pointers are 32 bits and aligned to 32 bits. 143 Ret += "-p:32:32"; 144 145 // ABIs other than APCS have 64 bit integers with natural alignment. 146 if (ABI != ARMBaseTargetMachine::ARM_ABI_APCS) 147 Ret += "-i64:64"; 148 149 // We have 64 bits floats. The APCS ABI requires them to be aligned to 32 150 // bits, others to 64 bits. We always try to align to 64 bits. 151 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 152 Ret += "-f64:32:64"; 153 154 // We have 128 and 64 bit vectors. The APCS ABI aligns them to 32 bits, others 155 // to 64. We always ty to give them natural alignment. 156 if (ABI == ARMBaseTargetMachine::ARM_ABI_APCS) 157 Ret += "-v64:32:64-v128:32:128"; 158 else if (ABI != ARMBaseTargetMachine::ARM_ABI_AAPCS16) 159 Ret += "-v128:64:128"; 160 161 // Try to align aggregates to 32 bits (the default is 64 bits, which has no 162 // particular hardware support on 32-bit ARM). 163 Ret += "-a:0:32"; 164 165 // Integer registers are 32 bits. 166 Ret += "-n32"; 167 168 // The stack is 128 bit aligned on NaCl, 64 bit aligned on AAPCS and 32 bit 169 // aligned everywhere else. 170 if (TT.isOSNaCl() || ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS16) 171 Ret += "-S128"; 172 else if (ABI == ARMBaseTargetMachine::ARM_ABI_AAPCS) 173 Ret += "-S64"; 174 else 175 Ret += "-S32"; 176 177 return Ret; 178 } 179 180 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 181 Optional<Reloc::Model> RM) { 182 if (!RM.hasValue()) 183 // Default relocation model on Darwin is PIC. 184 return TT.isOSBinFormatMachO() ? Reloc::PIC_ : Reloc::Static; 185 186 if (*RM == Reloc::ROPI || *RM == Reloc::RWPI || *RM == Reloc::ROPI_RWPI) 187 assert(TT.isOSBinFormatELF() && 188 "ROPI/RWPI currently only supported for ELF"); 189 190 // DynamicNoPIC is only used on darwin. 191 if (*RM == Reloc::DynamicNoPIC && !TT.isOSDarwin()) 192 return Reloc::Static; 193 194 return *RM; 195 } 196 197 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) { 198 if (CM) 199 return *CM; 200 return CodeModel::Small; 201 } 202 203 /// Create an ARM architecture model. 204 /// 205 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 206 StringRef CPU, StringRef FS, 207 const TargetOptions &Options, 208 Optional<Reloc::Model> RM, 209 Optional<CodeModel::Model> CM, 210 CodeGenOpt::Level OL, bool isLittle) 211 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 212 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 213 getEffectiveCodeModel(CM), OL), 214 TargetABI(computeTargetABI(TT, CPU, Options)), 215 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 216 217 // Default to triple-appropriate float ABI 218 if (Options.FloatABIType == FloatABI::Default) { 219 if (isTargetHardFloat()) 220 this->Options.FloatABIType = FloatABI::Hard; 221 else 222 this->Options.FloatABIType = FloatABI::Soft; 223 } 224 225 // Default to triple-appropriate EABI 226 if (Options.EABIVersion == EABI::Default || 227 Options.EABIVersion == EABI::Unknown) { 228 // musl is compatible with glibc with regard to EABI version 229 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 230 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 231 TargetTriple.getEnvironment() == Triple::MuslEABI || 232 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 233 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 234 this->Options.EABIVersion = EABI::GNU; 235 else 236 this->Options.EABIVersion = EABI::EABI5; 237 } 238 239 if (TT.isOSBinFormatMachO()) { 240 this->Options.TrapUnreachable = true; 241 this->Options.NoTrapAfterNoreturn = true; 242 } 243 244 initAsmInfo(); 245 } 246 247 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 248 249 const ARMSubtarget * 250 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 251 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 252 Attribute FSAttr = F.getFnAttribute("target-features"); 253 254 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 255 ? CPUAttr.getValueAsString().str() 256 : TargetCPU; 257 std::string FS = !FSAttr.hasAttribute(Attribute::None) 258 ? FSAttr.getValueAsString().str() 259 : TargetFS; 260 261 // FIXME: This is related to the code below to reset the target options, 262 // we need to know whether or not the soft float flag is set on the 263 // function before we can generate a subtarget. We also need to use 264 // it as a key for the subtarget since that can be the only difference 265 // between two functions. 266 bool SoftFloat = 267 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 268 // If the soft float attribute is set on the function turn on the soft float 269 // subtarget feature. 270 if (SoftFloat) 271 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 272 273 auto &I = SubtargetMap[CPU + FS]; 274 if (!I) { 275 // This needs to be done before we create a new subtarget since any 276 // creation will depend on the TM and the code generation flags on the 277 // function that reside in TargetOptions. 278 resetTargetOptions(F); 279 I = llvm::make_unique<ARMSubtarget>(TargetTriple, CPU, FS, *this, isLittle); 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