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