1 //===- AMDGPUTargetTransformInfo.cpp - AMDGPU specific TTI pass -----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // \file 10 // This file implements a TargetTransformInfo analysis pass specific to the 11 // AMDGPU target machine. It uses the target's detailed information to provide 12 // more precise answers to certain TTI queries, while letting the target 13 // independent and default TTI implementations handle the rest. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "AMDGPUTargetTransformInfo.h" 18 #include "AMDGPUSubtarget.h" 19 #include "Utils/AMDGPUBaseInfo.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/Analysis/ValueTracking.h" 24 #include "llvm/CodeGen/ISDOpcodes.h" 25 #include "llvm/CodeGen/ValueTypes.h" 26 #include "llvm/IR/Argument.h" 27 #include "llvm/IR/Attributes.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CallingConv.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DerivedTypes.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/IntrinsicInst.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/PatternMatch.h" 38 #include "llvm/IR/Type.h" 39 #include "llvm/IR/Value.h" 40 #include "llvm/MC/SubtargetFeature.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/CommandLine.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/ErrorHandling.h" 45 #include "llvm/Support/MachineValueType.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Target/TargetMachine.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <limits> 51 #include <utility> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "AMDGPUtti" 56 57 static cl::opt<unsigned> UnrollThresholdPrivate( 58 "amdgpu-unroll-threshold-private", 59 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 60 cl::init(2700), cl::Hidden); 61 62 static cl::opt<unsigned> UnrollThresholdLocal( 63 "amdgpu-unroll-threshold-local", 64 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 65 cl::init(1000), cl::Hidden); 66 67 static cl::opt<unsigned> UnrollThresholdIf( 68 "amdgpu-unroll-threshold-if", 69 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 70 cl::init(150), cl::Hidden); 71 72 static cl::opt<bool> UseLegacyDA( 73 "amdgpu-use-legacy-divergence-analysis", 74 cl::desc("Enable legacy divergence analysis for AMDGPU"), 75 cl::init(false), cl::Hidden); 76 77 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 78 unsigned Depth = 0) { 79 const Instruction *I = dyn_cast<Instruction>(Cond); 80 if (!I) 81 return false; 82 83 for (const Value *V : I->operand_values()) { 84 if (!L->contains(I)) 85 continue; 86 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 87 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 88 return SubLoop->contains(PHI); })) 89 return true; 90 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 91 return true; 92 } 93 return false; 94 } 95 96 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 97 TTI::UnrollingPreferences &UP) { 98 const Function &F = *L->getHeader()->getParent(); 99 UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300); 100 UP.MaxCount = std::numeric_limits<unsigned>::max(); 101 UP.Partial = true; 102 103 // TODO: Do we want runtime unrolling? 104 105 // Maximum alloca size than can fit registers. Reserve 16 registers. 106 const unsigned MaxAlloca = (256 - 16) * 4; 107 unsigned ThresholdPrivate = UnrollThresholdPrivate; 108 unsigned ThresholdLocal = UnrollThresholdLocal; 109 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 110 for (const BasicBlock *BB : L->getBlocks()) { 111 const DataLayout &DL = BB->getModule()->getDataLayout(); 112 unsigned LocalGEPsSeen = 0; 113 114 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 115 return SubLoop->contains(BB); })) 116 continue; // Block belongs to an inner loop. 117 118 for (const Instruction &I : *BB) { 119 // Unroll a loop which contains an "if" statement whose condition 120 // defined by a PHI belonging to the loop. This may help to eliminate 121 // if region and potentially even PHI itself, saving on both divergence 122 // and registers used for the PHI. 123 // Add a small bonus for each of such "if" statements. 124 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 125 if (UP.Threshold < MaxBoost && Br->isConditional()) { 126 BasicBlock *Succ0 = Br->getSuccessor(0); 127 BasicBlock *Succ1 = Br->getSuccessor(1); 128 if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) || 129 (L->contains(Succ1) && L->isLoopExiting(Succ1))) 130 continue; 131 if (dependsOnLocalPhi(L, Br->getCondition())) { 132 UP.Threshold += UnrollThresholdIf; 133 LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 134 << " for loop:\n" 135 << *L << " due to " << *Br << '\n'); 136 if (UP.Threshold >= MaxBoost) 137 return; 138 } 139 } 140 continue; 141 } 142 143 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 144 if (!GEP) 145 continue; 146 147 unsigned AS = GEP->getAddressSpace(); 148 unsigned Threshold = 0; 149 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 150 Threshold = ThresholdPrivate; 151 else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) 152 Threshold = ThresholdLocal; 153 else 154 continue; 155 156 if (UP.Threshold >= Threshold) 157 continue; 158 159 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 160 const Value *Ptr = GEP->getPointerOperand(); 161 const AllocaInst *Alloca = 162 dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL)); 163 if (!Alloca || !Alloca->isStaticAlloca()) 164 continue; 165 Type *Ty = Alloca->getAllocatedType(); 166 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 167 if (AllocaSize > MaxAlloca) 168 continue; 169 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 170 AS == AMDGPUAS::REGION_ADDRESS) { 171 LocalGEPsSeen++; 172 // Inhibit unroll for local memory if we have seen addressing not to 173 // a variable, most likely we will be unable to combine it. 174 // Do not unroll too deep inner loops for local memory to give a chance 175 // to unroll an outer loop for a more important reason. 176 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 177 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 178 !isa<Argument>(GEP->getPointerOperand()))) 179 continue; 180 } 181 182 // Check if GEP depends on a value defined by this loop itself. 183 bool HasLoopDef = false; 184 for (const Value *Op : GEP->operands()) { 185 const Instruction *Inst = dyn_cast<Instruction>(Op); 186 if (!Inst || L->isLoopInvariant(Op)) 187 continue; 188 189 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 190 return SubLoop->contains(Inst); })) 191 continue; 192 HasLoopDef = true; 193 break; 194 } 195 if (!HasLoopDef) 196 continue; 197 198 // We want to do whatever we can to limit the number of alloca 199 // instructions that make it through to the code generator. allocas 200 // require us to use indirect addressing, which is slow and prone to 201 // compiler bugs. If this loop does an address calculation on an 202 // alloca ptr, then we want to use a higher than normal loop unroll 203 // threshold. This will give SROA a better chance to eliminate these 204 // allocas. 205 // 206 // We also want to have more unrolling for local memory to let ds 207 // instructions with different offsets combine. 208 // 209 // Don't use the maximum allowed value here as it will make some 210 // programs way too big. 211 UP.Threshold = Threshold; 212 LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold 213 << " for loop:\n" 214 << *L << " due to " << *GEP << '\n'); 215 if (UP.Threshold >= MaxBoost) 216 return; 217 } 218 } 219 } 220 221 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 222 // The concept of vector registers doesn't really exist. Some packed vector 223 // operations operate on the normal 32-bit registers. 224 return 256; 225 } 226 227 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const { 228 // This is really the number of registers to fill when vectorizing / 229 // interleaving loops, so we lie to avoid trying to use all registers. 230 return getHardwareNumberOfRegisters(Vec) >> 3; 231 } 232 233 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const { 234 return 32; 235 } 236 237 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 238 return 32; 239 } 240 241 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 242 unsigned ChainSizeInBytes, 243 VectorType *VecTy) const { 244 unsigned VecRegBitWidth = VF * LoadSize; 245 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 246 // TODO: Support element-size less than 32bit? 247 return 128 / LoadSize; 248 249 return VF; 250 } 251 252 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 253 unsigned ChainSizeInBytes, 254 VectorType *VecTy) const { 255 unsigned VecRegBitWidth = VF * StoreSize; 256 if (VecRegBitWidth > 128) 257 return 128 / StoreSize; 258 259 return VF; 260 } 261 262 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 263 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 264 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 265 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 266 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 267 return 512; 268 } 269 270 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS || 271 AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 272 AddrSpace == AMDGPUAS::REGION_ADDRESS) 273 return 128; 274 275 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 276 return 8 * ST->getMaxPrivateElementSize(); 277 278 llvm_unreachable("unhandled address space"); 279 } 280 281 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 282 unsigned Alignment, 283 unsigned AddrSpace) const { 284 // We allow vectorization of flat stores, even though we may need to decompose 285 // them later if they may access private memory. We don't have enough context 286 // here, and legalization can handle it. 287 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 288 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 289 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 290 } 291 return true; 292 } 293 294 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 295 unsigned Alignment, 296 unsigned AddrSpace) const { 297 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 298 } 299 300 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 301 unsigned Alignment, 302 unsigned AddrSpace) const { 303 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 304 } 305 306 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 307 // Disable unrolling if the loop is not vectorized. 308 // TODO: Enable this again. 309 if (VF == 1) 310 return 1; 311 312 return 8; 313 } 314 315 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 316 MemIntrinsicInfo &Info) const { 317 switch (Inst->getIntrinsicID()) { 318 case Intrinsic::amdgcn_atomic_inc: 319 case Intrinsic::amdgcn_atomic_dec: 320 case Intrinsic::amdgcn_ds_ordered_add: 321 case Intrinsic::amdgcn_ds_ordered_swap: 322 case Intrinsic::amdgcn_ds_fadd: 323 case Intrinsic::amdgcn_ds_fmin: 324 case Intrinsic::amdgcn_ds_fmax: { 325 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 326 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 327 if (!Ordering || !Volatile) 328 return false; // Invalid. 329 330 unsigned OrderingVal = Ordering->getZExtValue(); 331 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 332 return false; 333 334 Info.PtrVal = Inst->getArgOperand(0); 335 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 336 Info.ReadMem = true; 337 Info.WriteMem = true; 338 Info.IsVolatile = !Volatile->isNullValue(); 339 return true; 340 } 341 default: 342 return false; 343 } 344 } 345 346 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 347 TTI::OperandValueKind Opd1Info, 348 TTI::OperandValueKind Opd2Info, 349 TTI::OperandValueProperties Opd1PropInfo, 350 TTI::OperandValueProperties Opd2PropInfo, 351 ArrayRef<const Value *> Args, 352 const Instruction *CxtI) { 353 EVT OrigTy = TLI->getValueType(DL, Ty); 354 if (!OrigTy.isSimple()) { 355 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 356 Opd1PropInfo, Opd2PropInfo); 357 } 358 359 // Legalize the type. 360 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 361 int ISD = TLI->InstructionOpcodeToISD(Opcode); 362 363 // Because we don't have any legal vector operations, but the legal types, we 364 // need to account for split vectors. 365 unsigned NElts = LT.second.isVector() ? 366 LT.second.getVectorNumElements() : 1; 367 368 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 369 370 switch (ISD) { 371 case ISD::SHL: 372 case ISD::SRL: 373 case ISD::SRA: 374 if (SLT == MVT::i64) 375 return get64BitInstrCost() * LT.first * NElts; 376 377 if (ST->has16BitInsts() && SLT == MVT::i16) 378 NElts = (NElts + 1) / 2; 379 380 // i32 381 return getFullRateInstrCost() * LT.first * NElts; 382 case ISD::ADD: 383 case ISD::SUB: 384 case ISD::AND: 385 case ISD::OR: 386 case ISD::XOR: 387 if (SLT == MVT::i64) { 388 // and, or and xor are typically split into 2 VALU instructions. 389 return 2 * getFullRateInstrCost() * LT.first * NElts; 390 } 391 392 if (ST->has16BitInsts() && SLT == MVT::i16) 393 NElts = (NElts + 1) / 2; 394 395 return LT.first * NElts * getFullRateInstrCost(); 396 case ISD::MUL: { 397 const int QuarterRateCost = getQuarterRateInstrCost(); 398 if (SLT == MVT::i64) { 399 const int FullRateCost = getFullRateInstrCost(); 400 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 401 } 402 403 if (ST->has16BitInsts() && SLT == MVT::i16) 404 NElts = (NElts + 1) / 2; 405 406 // i32 407 return QuarterRateCost * NElts * LT.first; 408 } 409 case ISD::FADD: 410 case ISD::FSUB: 411 case ISD::FMUL: 412 if (SLT == MVT::f64) 413 return LT.first * NElts * get64BitInstrCost(); 414 415 if (ST->has16BitInsts() && SLT == MVT::f16) 416 NElts = (NElts + 1) / 2; 417 418 if (SLT == MVT::f32 || SLT == MVT::f16) 419 return LT.first * NElts * getFullRateInstrCost(); 420 break; 421 case ISD::FDIV: 422 case ISD::FREM: 423 // FIXME: frem should be handled separately. The fdiv in it is most of it, 424 // but the current lowering is also not entirely correct. 425 if (SLT == MVT::f64) { 426 int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost(); 427 // Add cost of workaround. 428 if (!ST->hasUsableDivScaleConditionOutput()) 429 Cost += 3 * getFullRateInstrCost(); 430 431 return LT.first * Cost * NElts; 432 } 433 434 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 435 // TODO: This is more complicated, unsafe flags etc. 436 if ((SLT == MVT::f32 && !HasFP32Denormals) || 437 (SLT == MVT::f16 && ST->has16BitInsts())) { 438 return LT.first * getQuarterRateInstrCost() * NElts; 439 } 440 } 441 442 if (SLT == MVT::f16 && ST->has16BitInsts()) { 443 // 2 x v_cvt_f32_f16 444 // f32 rcp 445 // f32 fmul 446 // v_cvt_f16_f32 447 // f16 div_fixup 448 int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(); 449 return LT.first * Cost * NElts; 450 } 451 452 if (SLT == MVT::f32 || SLT == MVT::f16) { 453 int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost(); 454 455 if (!HasFP32Denormals) { 456 // FP mode switches. 457 Cost += 2 * getFullRateInstrCost(); 458 } 459 460 return LT.first * NElts * Cost; 461 } 462 break; 463 default: 464 break; 465 } 466 467 return BaseT::getArithmeticInstrCost(Opcode, Ty, Opd1Info, Opd2Info, 468 Opd1PropInfo, Opd2PropInfo); 469 } 470 471 template <typename T> 472 int GCNTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, 473 ArrayRef<T *> Args, 474 FastMathFlags FMF, unsigned VF) { 475 if (ID != Intrinsic::fma) 476 return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF); 477 478 EVT OrigTy = TLI->getValueType(DL, RetTy); 479 if (!OrigTy.isSimple()) { 480 return BaseT::getIntrinsicInstrCost(ID, RetTy, Args, FMF, VF); 481 } 482 483 // Legalize the type. 484 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy); 485 486 unsigned NElts = LT.second.isVector() ? 487 LT.second.getVectorNumElements() : 1; 488 489 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 490 491 if (SLT == MVT::f64) 492 return LT.first * NElts * get64BitInstrCost(); 493 494 if (ST->has16BitInsts() && SLT == MVT::f16) 495 NElts = (NElts + 1) / 2; 496 497 return LT.first * NElts * (ST->hasFastFMAF32() ? getHalfRateInstrCost() 498 : getQuarterRateInstrCost()); 499 } 500 501 int GCNTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, 502 ArrayRef<Value*> Args, FastMathFlags FMF, 503 unsigned VF) { 504 return getIntrinsicInstrCost<Value>(ID, RetTy, Args, FMF, VF); 505 } 506 507 int GCNTTIImpl::getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, 508 ArrayRef<Type *> Tys, FastMathFlags FMF, 509 unsigned ScalarizationCostPassed) { 510 return getIntrinsicInstrCost<Type>(ID, RetTy, Tys, FMF, 511 ScalarizationCostPassed); 512 } 513 514 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode) { 515 // XXX - For some reason this isn't called for switch. 516 switch (Opcode) { 517 case Instruction::Br: 518 case Instruction::Ret: 519 return 10; 520 default: 521 return BaseT::getCFInstrCost(Opcode); 522 } 523 } 524 525 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, Type *Ty, 526 bool IsPairwise) { 527 EVT OrigTy = TLI->getValueType(DL, Ty); 528 529 // Computes cost on targets that have packed math instructions(which support 530 // 16-bit types only). 531 if (IsPairwise || 532 !ST->hasVOP3PInsts() || 533 OrigTy.getScalarSizeInBits() != 16) 534 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise); 535 536 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 537 return LT.first * getFullRateInstrCost(); 538 } 539 540 int GCNTTIImpl::getMinMaxReductionCost(Type *Ty, Type *CondTy, 541 bool IsPairwise, 542 bool IsUnsigned) { 543 EVT OrigTy = TLI->getValueType(DL, Ty); 544 545 // Computes cost on targets that have packed math instructions(which support 546 // 16-bit types only). 547 if (IsPairwise || 548 !ST->hasVOP3PInsts() || 549 OrigTy.getScalarSizeInBits() != 16) 550 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned); 551 552 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 553 return LT.first * getHalfRateInstrCost(); 554 } 555 556 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 557 unsigned Index) { 558 switch (Opcode) { 559 case Instruction::ExtractElement: 560 case Instruction::InsertElement: { 561 unsigned EltSize 562 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 563 if (EltSize < 32) { 564 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 565 return 0; 566 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 567 } 568 569 // Extracts are just reads of a subregister, so are free. Inserts are 570 // considered free because we don't want to have any cost for scalarizing 571 // operations, and we don't have to copy into a different register class. 572 573 // Dynamic indexing isn't free and is best avoided. 574 return Index == ~0u ? 2 : 0; 575 } 576 default: 577 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 578 } 579 } 580 581 582 583 static bool isArgPassedInSGPR(const Argument *A) { 584 const Function *F = A->getParent(); 585 586 // Arguments to compute shaders are never a source of divergence. 587 CallingConv::ID CC = F->getCallingConv(); 588 switch (CC) { 589 case CallingConv::AMDGPU_KERNEL: 590 case CallingConv::SPIR_KERNEL: 591 return true; 592 case CallingConv::AMDGPU_VS: 593 case CallingConv::AMDGPU_LS: 594 case CallingConv::AMDGPU_HS: 595 case CallingConv::AMDGPU_ES: 596 case CallingConv::AMDGPU_GS: 597 case CallingConv::AMDGPU_PS: 598 case CallingConv::AMDGPU_CS: 599 // For non-compute shaders, SGPR inputs are marked with either inreg or byval. 600 // Everything else is in VGPRs. 601 return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) || 602 F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal); 603 default: 604 // TODO: Should calls support inreg for SGPR inputs? 605 return false; 606 } 607 } 608 609 /// \returns true if the new GPU divergence analysis is enabled. 610 bool GCNTTIImpl::useGPUDivergenceAnalysis() const { 611 return !UseLegacyDA; 612 } 613 614 /// \returns true if the result of the value could potentially be 615 /// different across workitems in a wavefront. 616 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 617 if (const Argument *A = dyn_cast<Argument>(V)) 618 return !isArgPassedInSGPR(A); 619 620 // Loads from the private and flat address spaces are divergent, because 621 // threads can execute the load instruction with the same inputs and get 622 // different results. 623 // 624 // All other loads are not divergent, because if threads issue loads with the 625 // same arguments, they will always get the same result. 626 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 627 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 628 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 629 630 // Atomics are divergent because they are executed sequentially: when an 631 // atomic operation refers to the same address in each thread, then each 632 // thread after the first sees the value written by the previous thread as 633 // original value. 634 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 635 return true; 636 637 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 638 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 639 640 // Assume all function calls are a source of divergence. 641 if (isa<CallInst>(V) || isa<InvokeInst>(V)) 642 return true; 643 644 return false; 645 } 646 647 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 648 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 649 switch (Intrinsic->getIntrinsicID()) { 650 default: 651 return false; 652 case Intrinsic::amdgcn_readfirstlane: 653 case Intrinsic::amdgcn_readlane: 654 case Intrinsic::amdgcn_icmp: 655 case Intrinsic::amdgcn_fcmp: 656 return true; 657 } 658 } 659 return false; 660 } 661 662 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 663 Intrinsic::ID IID) const { 664 switch (IID) { 665 case Intrinsic::amdgcn_atomic_inc: 666 case Intrinsic::amdgcn_atomic_dec: 667 case Intrinsic::amdgcn_ds_fadd: 668 case Intrinsic::amdgcn_ds_fmin: 669 case Intrinsic::amdgcn_ds_fmax: 670 case Intrinsic::amdgcn_is_shared: 671 case Intrinsic::amdgcn_is_private: 672 OpIndexes.push_back(0); 673 return true; 674 default: 675 return false; 676 } 677 } 678 679 bool GCNTTIImpl::rewriteIntrinsicWithAddressSpace( 680 IntrinsicInst *II, Value *OldV, Value *NewV) const { 681 auto IntrID = II->getIntrinsicID(); 682 switch (IntrID) { 683 case Intrinsic::amdgcn_atomic_inc: 684 case Intrinsic::amdgcn_atomic_dec: 685 case Intrinsic::amdgcn_ds_fadd: 686 case Intrinsic::amdgcn_ds_fmin: 687 case Intrinsic::amdgcn_ds_fmax: { 688 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 689 if (!IsVolatile->isZero()) 690 return false; 691 Module *M = II->getParent()->getParent()->getParent(); 692 Type *DestTy = II->getType(); 693 Type *SrcTy = NewV->getType(); 694 Function *NewDecl = 695 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 696 II->setArgOperand(0, NewV); 697 II->setCalledFunction(NewDecl); 698 return true; 699 } 700 case Intrinsic::amdgcn_is_shared: 701 case Intrinsic::amdgcn_is_private: { 702 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 703 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 704 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 705 LLVMContext &Ctx = NewV->getType()->getContext(); 706 ConstantInt *NewVal = (TrueAS == NewAS) ? 707 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 708 II->replaceAllUsesWith(NewVal); 709 II->eraseFromParent(); 710 return true; 711 } 712 default: 713 return false; 714 } 715 } 716 717 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index, 718 Type *SubTp) { 719 if (ST->hasVOP3PInsts()) { 720 VectorType *VT = cast<VectorType>(Tp); 721 if (VT->getNumElements() == 2 && 722 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 723 // With op_sel VOP3P instructions freely can access the low half or high 724 // half of a register, so any swizzle is free. 725 726 switch (Kind) { 727 case TTI::SK_Broadcast: 728 case TTI::SK_Reverse: 729 case TTI::SK_PermuteSingleSrc: 730 return 0; 731 default: 732 break; 733 } 734 } 735 } 736 737 return BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 738 } 739 740 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 741 const Function *Callee) const { 742 const TargetMachine &TM = getTLI()->getTargetMachine(); 743 const GCNSubtarget *CallerST 744 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 745 const GCNSubtarget *CalleeST 746 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 747 748 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 749 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 750 751 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 752 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 753 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 754 return false; 755 756 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 757 // no way to support merge for backend defined attributes. 758 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller, *CallerST); 759 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee, *CalleeST); 760 return CallerMode.isInlineCompatible(CalleeMode); 761 } 762 763 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 764 TTI::UnrollingPreferences &UP) { 765 CommonTTI.getUnrollingPreferences(L, SE, UP); 766 } 767 768 unsigned GCNTTIImpl::getUserCost(const User *U, 769 ArrayRef<const Value *> Operands) { 770 const Instruction *I = dyn_cast<Instruction>(U); 771 if (!I) 772 return BaseT::getUserCost(U, Operands); 773 774 // Estimate different operations to be optimized out 775 switch (I->getOpcode()) { 776 case Instruction::ExtractElement: { 777 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1)); 778 unsigned Idx = -1; 779 if (CI) 780 Idx = CI->getZExtValue(); 781 return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx); 782 } 783 case Instruction::InsertElement: { 784 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 785 unsigned Idx = -1; 786 if (CI) 787 Idx = CI->getZExtValue(); 788 return getVectorInstrCost(I->getOpcode(), I->getType(), Idx); 789 } 790 case Instruction::Call: { 791 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) { 792 SmallVector<Value *, 4> Args(II->arg_operands()); 793 FastMathFlags FMF; 794 if (auto *FPMO = dyn_cast<FPMathOperator>(II)) 795 FMF = FPMO->getFastMathFlags(); 796 return getIntrinsicInstrCost(II->getIntrinsicID(), II->getType(), Args, 797 FMF); 798 } else { 799 return BaseT::getUserCost(U, Operands); 800 } 801 } 802 case Instruction::ShuffleVector: { 803 const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I); 804 Type *Ty = Shuffle->getType(); 805 Type *SrcTy = Shuffle->getOperand(0)->getType(); 806 807 // TODO: Identify and add costs for insert subvector, etc. 808 int SubIndex; 809 if (Shuffle->isExtractSubvectorMask(SubIndex)) 810 return getShuffleCost(TTI::SK_ExtractSubvector, SrcTy, SubIndex, Ty); 811 812 if (Shuffle->changesLength()) 813 return BaseT::getUserCost(U, Operands); 814 815 if (Shuffle->isIdentity()) 816 return 0; 817 818 if (Shuffle->isReverse()) 819 return getShuffleCost(TTI::SK_Reverse, Ty, 0, nullptr); 820 821 if (Shuffle->isSelect()) 822 return getShuffleCost(TTI::SK_Select, Ty, 0, nullptr); 823 824 if (Shuffle->isTranspose()) 825 return getShuffleCost(TTI::SK_Transpose, Ty, 0, nullptr); 826 827 if (Shuffle->isZeroEltSplat()) 828 return getShuffleCost(TTI::SK_Broadcast, Ty, 0, nullptr); 829 830 if (Shuffle->isSingleSource()) 831 return getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, 0, nullptr); 832 833 return getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, 0, nullptr); 834 } 835 case Instruction::ZExt: 836 case Instruction::SExt: 837 case Instruction::FPToUI: 838 case Instruction::FPToSI: 839 case Instruction::FPExt: 840 case Instruction::PtrToInt: 841 case Instruction::IntToPtr: 842 case Instruction::SIToFP: 843 case Instruction::UIToFP: 844 case Instruction::Trunc: 845 case Instruction::FPTrunc: 846 case Instruction::BitCast: 847 case Instruction::AddrSpaceCast: { 848 return getCastInstrCost(I->getOpcode(), I->getType(), 849 I->getOperand(0)->getType(), I); 850 } 851 case Instruction::Add: 852 case Instruction::FAdd: 853 case Instruction::Sub: 854 case Instruction::FSub: 855 case Instruction::Mul: 856 case Instruction::FMul: 857 case Instruction::UDiv: 858 case Instruction::SDiv: 859 case Instruction::FDiv: 860 case Instruction::URem: 861 case Instruction::SRem: 862 case Instruction::FRem: 863 case Instruction::Shl: 864 case Instruction::LShr: 865 case Instruction::AShr: 866 case Instruction::And: 867 case Instruction::Or: 868 case Instruction::Xor: 869 case Instruction::FNeg: { 870 return getArithmeticInstrCost(I->getOpcode(), I->getType(), 871 TTI::OK_AnyValue, TTI::OK_AnyValue, 872 TTI::OP_None, TTI::OP_None, Operands, I); 873 } 874 default: 875 break; 876 } 877 878 return BaseT::getUserCost(U, Operands); 879 } 880 881 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 882 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 883 } 884 885 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 886 return getHardwareNumberOfRegisters(Vec); 887 } 888 889 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const { 890 return 32; 891 } 892 893 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 894 return 32; 895 } 896 897 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 898 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 899 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 900 return 128; 901 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 902 AddrSpace == AMDGPUAS::REGION_ADDRESS) 903 return 64; 904 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 905 return 32; 906 907 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 908 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 909 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 910 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 911 return 128; 912 llvm_unreachable("unhandled address space"); 913 } 914 915 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 916 unsigned Alignment, 917 unsigned AddrSpace) const { 918 // We allow vectorization of flat stores, even though we may need to decompose 919 // them later if they may access private memory. We don't have enough context 920 // here, and legalization can handle it. 921 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 922 } 923 924 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 925 unsigned Alignment, 926 unsigned AddrSpace) const { 927 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 928 } 929 930 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 931 unsigned Alignment, 932 unsigned AddrSpace) const { 933 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 934 } 935 936 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 937 // Disable unrolling if the loop is not vectorized. 938 // TODO: Enable this again. 939 if (VF == 1) 940 return 1; 941 942 return 8; 943 } 944 945 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode) { 946 // XXX - For some reason this isn't called for switch. 947 switch (Opcode) { 948 case Instruction::Br: 949 case Instruction::Ret: 950 return 10; 951 default: 952 return BaseT::getCFInstrCost(Opcode); 953 } 954 } 955 956 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 957 unsigned Index) { 958 switch (Opcode) { 959 case Instruction::ExtractElement: 960 case Instruction::InsertElement: { 961 unsigned EltSize 962 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 963 if (EltSize < 32) { 964 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 965 } 966 967 // Extracts are just reads of a subregister, so are free. Inserts are 968 // considered free because we don't want to have any cost for scalarizing 969 // operations, and we don't have to copy into a different register class. 970 971 // Dynamic indexing isn't free and is best avoided. 972 return Index == ~0u ? 2 : 0; 973 } 974 default: 975 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 976 } 977 } 978 979 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 980 TTI::UnrollingPreferences &UP) { 981 CommonTTI.getUnrollingPreferences(L, SE, UP); 982 } 983