1 //===-- AArch64TargetMachine.cpp - Define TargetMachine for AArch64 -------===// 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 "AArch64.h" 14 #include "AArch64CallLowering.h" 15 #include "AArch64InstructionSelector.h" 16 #include "AArch64MachineLegalizer.h" 17 #include "AArch64RegisterBankInfo.h" 18 #include "AArch64TargetMachine.h" 19 #include "AArch64TargetObjectFile.h" 20 #include "AArch64TargetTransformInfo.h" 21 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 22 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h" 23 #include "llvm/CodeGen/GlobalISel/MachineLegalizePass.h" 24 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h" 25 #include "llvm/CodeGen/Passes.h" 26 #include "llvm/CodeGen/RegAllocRegistry.h" 27 #include "llvm/CodeGen/TargetPassConfig.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/InitializePasses.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/TargetRegistry.h" 33 #include "llvm/Target/TargetOptions.h" 34 #include "llvm/Transforms/Scalar.h" 35 using namespace llvm; 36 37 static cl::opt<bool> 38 EnableCCMP("aarch64-ccmp", cl::desc("Enable the CCMP formation pass"), 39 cl::init(true), cl::Hidden); 40 41 static cl::opt<bool> EnableMCR("aarch64-mcr", 42 cl::desc("Enable the machine combiner pass"), 43 cl::init(true), cl::Hidden); 44 45 static cl::opt<bool> 46 EnableStPairSuppress("aarch64-stp-suppress", cl::desc("Suppress STP for AArch64"), 47 cl::init(true), cl::Hidden); 48 49 static cl::opt<bool> 50 EnableAdvSIMDScalar("aarch64-simd-scalar", cl::desc("Enable use of AdvSIMD scalar" 51 " integer instructions"), cl::init(false), cl::Hidden); 52 53 static cl::opt<bool> 54 EnablePromoteConstant("aarch64-promote-const", cl::desc("Enable the promote " 55 "constant pass"), cl::init(true), cl::Hidden); 56 57 static cl::opt<bool> 58 EnableCollectLOH("aarch64-collect-loh", cl::desc("Enable the pass that emits the" 59 " linker optimization hints (LOH)"), cl::init(true), 60 cl::Hidden); 61 62 static cl::opt<bool> 63 EnableDeadRegisterElimination("aarch64-dead-def-elimination", cl::Hidden, 64 cl::desc("Enable the pass that removes dead" 65 " definitons and replaces stores to" 66 " them with stores to the zero" 67 " register"), 68 cl::init(true)); 69 70 static cl::opt<bool> 71 EnableRedundantCopyElimination("aarch64-redundant-copy-elim", 72 cl::desc("Enable the redundant copy elimination pass"), 73 cl::init(true), cl::Hidden); 74 75 static cl::opt<bool> 76 EnableLoadStoreOpt("aarch64-load-store-opt", cl::desc("Enable the load/store pair" 77 " optimization pass"), cl::init(true), cl::Hidden); 78 79 static cl::opt<bool> 80 EnableAtomicTidy("aarch64-atomic-cfg-tidy", cl::Hidden, 81 cl::desc("Run SimplifyCFG after expanding atomic operations" 82 " to make use of cmpxchg flow-based information"), 83 cl::init(true)); 84 85 static cl::opt<bool> 86 EnableEarlyIfConversion("aarch64-enable-early-ifcvt", cl::Hidden, 87 cl::desc("Run early if-conversion"), 88 cl::init(true)); 89 90 static cl::opt<bool> 91 EnableCondOpt("aarch64-condopt", 92 cl::desc("Enable the condition optimizer pass"), 93 cl::init(true), cl::Hidden); 94 95 static cl::opt<bool> 96 EnableA53Fix835769("aarch64-fix-cortex-a53-835769", cl::Hidden, 97 cl::desc("Work around Cortex-A53 erratum 835769"), 98 cl::init(false)); 99 100 static cl::opt<bool> 101 EnableGEPOpt("aarch64-gep-opt", cl::Hidden, 102 cl::desc("Enable optimizations on complex GEPs"), 103 cl::init(false)); 104 105 // FIXME: Unify control over GlobalMerge. 106 static cl::opt<cl::boolOrDefault> 107 EnableGlobalMerge("aarch64-global-merge", cl::Hidden, 108 cl::desc("Enable the global merge pass")); 109 110 static cl::opt<bool> 111 EnableLoopDataPrefetch("aarch64-loop-data-prefetch", cl::Hidden, 112 cl::desc("Enable the loop data prefetch pass"), 113 cl::init(true)); 114 115 extern "C" void LLVMInitializeAArch64Target() { 116 // Register the target. 117 RegisterTargetMachine<AArch64leTargetMachine> X(TheAArch64leTarget); 118 RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget); 119 RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target); 120 auto PR = PassRegistry::getPassRegistry(); 121 initializeGlobalISel(*PR); 122 initializeAArch64ExpandPseudoPass(*PR); 123 initializeAArch64LoadStoreOptPass(*PR); 124 } 125 126 //===----------------------------------------------------------------------===// 127 // AArch64 Lowering public interface. 128 //===----------------------------------------------------------------------===// 129 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 130 if (TT.isOSBinFormatMachO()) 131 return make_unique<AArch64_MachoTargetObjectFile>(); 132 133 return make_unique<AArch64_ELFTargetObjectFile>(); 134 } 135 136 // Helper function to build a DataLayout string 137 static std::string computeDataLayout(const Triple &TT, bool LittleEndian) { 138 if (TT.isOSBinFormatMachO()) 139 return "e-m:o-i64:64-i128:128-n32:64-S128"; 140 if (LittleEndian) 141 return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"; 142 return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"; 143 } 144 145 // Helper function to set up the defaults for reciprocals. 146 static void initReciprocals(AArch64TargetMachine& TM, AArch64Subtarget& ST) 147 { 148 // For the estimates, convergence is quadratic, so essentially the number of 149 // digits is doubled after each iteration. ARMv8, the minimum architected 150 // accuracy of the initial estimate is 2^-8. Therefore, the number of extra 151 // steps to refine the result for float (23 mantissa bits) and for double 152 // (52 mantissa bits) are 2 and 3, respectively. 153 unsigned ExtraStepsF = 2, 154 ExtraStepsD = ExtraStepsF + 1; 155 bool UseRsqrt = ST.useRSqrt(); 156 157 TM.Options.Reciprocals.setDefaults("sqrtf", UseRsqrt, ExtraStepsF); 158 TM.Options.Reciprocals.setDefaults("sqrtd", UseRsqrt, ExtraStepsD); 159 TM.Options.Reciprocals.setDefaults("vec-sqrtf", UseRsqrt, ExtraStepsF); 160 TM.Options.Reciprocals.setDefaults("vec-sqrtd", UseRsqrt, ExtraStepsD); 161 162 TM.Options.Reciprocals.setDefaults("divf", false, ExtraStepsF); 163 TM.Options.Reciprocals.setDefaults("divd", false, ExtraStepsD); 164 TM.Options.Reciprocals.setDefaults("vec-divf", false, ExtraStepsF); 165 TM.Options.Reciprocals.setDefaults("vec-divd", false, ExtraStepsD); 166 } 167 168 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 169 Optional<Reloc::Model> RM) { 170 // AArch64 Darwin is always PIC. 171 if (TT.isOSDarwin()) 172 return Reloc::PIC_; 173 // On ELF platforms the default static relocation model has a smart enough 174 // linker to cope with referencing external symbols defined in a shared 175 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC. 176 if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC) 177 return Reloc::Static; 178 return *RM; 179 } 180 181 /// Create an AArch64 architecture model. 182 /// 183 AArch64TargetMachine::AArch64TargetMachine( 184 const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 185 const TargetOptions &Options, Optional<Reloc::Model> RM, 186 CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian) 187 // This nested ternary is horrible, but DL needs to be properly 188 // initialized before TLInfo is constructed. 189 : LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS, 190 Options, getEffectiveRelocModel(TT, RM), CM, OL), 191 TLOF(createTLOF(getTargetTriple())), 192 Subtarget(TT, CPU, FS, *this, LittleEndian) { 193 initReciprocals(*this, Subtarget); 194 initAsmInfo(); 195 } 196 197 AArch64TargetMachine::~AArch64TargetMachine() {} 198 199 #ifdef LLVM_BUILD_GLOBAL_ISEL 200 namespace { 201 struct AArch64GISelActualAccessor : public GISelAccessor { 202 std::unique_ptr<CallLowering> CallLoweringInfo; 203 std::unique_ptr<InstructionSelector> InstSelector; 204 std::unique_ptr<MachineLegalizer> Legalizer; 205 std::unique_ptr<RegisterBankInfo> RegBankInfo; 206 const CallLowering *getCallLowering() const override { 207 return CallLoweringInfo.get(); 208 } 209 const InstructionSelector *getInstructionSelector() const override { 210 return InstSelector.get(); 211 } 212 const class MachineLegalizer *getMachineLegalizer() const override { 213 return Legalizer.get(); 214 } 215 const RegisterBankInfo *getRegBankInfo() const override { 216 return RegBankInfo.get(); 217 } 218 }; 219 } // End anonymous namespace. 220 #endif 221 222 const AArch64Subtarget * 223 AArch64TargetMachine::getSubtargetImpl(const Function &F) const { 224 Attribute CPUAttr = F.getFnAttribute("target-cpu"); 225 Attribute FSAttr = F.getFnAttribute("target-features"); 226 227 std::string CPU = !CPUAttr.hasAttribute(Attribute::None) 228 ? CPUAttr.getValueAsString().str() 229 : TargetCPU; 230 std::string FS = !FSAttr.hasAttribute(Attribute::None) 231 ? FSAttr.getValueAsString().str() 232 : TargetFS; 233 234 auto &I = SubtargetMap[CPU + FS]; 235 if (!I) { 236 // This needs to be done before we create a new subtarget since any 237 // creation will depend on the TM and the code generation flags on the 238 // function that reside in TargetOptions. 239 resetTargetOptions(F); 240 I = llvm::make_unique<AArch64Subtarget>(TargetTriple, CPU, FS, *this, 241 Subtarget.isLittleEndian()); 242 #ifndef LLVM_BUILD_GLOBAL_ISEL 243 GISelAccessor *GISel = new GISelAccessor(); 244 #else 245 AArch64GISelActualAccessor *GISel = 246 new AArch64GISelActualAccessor(); 247 GISel->CallLoweringInfo.reset( 248 new AArch64CallLowering(*I->getTargetLowering())); 249 GISel->Legalizer.reset(new AArch64MachineLegalizer()); 250 251 auto *RBI = new AArch64RegisterBankInfo(*I->getRegisterInfo()); 252 253 // FIXME: At this point, we can't rely on Subtarget having RBI. 254 // It's awkward to mix passing RBI and the Subtarget; should we pass 255 // TII/TRI as well? 256 GISel->InstSelector.reset(new AArch64InstructionSelector(*I, *RBI)); 257 258 GISel->RegBankInfo.reset(RBI); 259 #endif 260 I->setGISelAccessor(*GISel); 261 } 262 return I.get(); 263 } 264 265 void AArch64leTargetMachine::anchor() { } 266 267 AArch64leTargetMachine::AArch64leTargetMachine( 268 const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 269 const TargetOptions &Options, Optional<Reloc::Model> RM, 270 CodeModel::Model CM, CodeGenOpt::Level OL) 271 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {} 272 273 void AArch64beTargetMachine::anchor() { } 274 275 AArch64beTargetMachine::AArch64beTargetMachine( 276 const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 277 const TargetOptions &Options, Optional<Reloc::Model> RM, 278 CodeModel::Model CM, CodeGenOpt::Level OL) 279 : AArch64TargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {} 280 281 namespace { 282 /// AArch64 Code Generator Pass Configuration Options. 283 class AArch64PassConfig : public TargetPassConfig { 284 public: 285 AArch64PassConfig(AArch64TargetMachine *TM, PassManagerBase &PM) 286 : TargetPassConfig(TM, PM) { 287 if (TM->getOptLevel() != CodeGenOpt::None) 288 substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); 289 } 290 291 AArch64TargetMachine &getAArch64TargetMachine() const { 292 return getTM<AArch64TargetMachine>(); 293 } 294 295 void addIRPasses() override; 296 bool addPreISel() override; 297 bool addInstSelector() override; 298 #ifdef LLVM_BUILD_GLOBAL_ISEL 299 bool addIRTranslator() override; 300 bool addLegalizeMachineIR() override; 301 bool addRegBankSelect() override; 302 bool addGlobalInstructionSelect() override; 303 #endif 304 bool addILPOpts() override; 305 void addPreRegAlloc() override; 306 void addPostRegAlloc() override; 307 void addPreSched2() override; 308 void addPreEmitPass() override; 309 }; 310 } // namespace 311 312 TargetIRAnalysis AArch64TargetMachine::getTargetIRAnalysis() { 313 return TargetIRAnalysis([this](const Function &F) { 314 return TargetTransformInfo(AArch64TTIImpl(this, F)); 315 }); 316 } 317 318 TargetPassConfig *AArch64TargetMachine::createPassConfig(PassManagerBase &PM) { 319 return new AArch64PassConfig(this, PM); 320 } 321 322 void AArch64PassConfig::addIRPasses() { 323 // Always expand atomic operations, we don't deal with atomicrmw or cmpxchg 324 // ourselves. 325 addPass(createAtomicExpandPass(TM)); 326 327 // Cmpxchg instructions are often used with a subsequent comparison to 328 // determine whether it succeeded. We can exploit existing control-flow in 329 // ldrex/strex loops to simplify this, but it needs tidying up. 330 if (TM->getOptLevel() != CodeGenOpt::None && EnableAtomicTidy) 331 addPass(createCFGSimplificationPass()); 332 333 // Run LoopDataPrefetch 334 // 335 // Run this before LSR to remove the multiplies involved in computing the 336 // pointer values N iterations ahead. 337 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoopDataPrefetch) 338 addPass(createLoopDataPrefetchPass()); 339 340 TargetPassConfig::addIRPasses(); 341 342 // Match interleaved memory accesses to ldN/stN intrinsics. 343 if (TM->getOptLevel() != CodeGenOpt::None) 344 addPass(createInterleavedAccessPass(TM)); 345 346 if (TM->getOptLevel() == CodeGenOpt::Aggressive && EnableGEPOpt) { 347 // Call SeparateConstOffsetFromGEP pass to extract constants within indices 348 // and lower a GEP with multiple indices to either arithmetic operations or 349 // multiple GEPs with single index. 350 addPass(createSeparateConstOffsetFromGEPPass(TM, true)); 351 // Call EarlyCSE pass to find and remove subexpressions in the lowered 352 // result. 353 addPass(createEarlyCSEPass()); 354 // Do loop invariant code motion in case part of the lowered result is 355 // invariant. 356 addPass(createLICMPass()); 357 } 358 } 359 360 // Pass Pipeline Configuration 361 bool AArch64PassConfig::addPreISel() { 362 // Run promote constant before global merge, so that the promoted constants 363 // get a chance to be merged 364 if (TM->getOptLevel() != CodeGenOpt::None && EnablePromoteConstant) 365 addPass(createAArch64PromoteConstantPass()); 366 // FIXME: On AArch64, this depends on the type. 367 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes(). 368 // and the offset has to be a multiple of the related size in bytes. 369 if ((TM->getOptLevel() != CodeGenOpt::None && 370 EnableGlobalMerge == cl::BOU_UNSET) || 371 EnableGlobalMerge == cl::BOU_TRUE) { 372 bool OnlyOptimizeForSize = (TM->getOptLevel() < CodeGenOpt::Aggressive) && 373 (EnableGlobalMerge == cl::BOU_UNSET); 374 addPass(createGlobalMergePass(TM, 4095, OnlyOptimizeForSize)); 375 } 376 377 if (TM->getOptLevel() != CodeGenOpt::None) 378 addPass(createAArch64AddressTypePromotionPass()); 379 380 return false; 381 } 382 383 bool AArch64PassConfig::addInstSelector() { 384 addPass(createAArch64ISelDag(getAArch64TargetMachine(), getOptLevel())); 385 386 // For ELF, cleanup any local-dynamic TLS accesses (i.e. combine as many 387 // references to _TLS_MODULE_BASE_ as possible. 388 if (TM->getTargetTriple().isOSBinFormatELF() && 389 getOptLevel() != CodeGenOpt::None) 390 addPass(createAArch64CleanupLocalDynamicTLSPass()); 391 392 return false; 393 } 394 395 #ifdef LLVM_BUILD_GLOBAL_ISEL 396 bool AArch64PassConfig::addIRTranslator() { 397 addPass(new IRTranslator()); 398 return false; 399 } 400 bool AArch64PassConfig::addLegalizeMachineIR() { 401 addPass(new MachineLegalizePass()); 402 return false; 403 } 404 bool AArch64PassConfig::addRegBankSelect() { 405 addPass(new RegBankSelect()); 406 return false; 407 } 408 bool AArch64PassConfig::addGlobalInstructionSelect() { 409 addPass(new InstructionSelect()); 410 return false; 411 } 412 #endif 413 414 bool AArch64PassConfig::addILPOpts() { 415 if (EnableCondOpt) 416 addPass(createAArch64ConditionOptimizerPass()); 417 if (EnableCCMP) 418 addPass(createAArch64ConditionalCompares()); 419 if (EnableMCR) 420 addPass(&MachineCombinerID); 421 if (EnableEarlyIfConversion) 422 addPass(&EarlyIfConverterID); 423 if (EnableStPairSuppress) 424 addPass(createAArch64StorePairSuppressPass()); 425 return true; 426 } 427 428 void AArch64PassConfig::addPreRegAlloc() { 429 // Use AdvSIMD scalar instructions whenever profitable. 430 if (TM->getOptLevel() != CodeGenOpt::None && EnableAdvSIMDScalar) { 431 addPass(createAArch64AdvSIMDScalar()); 432 // The AdvSIMD pass may produce copies that can be rewritten to 433 // be register coaleascer friendly. 434 addPass(&PeepholeOptimizerID); 435 } 436 } 437 438 void AArch64PassConfig::addPostRegAlloc() { 439 // Remove redundant copy instructions. 440 if (TM->getOptLevel() != CodeGenOpt::None && EnableRedundantCopyElimination) 441 addPass(createAArch64RedundantCopyEliminationPass()); 442 443 // Change dead register definitions to refer to the zero register. 444 if (TM->getOptLevel() != CodeGenOpt::None && EnableDeadRegisterElimination) 445 addPass(createAArch64DeadRegisterDefinitions()); 446 if (TM->getOptLevel() != CodeGenOpt::None && usingDefaultRegAlloc()) 447 // Improve performance for some FP/SIMD code for A57. 448 addPass(createAArch64A57FPLoadBalancing()); 449 } 450 451 void AArch64PassConfig::addPreSched2() { 452 // Expand some pseudo instructions to allow proper scheduling. 453 addPass(createAArch64ExpandPseudoPass()); 454 // Use load/store pair instructions when possible. 455 if (TM->getOptLevel() != CodeGenOpt::None && EnableLoadStoreOpt) 456 addPass(createAArch64LoadStoreOptimizationPass()); 457 } 458 459 void AArch64PassConfig::addPreEmitPass() { 460 if (EnableA53Fix835769) 461 addPass(createAArch64A53Fix835769()); 462 // Relax conditional branch instructions if they're otherwise out of 463 // range of their destination. 464 addPass(createAArch64BranchRelaxation()); 465 if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH && 466 TM->getTargetTriple().isOSBinFormatMachO()) 467 addPass(createAArch64CollectLOHPass()); 468 } 469