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