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