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 "AMDGPUTargetMachine.h" 19 #include "llvm/Analysis/LoopInfo.h" 20 #include "llvm/Analysis/ValueTracking.h" 21 #include "llvm/IR/IntrinsicsAMDGPU.h" 22 #include "llvm/IR/PatternMatch.h" 23 #include "llvm/Support/KnownBits.h" 24 25 using namespace llvm; 26 27 #define DEBUG_TYPE "AMDGPUtti" 28 29 static cl::opt<unsigned> UnrollThresholdPrivate( 30 "amdgpu-unroll-threshold-private", 31 cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"), 32 cl::init(2700), cl::Hidden); 33 34 static cl::opt<unsigned> UnrollThresholdLocal( 35 "amdgpu-unroll-threshold-local", 36 cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"), 37 cl::init(1000), cl::Hidden); 38 39 static cl::opt<unsigned> UnrollThresholdIf( 40 "amdgpu-unroll-threshold-if", 41 cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"), 42 cl::init(150), cl::Hidden); 43 44 static cl::opt<bool> UnrollRuntimeLocal( 45 "amdgpu-unroll-runtime-local", 46 cl::desc("Allow runtime unroll for AMDGPU if local memory used in a loop"), 47 cl::init(true), cl::Hidden); 48 49 static cl::opt<bool> UseLegacyDA( 50 "amdgpu-use-legacy-divergence-analysis", 51 cl::desc("Enable legacy divergence analysis for AMDGPU"), 52 cl::init(false), cl::Hidden); 53 54 static cl::opt<unsigned> UnrollMaxBlockToAnalyze( 55 "amdgpu-unroll-max-block-to-analyze", 56 cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"), 57 cl::init(32), cl::Hidden); 58 59 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond, 60 unsigned Depth = 0) { 61 const Instruction *I = dyn_cast<Instruction>(Cond); 62 if (!I) 63 return false; 64 65 for (const Value *V : I->operand_values()) { 66 if (!L->contains(I)) 67 continue; 68 if (const PHINode *PHI = dyn_cast<PHINode>(V)) { 69 if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) { 70 return SubLoop->contains(PHI); })) 71 return true; 72 } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1)) 73 return true; 74 } 75 return false; 76 } 77 78 AMDGPUTTIImpl::AMDGPUTTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 79 : BaseT(TM, F.getParent()->getDataLayout()), 80 TargetTriple(TM->getTargetTriple()), 81 ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))), 82 TLI(ST->getTargetLowering()) {} 83 84 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 85 TTI::UnrollingPreferences &UP) { 86 const Function &F = *L->getHeader()->getParent(); 87 UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300); 88 UP.MaxCount = std::numeric_limits<unsigned>::max(); 89 UP.Partial = true; 90 91 // TODO: Do we want runtime unrolling? 92 93 // Maximum alloca size than can fit registers. Reserve 16 registers. 94 const unsigned MaxAlloca = (256 - 16) * 4; 95 unsigned ThresholdPrivate = UnrollThresholdPrivate; 96 unsigned ThresholdLocal = UnrollThresholdLocal; 97 98 // If this loop has the amdgpu.loop.unroll.threshold metadata we will use the 99 // provided threshold value as the default for Threshold 100 if (MDNode *LoopUnrollThreshold = 101 findOptionMDForLoop(L, "amdgpu.loop.unroll.threshold")) { 102 if (LoopUnrollThreshold->getNumOperands() == 2) { 103 ConstantInt *MetaThresholdValue = mdconst::extract_or_null<ConstantInt>( 104 LoopUnrollThreshold->getOperand(1)); 105 if (MetaThresholdValue) { 106 // We will also use the supplied value for PartialThreshold for now. 107 // We may introduce additional metadata if it becomes necessary in the 108 // future. 109 UP.Threshold = MetaThresholdValue->getSExtValue(); 110 UP.PartialThreshold = UP.Threshold; 111 ThresholdPrivate = std::min(ThresholdPrivate, UP.Threshold); 112 ThresholdLocal = std::min(ThresholdLocal, UP.Threshold); 113 } 114 } 115 } 116 117 unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal); 118 for (const BasicBlock *BB : L->getBlocks()) { 119 const DataLayout &DL = BB->getModule()->getDataLayout(); 120 unsigned LocalGEPsSeen = 0; 121 122 if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) { 123 return SubLoop->contains(BB); })) 124 continue; // Block belongs to an inner loop. 125 126 for (const Instruction &I : *BB) { 127 // Unroll a loop which contains an "if" statement whose condition 128 // defined by a PHI belonging to the loop. This may help to eliminate 129 // if region and potentially even PHI itself, saving on both divergence 130 // and registers used for the PHI. 131 // Add a small bonus for each of such "if" statements. 132 if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) { 133 if (UP.Threshold < MaxBoost && Br->isConditional()) { 134 BasicBlock *Succ0 = Br->getSuccessor(0); 135 BasicBlock *Succ1 = Br->getSuccessor(1); 136 if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) || 137 (L->contains(Succ1) && L->isLoopExiting(Succ1))) 138 continue; 139 if (dependsOnLocalPhi(L, Br->getCondition())) { 140 UP.Threshold += UnrollThresholdIf; 141 LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold 142 << " for loop:\n" 143 << *L << " due to " << *Br << '\n'); 144 if (UP.Threshold >= MaxBoost) 145 return; 146 } 147 } 148 continue; 149 } 150 151 const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I); 152 if (!GEP) 153 continue; 154 155 unsigned AS = GEP->getAddressSpace(); 156 unsigned Threshold = 0; 157 if (AS == AMDGPUAS::PRIVATE_ADDRESS) 158 Threshold = ThresholdPrivate; 159 else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) 160 Threshold = ThresholdLocal; 161 else 162 continue; 163 164 if (UP.Threshold >= Threshold) 165 continue; 166 167 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 168 const Value *Ptr = GEP->getPointerOperand(); 169 const AllocaInst *Alloca = 170 dyn_cast<AllocaInst>(getUnderlyingObject(Ptr)); 171 if (!Alloca || !Alloca->isStaticAlloca()) 172 continue; 173 Type *Ty = Alloca->getAllocatedType(); 174 unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0; 175 if (AllocaSize > MaxAlloca) 176 continue; 177 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 178 AS == AMDGPUAS::REGION_ADDRESS) { 179 LocalGEPsSeen++; 180 // Inhibit unroll for local memory if we have seen addressing not to 181 // a variable, most likely we will be unable to combine it. 182 // Do not unroll too deep inner loops for local memory to give a chance 183 // to unroll an outer loop for a more important reason. 184 if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 || 185 (!isa<GlobalVariable>(GEP->getPointerOperand()) && 186 !isa<Argument>(GEP->getPointerOperand()))) 187 continue; 188 LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n" 189 << *L << " due to LDS use.\n"); 190 UP.Runtime = UnrollRuntimeLocal; 191 } 192 193 // Check if GEP depends on a value defined by this loop itself. 194 bool HasLoopDef = false; 195 for (const Value *Op : GEP->operands()) { 196 const Instruction *Inst = dyn_cast<Instruction>(Op); 197 if (!Inst || L->isLoopInvariant(Op)) 198 continue; 199 200 if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) { 201 return SubLoop->contains(Inst); })) 202 continue; 203 HasLoopDef = true; 204 break; 205 } 206 if (!HasLoopDef) 207 continue; 208 209 // We want to do whatever we can to limit the number of alloca 210 // instructions that make it through to the code generator. allocas 211 // require us to use indirect addressing, which is slow and prone to 212 // compiler bugs. If this loop does an address calculation on an 213 // alloca ptr, then we want to use a higher than normal loop unroll 214 // threshold. This will give SROA a better chance to eliminate these 215 // allocas. 216 // 217 // We also want to have more unrolling for local memory to let ds 218 // instructions with different offsets combine. 219 // 220 // Don't use the maximum allowed value here as it will make some 221 // programs way too big. 222 UP.Threshold = Threshold; 223 LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold 224 << " for loop:\n" 225 << *L << " due to " << *GEP << '\n'); 226 if (UP.Threshold >= MaxBoost) 227 return; 228 } 229 230 // If we got a GEP in a small BB from inner loop then increase max trip 231 // count to analyze for better estimation cost in unroll 232 if (L->isInnermost() && BB->size() < UnrollMaxBlockToAnalyze) 233 UP.MaxIterationsCountToAnalyze = 32; 234 } 235 } 236 237 void AMDGPUTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 238 TTI::PeelingPreferences &PP) { 239 BaseT::getPeelingPreferences(L, SE, PP); 240 } 241 242 GCNTTIImpl::GCNTTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 243 : BaseT(TM, F.getParent()->getDataLayout()), 244 ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))), 245 TLI(ST->getTargetLowering()), CommonTTI(TM, F), 246 IsGraphics(AMDGPU::isGraphics(F.getCallingConv())), 247 MaxVGPRs(ST->getMaxNumVGPRs( 248 std::max(ST->getWavesPerEU(F).first, 249 ST->getWavesPerEUForWorkGroup( 250 ST->getFlatWorkGroupSizes(F).second)))) { 251 AMDGPU::SIModeRegisterDefaults Mode(F); 252 HasFP32Denormals = Mode.allFP32Denormals(); 253 HasFP64FP16Denormals = Mode.allFP64FP16Denormals(); 254 } 255 256 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 257 // The concept of vector registers doesn't really exist. Some packed vector 258 // operations operate on the normal 32-bit registers. 259 return MaxVGPRs; 260 } 261 262 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const { 263 // This is really the number of registers to fill when vectorizing / 264 // interleaving loops, so we lie to avoid trying to use all registers. 265 return getHardwareNumberOfRegisters(Vec) >> 3; 266 } 267 268 unsigned GCNTTIImpl::getNumberOfRegisters(unsigned RCID) const { 269 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 270 const TargetRegisterClass *RC = TRI->getRegClass(RCID); 271 unsigned NumVGPRs = (TRI->getRegSizeInBits(*RC) + 31) / 32; 272 return getHardwareNumberOfRegisters(false) / NumVGPRs; 273 } 274 275 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const { 276 return 32; 277 } 278 279 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const { 280 return 32; 281 } 282 283 unsigned GCNTTIImpl::getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 284 if (Opcode == Instruction::Load || Opcode == Instruction::Store) 285 return 32 * 4 / ElemWidth; 286 return (ElemWidth == 16 && ST->has16BitInsts()) ? 2 : 1; 287 } 288 289 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize, 290 unsigned ChainSizeInBytes, 291 VectorType *VecTy) const { 292 unsigned VecRegBitWidth = VF * LoadSize; 293 if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32) 294 // TODO: Support element-size less than 32bit? 295 return 128 / LoadSize; 296 297 return VF; 298 } 299 300 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize, 301 unsigned ChainSizeInBytes, 302 VectorType *VecTy) const { 303 unsigned VecRegBitWidth = VF * StoreSize; 304 if (VecRegBitWidth > 128) 305 return 128 / StoreSize; 306 307 return VF; 308 } 309 310 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 311 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 312 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 313 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 314 AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) { 315 return 512; 316 } 317 318 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 319 return 8 * ST->getMaxPrivateElementSize(); 320 321 // Common to flat, global, local and region. Assume for unknown addrspace. 322 return 128; 323 } 324 325 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 326 Align Alignment, 327 unsigned AddrSpace) const { 328 // We allow vectorization of flat stores, even though we may need to decompose 329 // them later if they may access private memory. We don't have enough context 330 // here, and legalization can handle it. 331 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 332 return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) && 333 ChainSizeInBytes <= ST->getMaxPrivateElementSize(); 334 } 335 return true; 336 } 337 338 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 339 Align Alignment, 340 unsigned AddrSpace) const { 341 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 342 } 343 344 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 345 Align Alignment, 346 unsigned AddrSpace) const { 347 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 348 } 349 350 // FIXME: Really we would like to issue multiple 128-bit loads and stores per 351 // iteration. Should we report a larger size and let it legalize? 352 // 353 // FIXME: Should we use narrower types for local/region, or account for when 354 // unaligned access is legal? 355 // 356 // FIXME: This could use fine tuning and microbenchmarks. 357 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length, 358 unsigned SrcAddrSpace, 359 unsigned DestAddrSpace, 360 unsigned SrcAlign, 361 unsigned DestAlign) const { 362 unsigned MinAlign = std::min(SrcAlign, DestAlign); 363 364 // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the 365 // hardware into byte accesses. If you assume all alignments are equally 366 // probable, it's more efficient on average to use short accesses for this 367 // case. 368 if (MinAlign == 2) 369 return Type::getInt16Ty(Context); 370 371 // Not all subtargets have 128-bit DS instructions, and we currently don't 372 // form them by default. 373 if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 374 SrcAddrSpace == AMDGPUAS::REGION_ADDRESS || 375 DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS || 376 DestAddrSpace == AMDGPUAS::REGION_ADDRESS) { 377 return FixedVectorType::get(Type::getInt32Ty(Context), 2); 378 } 379 380 // Global memory works best with 16-byte accesses. Private memory will also 381 // hit this, although they'll be decomposed. 382 return FixedVectorType::get(Type::getInt32Ty(Context), 4); 383 } 384 385 void GCNTTIImpl::getMemcpyLoopResidualLoweringType( 386 SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context, 387 unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace, 388 unsigned SrcAlign, unsigned DestAlign) const { 389 assert(RemainingBytes < 16); 390 391 unsigned MinAlign = std::min(SrcAlign, DestAlign); 392 393 if (MinAlign != 2) { 394 Type *I64Ty = Type::getInt64Ty(Context); 395 while (RemainingBytes >= 8) { 396 OpsOut.push_back(I64Ty); 397 RemainingBytes -= 8; 398 } 399 400 Type *I32Ty = Type::getInt32Ty(Context); 401 while (RemainingBytes >= 4) { 402 OpsOut.push_back(I32Ty); 403 RemainingBytes -= 4; 404 } 405 } 406 407 Type *I16Ty = Type::getInt16Ty(Context); 408 while (RemainingBytes >= 2) { 409 OpsOut.push_back(I16Ty); 410 RemainingBytes -= 2; 411 } 412 413 Type *I8Ty = Type::getInt8Ty(Context); 414 while (RemainingBytes) { 415 OpsOut.push_back(I8Ty); 416 --RemainingBytes; 417 } 418 } 419 420 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) { 421 // Disable unrolling if the loop is not vectorized. 422 // TODO: Enable this again. 423 if (VF == 1) 424 return 1; 425 426 return 8; 427 } 428 429 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 430 MemIntrinsicInfo &Info) const { 431 switch (Inst->getIntrinsicID()) { 432 case Intrinsic::amdgcn_atomic_inc: 433 case Intrinsic::amdgcn_atomic_dec: 434 case Intrinsic::amdgcn_ds_ordered_add: 435 case Intrinsic::amdgcn_ds_ordered_swap: 436 case Intrinsic::amdgcn_ds_fadd: 437 case Intrinsic::amdgcn_ds_fmin: 438 case Intrinsic::amdgcn_ds_fmax: { 439 auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2)); 440 auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4)); 441 if (!Ordering || !Volatile) 442 return false; // Invalid. 443 444 unsigned OrderingVal = Ordering->getZExtValue(); 445 if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent)) 446 return false; 447 448 Info.PtrVal = Inst->getArgOperand(0); 449 Info.Ordering = static_cast<AtomicOrdering>(OrderingVal); 450 Info.ReadMem = true; 451 Info.WriteMem = true; 452 Info.IsVolatile = !Volatile->isNullValue(); 453 return true; 454 } 455 default: 456 return false; 457 } 458 } 459 460 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 461 TTI::TargetCostKind CostKind, 462 TTI::OperandValueKind Opd1Info, 463 TTI::OperandValueKind Opd2Info, 464 TTI::OperandValueProperties Opd1PropInfo, 465 TTI::OperandValueProperties Opd2PropInfo, 466 ArrayRef<const Value *> Args, 467 const Instruction *CxtI) { 468 EVT OrigTy = TLI->getValueType(DL, Ty); 469 if (!OrigTy.isSimple()) { 470 // FIXME: We're having to query the throughput cost so that the basic 471 // implementation tries to generate legalize and scalarization costs. Maybe 472 // we could hoist the scalarization code here? 473 if (CostKind != TTI::TCK_CodeSize) 474 return BaseT::getArithmeticInstrCost(Opcode, Ty, TTI::TCK_RecipThroughput, 475 Opd1Info, Opd2Info, Opd1PropInfo, 476 Opd2PropInfo, Args, CxtI); 477 // Scalarization 478 479 // Check if any of the operands are vector operands. 480 int ISD = TLI->InstructionOpcodeToISD(Opcode); 481 assert(ISD && "Invalid opcode"); 482 483 std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 484 485 bool IsFloat = Ty->isFPOrFPVectorTy(); 486 // Assume that floating point arithmetic operations cost twice as much as 487 // integer operations. 488 unsigned OpCost = (IsFloat ? 2 : 1); 489 490 if (TLI->isOperationLegalOrPromote(ISD, LT.second)) { 491 // The operation is legal. Assume it costs 1. 492 // TODO: Once we have extract/insert subvector cost we need to use them. 493 return LT.first * OpCost; 494 } 495 496 if (!TLI->isOperationExpand(ISD, LT.second)) { 497 // If the operation is custom lowered, then assume that the code is twice 498 // as expensive. 499 return LT.first * 2 * OpCost; 500 } 501 502 // Else, assume that we need to scalarize this op. 503 // TODO: If one of the types get legalized by splitting, handle this 504 // similarly to what getCastInstrCost() does. 505 if (auto *VTy = dyn_cast<VectorType>(Ty)) { 506 unsigned Num = cast<FixedVectorType>(VTy)->getNumElements(); 507 unsigned Cost = getArithmeticInstrCost( 508 Opcode, VTy->getScalarType(), CostKind, Opd1Info, Opd2Info, 509 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 510 // Return the cost of multiple scalar invocation plus the cost of 511 // inserting and extracting the values. 512 return getScalarizationOverhead(VTy, Args) + Num * Cost; 513 } 514 515 // We don't know anything about this scalar instruction. 516 return OpCost; 517 } 518 519 // Legalize the type. 520 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 521 int ISD = TLI->InstructionOpcodeToISD(Opcode); 522 523 // Because we don't have any legal vector operations, but the legal types, we 524 // need to account for split vectors. 525 unsigned NElts = LT.second.isVector() ? 526 LT.second.getVectorNumElements() : 1; 527 528 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 529 530 switch (ISD) { 531 case ISD::SHL: 532 case ISD::SRL: 533 case ISD::SRA: 534 if (SLT == MVT::i64) 535 return get64BitInstrCost(CostKind) * LT.first * NElts; 536 537 if (ST->has16BitInsts() && SLT == MVT::i16) 538 NElts = (NElts + 1) / 2; 539 540 // i32 541 return getFullRateInstrCost() * LT.first * NElts; 542 case ISD::ADD: 543 case ISD::SUB: 544 case ISD::AND: 545 case ISD::OR: 546 case ISD::XOR: 547 if (SLT == MVT::i64) { 548 // and, or and xor are typically split into 2 VALU instructions. 549 return 2 * getFullRateInstrCost() * LT.first * NElts; 550 } 551 552 if (ST->has16BitInsts() && SLT == MVT::i16) 553 NElts = (NElts + 1) / 2; 554 555 return LT.first * NElts * getFullRateInstrCost(); 556 case ISD::MUL: { 557 const int QuarterRateCost = getQuarterRateInstrCost(CostKind); 558 if (SLT == MVT::i64) { 559 const int FullRateCost = getFullRateInstrCost(); 560 return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts; 561 } 562 563 if (ST->has16BitInsts() && SLT == MVT::i16) 564 NElts = (NElts + 1) / 2; 565 566 // i32 567 return QuarterRateCost * NElts * LT.first; 568 } 569 case ISD::FMUL: 570 // Check possible fuse {fadd|fsub}(a,fmul(b,c)) and return zero cost for 571 // fmul(b,c) supposing the fadd|fsub will get estimated cost for the whole 572 // fused operation. 573 if (CxtI && CxtI->hasOneUse()) 574 if (const auto *FAdd = dyn_cast<BinaryOperator>(*CxtI->user_begin())) { 575 const int OPC = TLI->InstructionOpcodeToISD(FAdd->getOpcode()); 576 if (OPC == ISD::FADD || OPC == ISD::FSUB) { 577 if (ST->hasMadMacF32Insts() && SLT == MVT::f32 && !HasFP32Denormals) 578 return TargetTransformInfo::TCC_Free; 579 if (ST->has16BitInsts() && SLT == MVT::f16 && !HasFP64FP16Denormals) 580 return TargetTransformInfo::TCC_Free; 581 582 // Estimate all types may be fused with contract/unsafe flags 583 const TargetOptions &Options = TLI->getTargetMachine().Options; 584 if (Options.AllowFPOpFusion == FPOpFusion::Fast || 585 Options.UnsafeFPMath || 586 (FAdd->hasAllowContract() && CxtI->hasAllowContract())) 587 return TargetTransformInfo::TCC_Free; 588 } 589 } 590 LLVM_FALLTHROUGH; 591 case ISD::FADD: 592 case ISD::FSUB: 593 if (SLT == MVT::f64) 594 return LT.first * NElts * get64BitInstrCost(CostKind); 595 596 if (ST->has16BitInsts() && SLT == MVT::f16) 597 NElts = (NElts + 1) / 2; 598 599 if (SLT == MVT::f32 || SLT == MVT::f16) 600 return LT.first * NElts * getFullRateInstrCost(); 601 break; 602 case ISD::FDIV: 603 case ISD::FREM: 604 // FIXME: frem should be handled separately. The fdiv in it is most of it, 605 // but the current lowering is also not entirely correct. 606 if (SLT == MVT::f64) { 607 int Cost = 7 * get64BitInstrCost(CostKind) + 608 getQuarterRateInstrCost(CostKind) + 609 3 * getHalfRateInstrCost(CostKind); 610 // Add cost of workaround. 611 if (!ST->hasUsableDivScaleConditionOutput()) 612 Cost += 3 * getFullRateInstrCost(); 613 614 return LT.first * Cost * NElts; 615 } 616 617 if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) { 618 // TODO: This is more complicated, unsafe flags etc. 619 if ((SLT == MVT::f32 && !HasFP32Denormals) || 620 (SLT == MVT::f16 && ST->has16BitInsts())) { 621 return LT.first * getQuarterRateInstrCost(CostKind) * NElts; 622 } 623 } 624 625 if (SLT == MVT::f16 && ST->has16BitInsts()) { 626 // 2 x v_cvt_f32_f16 627 // f32 rcp 628 // f32 fmul 629 // v_cvt_f16_f32 630 // f16 div_fixup 631 int Cost = 632 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(CostKind); 633 return LT.first * Cost * NElts; 634 } 635 636 if (SLT == MVT::f32 || SLT == MVT::f16) { 637 // 4 more v_cvt_* insts without f16 insts support 638 int Cost = (SLT == MVT::f16 ? 14 : 10) * getFullRateInstrCost() + 639 1 * getQuarterRateInstrCost(CostKind); 640 641 if (!HasFP32Denormals) { 642 // FP mode switches. 643 Cost += 2 * getFullRateInstrCost(); 644 } 645 646 return LT.first * NElts * Cost; 647 } 648 break; 649 case ISD::FNEG: 650 // Use the backend' estimation. If fneg is not free each element will cost 651 // one additional instruction. 652 return TLI->isFNegFree(SLT) ? 0 : NElts; 653 default: 654 break; 655 } 656 657 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info, 658 Opd1PropInfo, Opd2PropInfo, Args, CxtI); 659 } 660 661 // Return true if there's a potential benefit from using v2f16/v2i16 662 // instructions for an intrinsic, even if it requires nontrivial legalization. 663 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) { 664 switch (ID) { 665 case Intrinsic::fma: // TODO: fmuladd 666 // There's a small benefit to using vector ops in the legalized code. 667 case Intrinsic::round: 668 case Intrinsic::uadd_sat: 669 case Intrinsic::usub_sat: 670 case Intrinsic::sadd_sat: 671 case Intrinsic::ssub_sat: 672 return true; 673 default: 674 return false; 675 } 676 } 677 678 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 679 TTI::TargetCostKind CostKind) { 680 if (ICA.getID() == Intrinsic::fabs) 681 return 0; 682 683 if (!intrinsicHasPackedVectorBenefit(ICA.getID())) 684 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 685 686 Type *RetTy = ICA.getReturnType(); 687 EVT OrigTy = TLI->getValueType(DL, RetTy); 688 if (!OrigTy.isSimple()) { 689 if (CostKind != TTI::TCK_CodeSize) 690 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 691 692 // TODO: Combine these two logic paths. 693 if (ICA.isTypeBasedOnly()) 694 return getTypeBasedIntrinsicInstrCost(ICA, CostKind); 695 696 Type *RetTy = ICA.getReturnType(); 697 unsigned VF = ICA.getVectorFactor().getFixedValue(); 698 unsigned RetVF = 699 (RetTy->isVectorTy() ? cast<FixedVectorType>(RetTy)->getNumElements() 700 : 1); 701 assert((RetVF == 1 || VF == 1) && "VF > 1 and RetVF is a vector type"); 702 const IntrinsicInst *I = ICA.getInst(); 703 const SmallVectorImpl<const Value *> &Args = ICA.getArgs(); 704 FastMathFlags FMF = ICA.getFlags(); 705 // Assume that we need to scalarize this intrinsic. 706 SmallVector<Type *, 4> Types; 707 for (const Value *Op : Args) { 708 Type *OpTy = Op->getType(); 709 assert(VF == 1 || !OpTy->isVectorTy()); 710 Types.push_back(VF == 1 ? OpTy : FixedVectorType::get(OpTy, VF)); 711 } 712 713 if (VF > 1 && !RetTy->isVoidTy()) 714 RetTy = FixedVectorType::get(RetTy, VF); 715 716 // Compute the scalarization overhead based on Args for a vector 717 // intrinsic. A vectorizer will pass a scalar RetTy and VF > 1, while 718 // CostModel will pass a vector RetTy and VF is 1. 719 unsigned ScalarizationCost = std::numeric_limits<unsigned>::max(); 720 if (RetVF > 1 || VF > 1) { 721 ScalarizationCost = 0; 722 if (!RetTy->isVoidTy()) 723 ScalarizationCost += 724 getScalarizationOverhead(cast<VectorType>(RetTy), true, false); 725 ScalarizationCost += getOperandsScalarizationOverhead(Args, VF); 726 } 727 728 IntrinsicCostAttributes Attrs(ICA.getID(), RetTy, Types, FMF, 729 ScalarizationCost, I); 730 return getIntrinsicInstrCost(Attrs, CostKind); 731 } 732 733 // Legalize the type. 734 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy); 735 736 unsigned NElts = LT.second.isVector() ? 737 LT.second.getVectorNumElements() : 1; 738 739 MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy; 740 741 if (SLT == MVT::f64) 742 return LT.first * NElts * get64BitInstrCost(CostKind); 743 744 if (ST->has16BitInsts() && SLT == MVT::f16) 745 NElts = (NElts + 1) / 2; 746 747 // TODO: Get more refined intrinsic costs? 748 unsigned InstRate = getQuarterRateInstrCost(CostKind); 749 if (ICA.getID() == Intrinsic::fma) { 750 InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost(CostKind) 751 : getQuarterRateInstrCost(CostKind); 752 } 753 754 return LT.first * NElts * InstRate; 755 } 756 757 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode, 758 TTI::TargetCostKind CostKind) { 759 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 760 return Opcode == Instruction::PHI ? 0 : 1; 761 762 // XXX - For some reason this isn't called for switch. 763 switch (Opcode) { 764 case Instruction::Br: 765 case Instruction::Ret: 766 return 10; 767 default: 768 return BaseT::getCFInstrCost(Opcode, CostKind); 769 } 770 } 771 772 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, 773 bool IsPairwise, 774 TTI::TargetCostKind CostKind) { 775 EVT OrigTy = TLI->getValueType(DL, Ty); 776 777 // Computes cost on targets that have packed math instructions(which support 778 // 16-bit types only). 779 if (IsPairwise || 780 !ST->hasVOP3PInsts() || 781 OrigTy.getScalarSizeInBits() != 16) 782 return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind); 783 784 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 785 return LT.first * getFullRateInstrCost(); 786 } 787 788 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, 789 bool IsPairwise, bool IsUnsigned, 790 TTI::TargetCostKind CostKind) { 791 EVT OrigTy = TLI->getValueType(DL, Ty); 792 793 // Computes cost on targets that have packed math instructions(which support 794 // 16-bit types only). 795 if (IsPairwise || 796 !ST->hasVOP3PInsts() || 797 OrigTy.getScalarSizeInBits() != 16) 798 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned, 799 CostKind); 800 801 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 802 return LT.first * getHalfRateInstrCost(CostKind); 803 } 804 805 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 806 unsigned Index) { 807 switch (Opcode) { 808 case Instruction::ExtractElement: 809 case Instruction::InsertElement: { 810 unsigned EltSize 811 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 812 if (EltSize < 32) { 813 if (EltSize == 16 && Index == 0 && ST->has16BitInsts()) 814 return 0; 815 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 816 } 817 818 // Extracts are just reads of a subregister, so are free. Inserts are 819 // considered free because we don't want to have any cost for scalarizing 820 // operations, and we don't have to copy into a different register class. 821 822 // Dynamic indexing isn't free and is best avoided. 823 return Index == ~0u ? 2 : 0; 824 } 825 default: 826 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 827 } 828 } 829 830 /// Analyze if the results of inline asm are divergent. If \p Indices is empty, 831 /// this is analyzing the collective result of all output registers. Otherwise, 832 /// this is only querying a specific result index if this returns multiple 833 /// registers in a struct. 834 bool GCNTTIImpl::isInlineAsmSourceOfDivergence( 835 const CallInst *CI, ArrayRef<unsigned> Indices) const { 836 // TODO: Handle complex extract indices 837 if (Indices.size() > 1) 838 return true; 839 840 const DataLayout &DL = CI->getModule()->getDataLayout(); 841 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 842 TargetLowering::AsmOperandInfoVector TargetConstraints = 843 TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI); 844 845 const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0]; 846 847 int OutputIdx = 0; 848 for (auto &TC : TargetConstraints) { 849 if (TC.Type != InlineAsm::isOutput) 850 continue; 851 852 // Skip outputs we don't care about. 853 if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++) 854 continue; 855 856 TLI->ComputeConstraintToUse(TC, SDValue()); 857 858 Register AssignedReg; 859 const TargetRegisterClass *RC; 860 std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint( 861 TRI, TC.ConstraintCode, TC.ConstraintVT); 862 if (AssignedReg) { 863 // FIXME: This is a workaround for getRegForInlineAsmConstraint 864 // returning VS_32 865 RC = TRI->getPhysRegClass(AssignedReg); 866 } 867 868 // For AGPR constraints null is returned on subtargets without AGPRs, so 869 // assume divergent for null. 870 if (!RC || !TRI->isSGPRClass(RC)) 871 return true; 872 } 873 874 return false; 875 } 876 877 /// \returns true if the new GPU divergence analysis is enabled. 878 bool GCNTTIImpl::useGPUDivergenceAnalysis() const { 879 return !UseLegacyDA; 880 } 881 882 /// \returns true if the result of the value could potentially be 883 /// different across workitems in a wavefront. 884 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const { 885 if (const Argument *A = dyn_cast<Argument>(V)) 886 return !AMDGPU::isArgPassedInSGPR(A); 887 888 // Loads from the private and flat address spaces are divergent, because 889 // threads can execute the load instruction with the same inputs and get 890 // different results. 891 // 892 // All other loads are not divergent, because if threads issue loads with the 893 // same arguments, they will always get the same result. 894 if (const LoadInst *Load = dyn_cast<LoadInst>(V)) 895 return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS || 896 Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS; 897 898 // Atomics are divergent because they are executed sequentially: when an 899 // atomic operation refers to the same address in each thread, then each 900 // thread after the first sees the value written by the previous thread as 901 // original value. 902 if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V)) 903 return true; 904 905 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) 906 return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID()); 907 908 // Assume all function calls are a source of divergence. 909 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 910 if (CI->isInlineAsm()) 911 return isInlineAsmSourceOfDivergence(CI); 912 return true; 913 } 914 915 // Assume all function calls are a source of divergence. 916 if (isa<InvokeInst>(V)) 917 return true; 918 919 return false; 920 } 921 922 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const { 923 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 924 switch (Intrinsic->getIntrinsicID()) { 925 default: 926 return false; 927 case Intrinsic::amdgcn_readfirstlane: 928 case Intrinsic::amdgcn_readlane: 929 case Intrinsic::amdgcn_icmp: 930 case Intrinsic::amdgcn_fcmp: 931 case Intrinsic::amdgcn_ballot: 932 case Intrinsic::amdgcn_if_break: 933 return true; 934 } 935 } 936 937 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 938 if (CI->isInlineAsm()) 939 return !isInlineAsmSourceOfDivergence(CI); 940 return false; 941 } 942 943 const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V); 944 if (!ExtValue) 945 return false; 946 947 const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0)); 948 if (!CI) 949 return false; 950 951 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) { 952 switch (Intrinsic->getIntrinsicID()) { 953 default: 954 return false; 955 case Intrinsic::amdgcn_if: 956 case Intrinsic::amdgcn_else: { 957 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 958 return Indices.size() == 1 && Indices[0] == 1; 959 } 960 } 961 } 962 963 // If we have inline asm returning mixed SGPR and VGPR results, we inferred 964 // divergent for the overall struct return. We need to override it in the 965 // case we're extracting an SGPR component here. 966 if (CI->isInlineAsm()) 967 return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices()); 968 969 return false; 970 } 971 972 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes, 973 Intrinsic::ID IID) const { 974 switch (IID) { 975 case Intrinsic::amdgcn_atomic_inc: 976 case Intrinsic::amdgcn_atomic_dec: 977 case Intrinsic::amdgcn_ds_fadd: 978 case Intrinsic::amdgcn_ds_fmin: 979 case Intrinsic::amdgcn_ds_fmax: 980 case Intrinsic::amdgcn_is_shared: 981 case Intrinsic::amdgcn_is_private: 982 OpIndexes.push_back(0); 983 return true; 984 default: 985 return false; 986 } 987 } 988 989 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II, 990 Value *OldV, 991 Value *NewV) const { 992 auto IntrID = II->getIntrinsicID(); 993 switch (IntrID) { 994 case Intrinsic::amdgcn_atomic_inc: 995 case Intrinsic::amdgcn_atomic_dec: 996 case Intrinsic::amdgcn_ds_fadd: 997 case Intrinsic::amdgcn_ds_fmin: 998 case Intrinsic::amdgcn_ds_fmax: { 999 const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4)); 1000 if (!IsVolatile->isZero()) 1001 return nullptr; 1002 Module *M = II->getParent()->getParent()->getParent(); 1003 Type *DestTy = II->getType(); 1004 Type *SrcTy = NewV->getType(); 1005 Function *NewDecl = 1006 Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy}); 1007 II->setArgOperand(0, NewV); 1008 II->setCalledFunction(NewDecl); 1009 return II; 1010 } 1011 case Intrinsic::amdgcn_is_shared: 1012 case Intrinsic::amdgcn_is_private: { 1013 unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ? 1014 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 1015 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1016 LLVMContext &Ctx = NewV->getType()->getContext(); 1017 ConstantInt *NewVal = (TrueAS == NewAS) ? 1018 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx); 1019 return NewVal; 1020 } 1021 case Intrinsic::ptrmask: { 1022 unsigned OldAS = OldV->getType()->getPointerAddressSpace(); 1023 unsigned NewAS = NewV->getType()->getPointerAddressSpace(); 1024 Value *MaskOp = II->getArgOperand(1); 1025 Type *MaskTy = MaskOp->getType(); 1026 1027 bool DoTruncate = false; 1028 1029 const GCNTargetMachine &TM = 1030 static_cast<const GCNTargetMachine &>(getTLI()->getTargetMachine()); 1031 if (!TM.isNoopAddrSpaceCast(OldAS, NewAS)) { 1032 // All valid 64-bit to 32-bit casts work by chopping off the high 1033 // bits. Any masking only clearing the low bits will also apply in the new 1034 // address space. 1035 if (DL.getPointerSizeInBits(OldAS) != 64 || 1036 DL.getPointerSizeInBits(NewAS) != 32) 1037 return nullptr; 1038 1039 // TODO: Do we need to thread more context in here? 1040 KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II); 1041 if (Known.countMinLeadingOnes() < 32) 1042 return nullptr; 1043 1044 DoTruncate = true; 1045 } 1046 1047 IRBuilder<> B(II); 1048 if (DoTruncate) { 1049 MaskTy = B.getInt32Ty(); 1050 MaskOp = B.CreateTrunc(MaskOp, MaskTy); 1051 } 1052 1053 return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy}, 1054 {NewV, MaskOp}); 1055 } 1056 default: 1057 return nullptr; 1058 } 1059 } 1060 1061 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT, 1062 int Index, VectorType *SubTp) { 1063 if (ST->hasVOP3PInsts()) { 1064 if (cast<FixedVectorType>(VT)->getNumElements() == 2 && 1065 DL.getTypeSizeInBits(VT->getElementType()) == 16) { 1066 // With op_sel VOP3P instructions freely can access the low half or high 1067 // half of a register, so any swizzle is free. 1068 1069 switch (Kind) { 1070 case TTI::SK_Broadcast: 1071 case TTI::SK_Reverse: 1072 case TTI::SK_PermuteSingleSrc: 1073 return 0; 1074 default: 1075 break; 1076 } 1077 } 1078 } 1079 1080 return BaseT::getShuffleCost(Kind, VT, Index, SubTp); 1081 } 1082 1083 bool GCNTTIImpl::areInlineCompatible(const Function *Caller, 1084 const Function *Callee) const { 1085 const TargetMachine &TM = getTLI()->getTargetMachine(); 1086 const GCNSubtarget *CallerST 1087 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller)); 1088 const GCNSubtarget *CalleeST 1089 = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee)); 1090 1091 const FeatureBitset &CallerBits = CallerST->getFeatureBits(); 1092 const FeatureBitset &CalleeBits = CalleeST->getFeatureBits(); 1093 1094 FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList; 1095 FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList; 1096 if ((RealCallerBits & RealCalleeBits) != RealCalleeBits) 1097 return false; 1098 1099 // FIXME: dx10_clamp can just take the caller setting, but there seems to be 1100 // no way to support merge for backend defined attributes. 1101 AMDGPU::SIModeRegisterDefaults CallerMode(*Caller); 1102 AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee); 1103 return CallerMode.isInlineCompatible(CalleeMode); 1104 } 1105 1106 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1107 TTI::UnrollingPreferences &UP) { 1108 CommonTTI.getUnrollingPreferences(L, SE, UP); 1109 } 1110 1111 void GCNTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1112 TTI::PeelingPreferences &PP) { 1113 CommonTTI.getPeelingPreferences(L, SE, PP); 1114 } 1115 1116 R600TTIImpl::R600TTIImpl(const AMDGPUTargetMachine *TM, const Function &F) 1117 : BaseT(TM, F.getParent()->getDataLayout()), 1118 ST(static_cast<const R600Subtarget *>(TM->getSubtargetImpl(F))), 1119 TLI(ST->getTargetLowering()), CommonTTI(TM, F) {} 1120 1121 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const { 1122 return 4 * 128; // XXX - 4 channels. Should these count as vector instead? 1123 } 1124 1125 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const { 1126 return getHardwareNumberOfRegisters(Vec); 1127 } 1128 1129 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const { 1130 return 32; 1131 } 1132 1133 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const { 1134 return 32; 1135 } 1136 1137 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const { 1138 if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS || 1139 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) 1140 return 128; 1141 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1142 AddrSpace == AMDGPUAS::REGION_ADDRESS) 1143 return 64; 1144 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) 1145 return 32; 1146 1147 if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS || 1148 AddrSpace == AMDGPUAS::PARAM_I_ADDRESS || 1149 (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 && 1150 AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15))) 1151 return 128; 1152 llvm_unreachable("unhandled address space"); 1153 } 1154 1155 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes, 1156 Align Alignment, 1157 unsigned AddrSpace) const { 1158 // We allow vectorization of flat stores, even though we may need to decompose 1159 // them later if they may access private memory. We don't have enough context 1160 // here, and legalization can handle it. 1161 return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS); 1162 } 1163 1164 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes, 1165 Align Alignment, 1166 unsigned AddrSpace) const { 1167 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1168 } 1169 1170 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes, 1171 Align Alignment, 1172 unsigned AddrSpace) const { 1173 return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace); 1174 } 1175 1176 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) { 1177 // Disable unrolling if the loop is not vectorized. 1178 // TODO: Enable this again. 1179 if (VF == 1) 1180 return 1; 1181 1182 return 8; 1183 } 1184 1185 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode, 1186 TTI::TargetCostKind CostKind) { 1187 if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency) 1188 return Opcode == Instruction::PHI ? 0 : 1; 1189 1190 // XXX - For some reason this isn't called for switch. 1191 switch (Opcode) { 1192 case Instruction::Br: 1193 case Instruction::Ret: 1194 return 10; 1195 default: 1196 return BaseT::getCFInstrCost(Opcode, CostKind); 1197 } 1198 } 1199 1200 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 1201 unsigned Index) { 1202 switch (Opcode) { 1203 case Instruction::ExtractElement: 1204 case Instruction::InsertElement: { 1205 unsigned EltSize 1206 = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType()); 1207 if (EltSize < 32) { 1208 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1209 } 1210 1211 // Extracts are just reads of a subregister, so are free. Inserts are 1212 // considered free because we don't want to have any cost for scalarizing 1213 // operations, and we don't have to copy into a different register class. 1214 1215 // Dynamic indexing isn't free and is best avoided. 1216 return Index == ~0u ? 2 : 0; 1217 } 1218 default: 1219 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 1220 } 1221 } 1222 1223 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1224 TTI::UnrollingPreferences &UP) { 1225 CommonTTI.getUnrollingPreferences(L, SE, UP); 1226 } 1227 1228 void R600TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1229 TTI::PeelingPreferences &PP) { 1230 CommonTTI.getPeelingPreferences(L, SE, PP); 1231 } 1232