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