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