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 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 static CodeModel::Model getEffectiveCodeModel(Optional<CodeModel::Model> CM) { 197 if (CM) 198 return *CM; 199 return CodeModel::Small; 200 } 201 202 /// Create an ARM architecture model. 203 /// 204 ARMBaseTargetMachine::ARMBaseTargetMachine(const Target &T, const Triple &TT, 205 StringRef CPU, StringRef FS, 206 const TargetOptions &Options, 207 Optional<Reloc::Model> RM, 208 Optional<CodeModel::Model> CM, 209 CodeGenOpt::Level OL, bool isLittle) 210 : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT, 211 CPU, FS, Options, getEffectiveRelocModel(TT, RM), 212 getEffectiveCodeModel(CM), OL), 213 TargetABI(computeTargetABI(TT, CPU, Options)), 214 TLOF(createTLOF(getTargetTriple())), isLittle(isLittle) { 215 216 // Default to triple-appropriate float ABI 217 if (Options.FloatABIType == FloatABI::Default) { 218 if (isTargetHardFloat()) 219 this->Options.FloatABIType = FloatABI::Hard; 220 else 221 this->Options.FloatABIType = FloatABI::Soft; 222 } 223 224 // Default to triple-appropriate EABI 225 if (Options.EABIVersion == EABI::Default || 226 Options.EABIVersion == EABI::Unknown) { 227 // musl is compatible with glibc with regard to EABI version 228 if ((TargetTriple.getEnvironment() == Triple::GNUEABI || 229 TargetTriple.getEnvironment() == Triple::GNUEABIHF || 230 TargetTriple.getEnvironment() == Triple::MuslEABI || 231 TargetTriple.getEnvironment() == Triple::MuslEABIHF) && 232 !(TargetTriple.isOSWindows() || TargetTriple.isOSDarwin())) 233 this->Options.EABIVersion = EABI::GNU; 234 else 235 this->Options.EABIVersion = EABI::EABI5; 236 } 237 238 if (TT.isOSBinFormatMachO()) { 239 this->Options.TrapUnreachable = true; 240 this->Options.NoTrapAfterNoreturn = true; 241 } 242 243 initAsmInfo(); 244 } 245 246 ARMBaseTargetMachine::~ARMBaseTargetMachine() = default; 247 248 const ARMSubtarget * 249 ARMBaseTargetMachine::getSubtargetImpl(const Function &F) const { 250 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 251 Attribute FSAttr = F.getFnAttribute("target-features"); 252 253 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 254 ? CPUAttr.getValueAsString().str() 255 : TargetCPU; 256 std::string FS = !FSAttr.hasAttribute(Attribute::None) 257 ? FSAttr.getValueAsString().str() 258 : TargetFS; 259 260 // FIXME: This is related to the code below to reset the target options, 261 // we need to know whether or not the soft float flag is set on the 262 // function before we can generate a subtarget. We also need to use 263 // it as a key for the subtarget since that can be the only difference 264 // between two functions. 265 bool SoftFloat = 266 F.getFnAttribute("use-soft-float").getValueAsString() == "true"; 267 // If the soft float attribute is set on the function turn on the soft float 268 // subtarget feature. 269 if (SoftFloat) 270 FS += FS.empty() ? "+soft-float" : ",+soft-float"; 271 272 auto &I = SubtargetMap[CPU + FS]; 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 280 if (!I->isThumb() && !I->hasARMOps()) 281 F.getContext().emitError("Function '" + F.getName() + "' uses ARM " 282 "instructions, but the target does not support ARM mode execution."); 283 } 284 285 return I.get(); 286 } 287 288 TargetTransformInfo 289 ARMBaseTargetMachine::getTargetTransformInfo(const Function &F) { 290 return TargetTransformInfo(ARMTTIImpl(this, F)); 291 } 292 293 ARMLETargetMachine::ARMLETargetMachine(const Target &T, const Triple &TT, 294 StringRef CPU, StringRef FS, 295 const TargetOptions &Options, 296 Optional<Reloc::Model> RM, 297 Optional<CodeModel::Model> CM, 298 CodeGenOpt::Level OL, bool JIT) 299 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 300 301 ARMBETargetMachine::ARMBETargetMachine(const Target &T, const Triple &TT, 302 StringRef CPU, StringRef FS, 303 const TargetOptions &Options, 304 Optional<Reloc::Model> RM, 305 Optional<CodeModel::Model> CM, 306 CodeGenOpt::Level OL, bool JIT) 307 : ARMBaseTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 308 309 namespace { 310 311 /// ARM Code Generator Pass Configuration Options. 312 class ARMPassConfig : public TargetPassConfig { 313 public: 314 ARMPassConfig(ARMBaseTargetMachine &TM, PassManagerBase &PM) 315 : TargetPassConfig(TM, PM) { 316 if (TM.getOptLevel() != CodeGenOpt::None) { 317 ARMGenSubtargetInfo STI(TM.getTargetTriple(), TM.getTargetCPU(), 318 TM.getTargetFeatureString()); 319 if (STI.hasFeature(ARM::FeatureUseMISched)) 320 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 321 } 322 } 323 324 ARMBaseTargetMachine &getARMTargetMachine() const { 325 return getTM<ARMBaseTargetMachine>(); 326 } 327 328 ScheduleDAGInstrs * 329 createMachineScheduler(MachineSchedContext *C) const override { 330 ScheduleDAGMILive *DAG = createGenericSchedLive(C); 331 // add DAG Mutations here. 332 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 333 if (ST.hasFusion()) 334 DAG->addMutation(createARMMacroFusionDAGMutation()); 335 return DAG; 336 } 337 338 ScheduleDAGInstrs * 339 createPostMachineScheduler(MachineSchedContext *C) const override { 340 ScheduleDAGMI *DAG = createGenericSchedPostRA(C); 341 // add DAG Mutations here. 342 const ARMSubtarget &ST = C->MF->getSubtarget<ARMSubtarget>(); 343 if (ST.hasFusion()) 344 DAG->addMutation(createARMMacroFusionDAGMutation()); 345 return DAG; 346 } 347 348 void addIRPasses() override; 349 bool addPreISel() override; 350 bool addInstSelector() override; 351 bool addIRTranslator() override; 352 bool addLegalizeMachineIR() override; 353 bool addRegBankSelect() override; 354 bool addGlobalInstructionSelect() override; 355 void addPreRegAlloc() override; 356 void addPreSched2() override; 357 void addPreEmitPass() override; 358 }; 359 360 class ARMExecutionDomainFix : public ExecutionDomainFix { 361 public: 362 static char ID; 363 ARMExecutionDomainFix() : ExecutionDomainFix(ID, ARM::DPRRegClass) {} 364 StringRef getPassName() const override { 365 return "ARM Execution Domain Fix"; 366 } 367 }; 368 char ARMExecutionDomainFix::ID; 369 370 } // end anonymous namespace 371 372 INITIALIZE_PASS_BEGIN(ARMExecutionDomainFix, "arm-execution-domain-fix", 373 "ARM Execution Domain Fix", false, false) 374 INITIALIZE_PASS_DEPENDENCY(ReachingDefAnalysis) 375 INITIALIZE_PASS_END(ARMExecutionDomainFix, "arm-execution-domain-fix", 376 "ARM Execution Domain Fix", false, false) 377 378 TargetPassConfig *ARMBaseTargetMachine::createPassConfig(PassManagerBase &PM) { 379 return new ARMPassConfig(*this, PM); 380 } 381 382 void ARMPassConfig::addIRPasses() { 383 if (TM->Options.ThreadModel == ThreadModel::Single) 384 addPass(createLowerAtomicPass()); 385 else 386 addPass(createAtomicExpandPass()); 387 388 // Cmpxchg instructions are often used with a subsequent comparison to 389 // determine whether it succeeded. We can exploit existing control-flow in 390 // ldrex/strex loops to simplify this, but it needs tidying up. 391 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 392 addPass(createCFGSimplificationPass( 393 1, false, false, true, true, [this](const Function &F) { 394 const auto &ST = this->TM->getSubtarget<ARMSubtarget>(F); 395 return ST.hasAnyDataBarrier() && !ST.isThumb1Only(); 396 })); 397 398 TargetPassConfig::addIRPasses(); 399 400 // Match interleaved memory accesses to ldN/stN intrinsics. 401 if (TM->getOptLevel() != CodeGenOpt::None) 402 addPass(createInterleavedAccessPass()); 403 } 404 405 bool ARMPassConfig::addPreISel() { 406 if (getOptLevel() != CodeGenOpt::None) 407 addPass(createARMParallelDSPPass()); 408 409 if ((TM->getOptLevel() != CodeGenOpt::None && 410 EnableGlobalMerge == cl::BOU_UNSET) || 411 EnableGlobalMerge == cl::BOU_TRUE) { 412 // FIXME: This is using the thumb1 only constant value for 413 // maximal global offset for merging globals. We may want 414 // to look into using the old value for non-thumb1 code of 415 // 4095 based on the TargetMachine, but this starts to become 416 // tricky when doing code gen per function. 417 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 418 (EnableGlobalMerge == cl::BOU_UNSET); 419 // Merging of extern globals is enabled by default on non-Mach-O as we 420 // expect it to be generally either beneficial or harmless. On Mach-O it 421 // is disabled as we emit the .subsections_via_symbols directive which 422 // means that merging extern globals is not safe. 423 bool MergeExternalByDefault = !TM->getTargetTriple().isOSBinFormatMachO(); 424 addPass(createGlobalMergePass(TM, 127, OnlyOptimizeForSize, 425 MergeExternalByDefault)); 426 } 427 428 return false; 429 } 430 431 bool ARMPassConfig::addInstSelector() { 432 addPass(createARMISelDag(getARMTargetMachine(), getOptLevel())); 433 return false; 434 } 435 436 bool ARMPassConfig::addIRTranslator() { 437 addPass(new IRTranslator()); 438 return false; 439 } 440 441 bool ARMPassConfig::addLegalizeMachineIR() { 442 addPass(new Legalizer()); 443 return false; 444 } 445 446 bool ARMPassConfig::addRegBankSelect() { 447 addPass(new RegBankSelect()); 448 return false; 449 } 450 451 bool ARMPassConfig::addGlobalInstructionSelect() { 452 addPass(new InstructionSelect()); 453 return false; 454 } 455 456 void ARMPassConfig::addPreRegAlloc() { 457 if (getOptLevel() != CodeGenOpt::None) { 458 addPass(createMLxExpansionPass()); 459 460 if (EnableARMLoadStoreOpt) 461 addPass(createARMLoadStoreOptimizationPass(/* pre-register alloc */ true)); 462 463 if (!DisableA15SDOptimization) 464 addPass(createA15SDOptimizerPass()); 465 } 466 } 467 468 void ARMPassConfig::addPreSched2() { 469 if (getOptLevel() != CodeGenOpt::None) { 470 if (EnableARMLoadStoreOpt) 471 addPass(createARMLoadStoreOptimizationPass()); 472 473 addPass(new ARMExecutionDomainFix()); 474 addPass(createBreakFalseDeps()); 475 } 476 477 // Expand some pseudo instructions into multiple instructions to allow 478 // proper scheduling. 479 addPass(createARMExpandPseudoPass()); 480 481 if (getOptLevel() != CodeGenOpt::None) { 482 // in v8, IfConversion depends on Thumb instruction widths 483 addPass(createThumb2SizeReductionPass([this](const Function &F) { 484 return this->TM->getSubtarget<ARMSubtarget>(F).restrictIT(); 485 })); 486 487 addPass(createIfConverter([](const MachineFunction &MF) { 488 return !MF.getSubtarget<ARMSubtarget>().isThumb1Only(); 489 })); 490 } 491 addPass(createThumb2ITBlockPass()); 492 } 493 494 void ARMPassConfig::addPreEmitPass() { 495 addPass(createThumb2SizeReductionPass()); 496 497 // Constant island pass work on unbundled instructions. 498 addPass(createUnpackMachineBundles([](const MachineFunction &MF) { 499 return MF.getSubtarget<ARMSubtarget>().isThumb2(); 500 })); 501 502 // Don't optimize barriers at -O0. 503 if (getOptLevel() != CodeGenOpt::None) 504 addPass(createARMOptimizeBarriersPass()); 505 506 addPass(createARMConstantIslandPass()); 507 } 508