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