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