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> 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(TheAArch64leTarget); 130 RegisterTargetMachine<AArch64beTargetMachine> Y(TheAArch64beTarget); 131 RegisterTargetMachine<AArch64leTargetMachine> Z(TheARM64Target); 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 initializeAArch64PromoteConstantPass(*PR); 145 initializeAArch64RedundantCopyEliminationPass(*PR); 146 initializeAArch64StorePairSuppressPass(*PR); 147 initializeLDTLSCleanupPass(*PR); 148 } 149 150 //===----------------------------------------------------------------------===// 151 // AArch64 Lowering public interface. 152 //===----------------------------------------------------------------------===// 153 static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) { 154 if (TT.isOSBinFormatMachO()) 155 return make_unique<AArch64_MachoTargetObjectFile>(); 156 157 return make_unique<AArch64_ELFTargetObjectFile>(); 158 } 159 160 // Helper function to build a DataLayout string 161 static std::string computeDataLayout(const Triple &TT, bool LittleEndian) { 162 if (TT.isOSBinFormatMachO()) 163 return "e-m:o-i64:64-i128:128-n32:64-S128"; 164 if (LittleEndian) 165 return "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"; 166 return "E-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"; 167 } 168 169 static Reloc::Model getEffectiveRelocModel(const Triple &TT, 170 Optional<Reloc::Model> RM) { 171 // AArch64 Darwin is always PIC. 172 if (TT.isOSDarwin()) 173 return Reloc::PIC_; 174 // On ELF platforms the default static relocation model has a smart enough 175 // linker to cope with referencing external symbols defined in a shared 176 // library. Hence DynamicNoPIC doesn't need to be promoted to PIC. 177 if (!RM.hasValue() || *RM == Reloc::DynamicNoPIC) 178 return Reloc::Static; 179 return *RM; 180 } 181 182 /// Create an AArch64 architecture model. 183 /// 184 AArch64TargetMachine::AArch64TargetMachine( 185 const Target &T, const Triple &TT, StringRef CPU, StringRef FS, 186 const TargetOptions &Options, Optional<Reloc::Model> RM, 187 CodeModel::Model CM, CodeGenOpt::Level OL, bool LittleEndian) 188 // This nested ternary is horrible, but DL needs to be properly 189 // initialized before TLInfo is constructed. 190 : LLVMTargetMachine(T, computeDataLayout(TT, LittleEndian), TT, CPU, FS, 191 Options, getEffectiveRelocModel(TT, RM), CM, OL), 192 TLOF(createTLOF(getTargetTriple())), 193 isLittle(LittleEndian) { 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 isLittle); 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 && EnableAddressTypePromotion) 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 if (BranchRelaxation) 465 addPass(&BranchRelaxationPassID); 466 467 if (TM->getOptLevel() != CodeGenOpt::None && EnableCollectLOH && 468 TM->getTargetTriple().isOSBinFormatMachO()) 469 addPass(createAArch64CollectLOHPass()); 470 } 471