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