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