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 FixedVectorType::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 FixedVectorType::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 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
562                                       TTI::TargetCostKind CostKind) {
563   if (ICA.getID() == Intrinsic::fabs)
564     return 0;
565 
566   if (!intrinsicHasPackedVectorBenefit(ICA.getID()))
567     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
568 
569   Type *RetTy = ICA.getReturnType();
570   EVT OrigTy = TLI->getValueType(DL, RetTy);
571   if (!OrigTy.isSimple()) {
572     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
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 (ICA.getID() == Intrinsic::fma) {
592     InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost()
593                                    : getQuarterRateInstrCost();
594   }
595 
596   return LT.first * NElts * InstRate;
597 }
598 
599 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode,
600                                     TTI::TargetCostKind CostKind) {
601   // XXX - For some reason this isn't called for switch.
602   switch (Opcode) {
603   case Instruction::Br:
604   case Instruction::Ret:
605     return 10;
606   default:
607     return BaseT::getCFInstrCost(Opcode, CostKind);
608   }
609 }
610 
611 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
612                                            bool IsPairwise,
613                                            TTI::TargetCostKind CostKind) {
614   EVT OrigTy = TLI->getValueType(DL, Ty);
615 
616   // Computes cost on targets that have packed math instructions(which support
617   // 16-bit types only).
618   if (IsPairwise ||
619       !ST->hasVOP3PInsts() ||
620       OrigTy.getScalarSizeInBits() != 16)
621     return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind);
622 
623   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
624   return LT.first * getFullRateInstrCost();
625 }
626 
627 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
628                                        bool IsPairwise, bool IsUnsigned,
629                                        TTI::TargetCostKind CostKind) {
630   EVT OrigTy = TLI->getValueType(DL, Ty);
631 
632   // Computes cost on targets that have packed math instructions(which support
633   // 16-bit types only).
634   if (IsPairwise ||
635       !ST->hasVOP3PInsts() ||
636       OrigTy.getScalarSizeInBits() != 16)
637     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned,
638                                          CostKind);
639 
640   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
641   return LT.first * getHalfRateInstrCost();
642 }
643 
644 int GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
645                                       unsigned Index) {
646   switch (Opcode) {
647   case Instruction::ExtractElement:
648   case Instruction::InsertElement: {
649     unsigned EltSize
650       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
651     if (EltSize < 32) {
652       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
653         return 0;
654       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
655     }
656 
657     // Extracts are just reads of a subregister, so are free. Inserts are
658     // considered free because we don't want to have any cost for scalarizing
659     // operations, and we don't have to copy into a different register class.
660 
661     // Dynamic indexing isn't free and is best avoided.
662     return Index == ~0u ? 2 : 0;
663   }
664   default:
665     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
666   }
667 }
668 
669 static bool isArgPassedInSGPR(const Argument *A) {
670   const Function *F = A->getParent();
671 
672   // Arguments to compute shaders are never a source of divergence.
673   CallingConv::ID CC = F->getCallingConv();
674   switch (CC) {
675   case CallingConv::AMDGPU_KERNEL:
676   case CallingConv::SPIR_KERNEL:
677     return true;
678   case CallingConv::AMDGPU_VS:
679   case CallingConv::AMDGPU_LS:
680   case CallingConv::AMDGPU_HS:
681   case CallingConv::AMDGPU_ES:
682   case CallingConv::AMDGPU_GS:
683   case CallingConv::AMDGPU_PS:
684   case CallingConv::AMDGPU_CS:
685     // For non-compute shaders, SGPR inputs are marked with either inreg or byval.
686     // Everything else is in VGPRs.
687     return F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::InReg) ||
688            F->getAttributes().hasParamAttribute(A->getArgNo(), Attribute::ByVal);
689   default:
690     // TODO: Should calls support inreg for SGPR inputs?
691     return false;
692   }
693 }
694 
695 /// Analyze if the results of inline asm are divergent. If \p Indices is empty,
696 /// this is analyzing the collective result of all output registers. Otherwise,
697 /// this is only querying a specific result index if this returns multiple
698 /// registers in a struct.
699 bool GCNTTIImpl::isInlineAsmSourceOfDivergence(
700   const CallInst *CI, ArrayRef<unsigned> Indices) const {
701   // TODO: Handle complex extract indices
702   if (Indices.size() > 1)
703     return true;
704 
705   const DataLayout &DL = CI->getModule()->getDataLayout();
706   const SIRegisterInfo *TRI = ST->getRegisterInfo();
707   TargetLowering::AsmOperandInfoVector TargetConstraints =
708       TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI);
709 
710   const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0];
711 
712   int OutputIdx = 0;
713   for (auto &TC : TargetConstraints) {
714     if (TC.Type != InlineAsm::isOutput)
715       continue;
716 
717     // Skip outputs we don't care about.
718     if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++)
719       continue;
720 
721     TLI->ComputeConstraintToUse(TC, SDValue());
722 
723     Register AssignedReg;
724     const TargetRegisterClass *RC;
725     std::tie(AssignedReg, RC) = TLI->getRegForInlineAsmConstraint(
726       TRI, TC.ConstraintCode, TC.ConstraintVT);
727     if (AssignedReg) {
728       // FIXME: This is a workaround for getRegForInlineAsmConstraint
729       // returning VS_32
730       RC = TRI->getPhysRegClass(AssignedReg);
731     }
732 
733     // For AGPR constraints null is returned on subtargets without AGPRs, so
734     // assume divergent for null.
735     if (!RC || !TRI->isSGPRClass(RC))
736       return true;
737   }
738 
739   return false;
740 }
741 
742 /// \returns true if the new GPU divergence analysis is enabled.
743 bool GCNTTIImpl::useGPUDivergenceAnalysis() const {
744   return !UseLegacyDA;
745 }
746 
747 /// \returns true if the result of the value could potentially be
748 /// different across workitems in a wavefront.
749 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const {
750   if (const Argument *A = dyn_cast<Argument>(V))
751     return !isArgPassedInSGPR(A);
752 
753   // Loads from the private and flat address spaces are divergent, because
754   // threads can execute the load instruction with the same inputs and get
755   // different results.
756   //
757   // All other loads are not divergent, because if threads issue loads with the
758   // same arguments, they will always get the same result.
759   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
760     return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
761            Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS;
762 
763   // Atomics are divergent because they are executed sequentially: when an
764   // atomic operation refers to the same address in each thread, then each
765   // thread after the first sees the value written by the previous thread as
766   // original value.
767   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
768     return true;
769 
770   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
771     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
772 
773   // Assume all function calls are a source of divergence.
774   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
775     if (CI->isInlineAsm())
776       return isInlineAsmSourceOfDivergence(CI);
777     return true;
778   }
779 
780   // Assume all function calls are a source of divergence.
781   if (isa<InvokeInst>(V))
782     return true;
783 
784   return false;
785 }
786 
787 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const {
788   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
789     switch (Intrinsic->getIntrinsicID()) {
790     default:
791       return false;
792     case Intrinsic::amdgcn_readfirstlane:
793     case Intrinsic::amdgcn_readlane:
794     case Intrinsic::amdgcn_icmp:
795     case Intrinsic::amdgcn_fcmp:
796     case Intrinsic::amdgcn_ballot:
797     case Intrinsic::amdgcn_if_break:
798       return true;
799     }
800   }
801 
802   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
803     if (CI->isInlineAsm())
804       return !isInlineAsmSourceOfDivergence(CI);
805     return false;
806   }
807 
808   const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V);
809   if (!ExtValue)
810     return false;
811 
812   const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0));
813   if (!CI)
814     return false;
815 
816   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) {
817     switch (Intrinsic->getIntrinsicID()) {
818     default:
819       return false;
820     case Intrinsic::amdgcn_if:
821     case Intrinsic::amdgcn_else: {
822       ArrayRef<unsigned> Indices = ExtValue->getIndices();
823       return Indices.size() == 1 && Indices[0] == 1;
824     }
825     }
826   }
827 
828   // If we have inline asm returning mixed SGPR and VGPR results, we inferred
829   // divergent for the overall struct return. We need to override it in the
830   // case we're extracting an SGPR component here.
831   if (CI->isInlineAsm())
832     return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices());
833 
834   return false;
835 }
836 
837 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
838                                             Intrinsic::ID IID) const {
839   switch (IID) {
840   case Intrinsic::amdgcn_atomic_inc:
841   case Intrinsic::amdgcn_atomic_dec:
842   case Intrinsic::amdgcn_ds_fadd:
843   case Intrinsic::amdgcn_ds_fmin:
844   case Intrinsic::amdgcn_ds_fmax:
845   case Intrinsic::amdgcn_is_shared:
846   case Intrinsic::amdgcn_is_private:
847     OpIndexes.push_back(0);
848     return true;
849   default:
850     return false;
851   }
852 }
853 
854 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
855                                                     Value *OldV,
856                                                     Value *NewV) const {
857   auto IntrID = II->getIntrinsicID();
858   switch (IntrID) {
859   case Intrinsic::amdgcn_atomic_inc:
860   case Intrinsic::amdgcn_atomic_dec:
861   case Intrinsic::amdgcn_ds_fadd:
862   case Intrinsic::amdgcn_ds_fmin:
863   case Intrinsic::amdgcn_ds_fmax: {
864     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
865     if (!IsVolatile->isZero())
866       return nullptr;
867     Module *M = II->getParent()->getParent()->getParent();
868     Type *DestTy = II->getType();
869     Type *SrcTy = NewV->getType();
870     Function *NewDecl =
871         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
872     II->setArgOperand(0, NewV);
873     II->setCalledFunction(NewDecl);
874     return II;
875   }
876   case Intrinsic::amdgcn_is_shared:
877   case Intrinsic::amdgcn_is_private: {
878     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
879       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
880     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
881     LLVMContext &Ctx = NewV->getType()->getContext();
882     ConstantInt *NewVal = (TrueAS == NewAS) ?
883       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
884     return NewVal;
885   }
886   case Intrinsic::ptrmask: {
887     unsigned OldAS = OldV->getType()->getPointerAddressSpace();
888     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
889     Value *MaskOp = II->getArgOperand(1);
890     Type *MaskTy = MaskOp->getType();
891 
892     bool DoTruncate = false;
893     if (!getTLI()->isNoopAddrSpaceCast(OldAS, NewAS)) {
894       // All valid 64-bit to 32-bit casts work by chopping off the high
895       // bits. Any masking only clearing the low bits will also apply in the new
896       // address space.
897       if (DL.getPointerSizeInBits(OldAS) != 64 ||
898           DL.getPointerSizeInBits(NewAS) != 32)
899         return nullptr;
900 
901       // TODO: Do we need to thread more context in here?
902       KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II);
903       if (Known.countMinLeadingOnes() < 32)
904         return nullptr;
905 
906       DoTruncate = true;
907     }
908 
909     IRBuilder<> B(II);
910     if (DoTruncate) {
911       MaskTy = B.getInt32Ty();
912       MaskOp = B.CreateTrunc(MaskOp, MaskTy);
913     }
914 
915     return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy},
916                              {NewV, MaskOp});
917   }
918   default:
919     return nullptr;
920   }
921 }
922 
923 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT,
924                                     int Index, VectorType *SubTp) {
925   if (ST->hasVOP3PInsts()) {
926     if (cast<FixedVectorType>(VT)->getNumElements() == 2 &&
927         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
928       // With op_sel VOP3P instructions freely can access the low half or high
929       // half of a register, so any swizzle is free.
930 
931       switch (Kind) {
932       case TTI::SK_Broadcast:
933       case TTI::SK_Reverse:
934       case TTI::SK_PermuteSingleSrc:
935         return 0;
936       default:
937         break;
938       }
939     }
940   }
941 
942   return BaseT::getShuffleCost(Kind, VT, Index, SubTp);
943 }
944 
945 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
946                                      const Function *Callee) const {
947   const TargetMachine &TM = getTLI()->getTargetMachine();
948   const GCNSubtarget *CallerST
949     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
950   const GCNSubtarget *CalleeST
951     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
952 
953   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
954   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
955 
956   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
957   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
958   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
959     return false;
960 
961   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
962   // no way to support merge for backend defined attributes.
963   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller);
964   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee);
965   return CallerMode.isInlineCompatible(CalleeMode);
966 }
967 
968 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
969                                          TTI::UnrollingPreferences &UP) {
970   CommonTTI.getUnrollingPreferences(L, SE, UP);
971 }
972 
973 unsigned
974 GCNTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands,
975                         TTI::TargetCostKind CostKind) {
976   const Instruction *I = dyn_cast<Instruction>(U);
977   if (!I)
978     return BaseT::getUserCost(U, Operands, CostKind);
979 
980   // Estimate different operations to be optimized out
981   switch (I->getOpcode()) {
982   case Instruction::ExtractElement: {
983     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
984     unsigned Idx = -1;
985     if (CI)
986       Idx = CI->getZExtValue();
987     return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx);
988   }
989   case Instruction::InsertElement: {
990     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
991     unsigned Idx = -1;
992     if (CI)
993       Idx = CI->getZExtValue();
994     return getVectorInstrCost(I->getOpcode(), I->getType(), Idx);
995   }
996   case Instruction::Call: {
997     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
998       IntrinsicCostAttributes CostAttrs(*II);
999       return getIntrinsicInstrCost(CostAttrs, CostKind);
1000     } else {
1001       return BaseT::getUserCost(U, Operands, CostKind);
1002     }
1003   }
1004   case Instruction::ShuffleVector: {
1005     const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1006     auto *Ty = cast<VectorType>(Shuffle->getType());
1007     auto *SrcTy = cast<VectorType>(Shuffle->getOperand(0)->getType());
1008 
1009     // TODO: Identify and add costs for insert subvector, etc.
1010     int SubIndex;
1011     if (Shuffle->isExtractSubvectorMask(SubIndex))
1012       return getShuffleCost(TTI::SK_ExtractSubvector, SrcTy, SubIndex, Ty);
1013 
1014     if (Shuffle->changesLength())
1015       return BaseT::getUserCost(U, Operands, CostKind);
1016 
1017     if (Shuffle->isIdentity())
1018       return 0;
1019 
1020     if (Shuffle->isReverse())
1021       return getShuffleCost(TTI::SK_Reverse, Ty, 0, nullptr);
1022 
1023     if (Shuffle->isSelect())
1024       return getShuffleCost(TTI::SK_Select, Ty, 0, nullptr);
1025 
1026     if (Shuffle->isTranspose())
1027       return getShuffleCost(TTI::SK_Transpose, Ty, 0, nullptr);
1028 
1029     if (Shuffle->isZeroEltSplat())
1030       return getShuffleCost(TTI::SK_Broadcast, Ty, 0, nullptr);
1031 
1032     if (Shuffle->isSingleSource())
1033       return getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, 0, nullptr);
1034 
1035     return getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, 0, nullptr);
1036   }
1037   case Instruction::ZExt:
1038   case Instruction::SExt:
1039   case Instruction::FPToUI:
1040   case Instruction::FPToSI:
1041   case Instruction::FPExt:
1042   case Instruction::PtrToInt:
1043   case Instruction::IntToPtr:
1044   case Instruction::SIToFP:
1045   case Instruction::UIToFP:
1046   case Instruction::Trunc:
1047   case Instruction::FPTrunc:
1048   case Instruction::BitCast:
1049   case Instruction::AddrSpaceCast: {
1050     return getCastInstrCost(I->getOpcode(), I->getType(),
1051                             I->getOperand(0)->getType(), CostKind, I);
1052   }
1053   case Instruction::Add:
1054   case Instruction::FAdd:
1055   case Instruction::Sub:
1056   case Instruction::FSub:
1057   case Instruction::Mul:
1058   case Instruction::FMul:
1059   case Instruction::UDiv:
1060   case Instruction::SDiv:
1061   case Instruction::FDiv:
1062   case Instruction::URem:
1063   case Instruction::SRem:
1064   case Instruction::FRem:
1065   case Instruction::Shl:
1066   case Instruction::LShr:
1067   case Instruction::AShr:
1068   case Instruction::And:
1069   case Instruction::Or:
1070   case Instruction::Xor:
1071   case Instruction::FNeg: {
1072     return getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind,
1073                                   TTI::OK_AnyValue, TTI::OK_AnyValue,
1074                                   TTI::OP_None, TTI::OP_None, Operands, I);
1075   }
1076   default:
1077     break;
1078   }
1079 
1080   return BaseT::getUserCost(U, Operands, CostKind);
1081 }
1082 
1083 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
1084   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
1085 }
1086 
1087 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const {
1088   return getHardwareNumberOfRegisters(Vec);
1089 }
1090 
1091 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const {
1092   return 32;
1093 }
1094 
1095 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const {
1096   return 32;
1097 }
1098 
1099 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
1100   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
1101       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS)
1102     return 128;
1103   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1104       AddrSpace == AMDGPUAS::REGION_ADDRESS)
1105     return 64;
1106   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
1107     return 32;
1108 
1109   if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS ||
1110       AddrSpace == AMDGPUAS::PARAM_I_ADDRESS ||
1111       (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 &&
1112       AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15)))
1113     return 128;
1114   llvm_unreachable("unhandled address space");
1115 }
1116 
1117 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
1118                                              unsigned Alignment,
1119                                              unsigned AddrSpace) const {
1120   // We allow vectorization of flat stores, even though we may need to decompose
1121   // them later if they may access private memory. We don't have enough context
1122   // here, and legalization can handle it.
1123   return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS);
1124 }
1125 
1126 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1127                                               unsigned Alignment,
1128                                               unsigned AddrSpace) const {
1129   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1130 }
1131 
1132 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1133                                                unsigned Alignment,
1134                                                unsigned AddrSpace) const {
1135   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1136 }
1137 
1138 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) {
1139   // Disable unrolling if the loop is not vectorized.
1140   // TODO: Enable this again.
1141   if (VF == 1)
1142     return 1;
1143 
1144   return 8;
1145 }
1146 
1147 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode,
1148                                      TTI::TargetCostKind CostKind) {
1149   // XXX - For some reason this isn't called for switch.
1150   switch (Opcode) {
1151   case Instruction::Br:
1152   case Instruction::Ret:
1153     return 10;
1154   default:
1155     return BaseT::getCFInstrCost(Opcode, CostKind);
1156   }
1157 }
1158 
1159 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
1160                                     unsigned Index) {
1161   switch (Opcode) {
1162   case Instruction::ExtractElement:
1163   case Instruction::InsertElement: {
1164     unsigned EltSize
1165       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
1166     if (EltSize < 32) {
1167       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1168     }
1169 
1170     // Extracts are just reads of a subregister, so are free. Inserts are
1171     // considered free because we don't want to have any cost for scalarizing
1172     // operations, and we don't have to copy into a different register class.
1173 
1174     // Dynamic indexing isn't free and is best avoided.
1175     return Index == ~0u ? 2 : 0;
1176   }
1177   default:
1178     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1179   }
1180 }
1181 
1182 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1183                                           TTI::UnrollingPreferences &UP) {
1184   CommonTTI.getUnrollingPreferences(L, SE, UP);
1185 }
1186