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 cl::opt<unsigned> UnrollMaxBlockToAnalyze(
83     "amdgpu-unroll-max-block-to-analyze",
84     cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"),
85     cl::init(20), cl::Hidden);
86 
87 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond,
88                               unsigned Depth = 0) {
89   const Instruction *I = dyn_cast<Instruction>(Cond);
90   if (!I)
91     return false;
92 
93   for (const Value *V : I->operand_values()) {
94     if (!L->contains(I))
95       continue;
96     if (const PHINode *PHI = dyn_cast<PHINode>(V)) {
97       if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) {
98                   return SubLoop->contains(PHI); }))
99         return true;
100     } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1))
101       return true;
102   }
103   return false;
104 }
105 
106 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
107                                             TTI::UnrollingPreferences &UP) {
108   const Function &F = *L->getHeader()->getParent();
109   UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300);
110   UP.MaxCount = std::numeric_limits<unsigned>::max();
111   UP.Partial = true;
112 
113   // TODO: Do we want runtime unrolling?
114 
115   // Maximum alloca size than can fit registers. Reserve 16 registers.
116   const unsigned MaxAlloca = (256 - 16) * 4;
117   unsigned ThresholdPrivate = UnrollThresholdPrivate;
118   unsigned ThresholdLocal = UnrollThresholdLocal;
119   unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal);
120   for (const BasicBlock *BB : L->getBlocks()) {
121     const DataLayout &DL = BB->getModule()->getDataLayout();
122     unsigned LocalGEPsSeen = 0;
123 
124     if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) {
125                return SubLoop->contains(BB); }))
126         continue; // Block belongs to an inner loop.
127 
128     for (const Instruction &I : *BB) {
129       // Unroll a loop which contains an "if" statement whose condition
130       // defined by a PHI belonging to the loop. This may help to eliminate
131       // if region and potentially even PHI itself, saving on both divergence
132       // and registers used for the PHI.
133       // Add a small bonus for each of such "if" statements.
134       if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) {
135         if (UP.Threshold < MaxBoost && Br->isConditional()) {
136           BasicBlock *Succ0 = Br->getSuccessor(0);
137           BasicBlock *Succ1 = Br->getSuccessor(1);
138           if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) ||
139               (L->contains(Succ1) && L->isLoopExiting(Succ1)))
140             continue;
141           if (dependsOnLocalPhi(L, Br->getCondition())) {
142             UP.Threshold += UnrollThresholdIf;
143             LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold
144                               << " for loop:\n"
145                               << *L << " due to " << *Br << '\n');
146             if (UP.Threshold >= MaxBoost)
147               return;
148           }
149         }
150         continue;
151       }
152 
153       const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
154       if (!GEP)
155         continue;
156 
157       unsigned AS = GEP->getAddressSpace();
158       unsigned Threshold = 0;
159       if (AS == AMDGPUAS::PRIVATE_ADDRESS)
160         Threshold = ThresholdPrivate;
161       else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS)
162         Threshold = ThresholdLocal;
163       else
164         continue;
165 
166       if (UP.Threshold >= Threshold)
167         continue;
168 
169       if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
170         const Value *Ptr = GEP->getPointerOperand();
171         const AllocaInst *Alloca =
172             dyn_cast<AllocaInst>(GetUnderlyingObject(Ptr, DL));
173         if (!Alloca || !Alloca->isStaticAlloca())
174           continue;
175         Type *Ty = Alloca->getAllocatedType();
176         unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0;
177         if (AllocaSize > MaxAlloca)
178           continue;
179       } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
180                  AS == AMDGPUAS::REGION_ADDRESS) {
181         LocalGEPsSeen++;
182         // Inhibit unroll for local memory if we have seen addressing not to
183         // a variable, most likely we will be unable to combine it.
184         // Do not unroll too deep inner loops for local memory to give a chance
185         // to unroll an outer loop for a more important reason.
186         if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 ||
187             (!isa<GlobalVariable>(GEP->getPointerOperand()) &&
188              !isa<Argument>(GEP->getPointerOperand())))
189           continue;
190         LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n"
191                           << *L << " due to LDS use.\n");
192         UP.Runtime = UnrollRuntimeLocal;
193       }
194 
195       // Check if GEP depends on a value defined by this loop itself.
196       bool HasLoopDef = false;
197       for (const Value *Op : GEP->operands()) {
198         const Instruction *Inst = dyn_cast<Instruction>(Op);
199         if (!Inst || L->isLoopInvariant(Op))
200           continue;
201 
202         if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) {
203              return SubLoop->contains(Inst); }))
204           continue;
205         HasLoopDef = true;
206         break;
207       }
208       if (!HasLoopDef)
209         continue;
210 
211       // We want to do whatever we can to limit the number of alloca
212       // instructions that make it through to the code generator.  allocas
213       // require us to use indirect addressing, which is slow and prone to
214       // compiler bugs.  If this loop does an address calculation on an
215       // alloca ptr, then we want to use a higher than normal loop unroll
216       // threshold. This will give SROA a better chance to eliminate these
217       // allocas.
218       //
219       // We also want to have more unrolling for local memory to let ds
220       // instructions with different offsets combine.
221       //
222       // Don't use the maximum allowed value here as it will make some
223       // programs way too big.
224       UP.Threshold = Threshold;
225       LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold
226                         << " for loop:\n"
227                         << *L << " due to " << *GEP << '\n');
228       if (UP.Threshold >= MaxBoost)
229         return;
230     }
231 
232     // If we got a GEP in a small BB from inner loop then increase max trip
233     // count to analyze for better estimation cost in unroll
234     if (L->empty() && BB->size() < UnrollMaxBlockToAnalyze)
235       UP.MaxIterationsCountToAnalyze = 32;
236   }
237 }
238 
239 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
240   // The concept of vector registers doesn't really exist. Some packed vector
241   // operations operate on the normal 32-bit registers.
242   return 256;
243 }
244 
245 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const {
246   // This is really the number of registers to fill when vectorizing /
247   // interleaving loops, so we lie to avoid trying to use all registers.
248   return getHardwareNumberOfRegisters(Vec) >> 3;
249 }
250 
251 unsigned GCNTTIImpl::getRegisterBitWidth(bool Vector) const {
252   return 32;
253 }
254 
255 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const {
256   return 32;
257 }
258 
259 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize,
260                                             unsigned ChainSizeInBytes,
261                                             VectorType *VecTy) const {
262   unsigned VecRegBitWidth = VF * LoadSize;
263   if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32)
264     // TODO: Support element-size less than 32bit?
265     return 128 / LoadSize;
266 
267   return VF;
268 }
269 
270 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize,
271                                              unsigned ChainSizeInBytes,
272                                              VectorType *VecTy) const {
273   unsigned VecRegBitWidth = VF * StoreSize;
274   if (VecRegBitWidth > 128)
275     return 128 / StoreSize;
276 
277   return VF;
278 }
279 
280 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
281   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
282       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
283       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
284       AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) {
285     return 512;
286   }
287 
288   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
289     return 8 * ST->getMaxPrivateElementSize();
290 
291   // Common to flat, global, local and region. Assume for unknown addrspace.
292   return 128;
293 }
294 
295 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
296                                                unsigned Alignment,
297                                                unsigned AddrSpace) const {
298   // We allow vectorization of flat stores, even though we may need to decompose
299   // them later if they may access private memory. We don't have enough context
300   // here, and legalization can handle it.
301   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
302     return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) &&
303       ChainSizeInBytes <= ST->getMaxPrivateElementSize();
304   }
305   return true;
306 }
307 
308 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
309                                                 unsigned Alignment,
310                                                 unsigned AddrSpace) const {
311   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
312 }
313 
314 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
315                                                  unsigned Alignment,
316                                                  unsigned AddrSpace) const {
317   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
318 }
319 
320 // FIXME: Really we would like to issue multiple 128-bit loads and stores per
321 // iteration. Should we report a larger size and let it legalize?
322 //
323 // FIXME: Should we use narrower types for local/region, or account for when
324 // unaligned access is legal?
325 //
326 // FIXME: This could use fine tuning and microbenchmarks.
327 Type *GCNTTIImpl::getMemcpyLoopLoweringType(LLVMContext &Context, Value *Length,
328                                             unsigned SrcAddrSpace,
329                                             unsigned DestAddrSpace,
330                                             unsigned SrcAlign,
331                                             unsigned DestAlign) const {
332   unsigned MinAlign = std::min(SrcAlign, DestAlign);
333 
334   // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the
335   // hardware into byte accesses. If you assume all alignments are equally
336   // probable, it's more efficient on average to use short accesses for this
337   // case.
338   if (MinAlign == 2)
339     return Type::getInt16Ty(Context);
340 
341   // Not all subtargets have 128-bit DS instructions, and we currently don't
342   // form them by default.
343   if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
344       SrcAddrSpace == AMDGPUAS::REGION_ADDRESS ||
345       DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
346       DestAddrSpace == AMDGPUAS::REGION_ADDRESS) {
347     return FixedVectorType::get(Type::getInt32Ty(Context), 2);
348   }
349 
350   // Global memory works best with 16-byte accesses. Private memory will also
351   // hit this, although they'll be decomposed.
352   return FixedVectorType::get(Type::getInt32Ty(Context), 4);
353 }
354 
355 void GCNTTIImpl::getMemcpyLoopResidualLoweringType(
356   SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
357   unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
358   unsigned SrcAlign, unsigned DestAlign) const {
359   assert(RemainingBytes < 16);
360 
361   unsigned MinAlign = std::min(SrcAlign, DestAlign);
362 
363   if (MinAlign != 2) {
364     Type *I64Ty = Type::getInt64Ty(Context);
365     while (RemainingBytes >= 8) {
366       OpsOut.push_back(I64Ty);
367       RemainingBytes -= 8;
368     }
369 
370     Type *I32Ty = Type::getInt32Ty(Context);
371     while (RemainingBytes >= 4) {
372       OpsOut.push_back(I32Ty);
373       RemainingBytes -= 4;
374     }
375   }
376 
377   Type *I16Ty = Type::getInt16Ty(Context);
378   while (RemainingBytes >= 2) {
379     OpsOut.push_back(I16Ty);
380     RemainingBytes -= 2;
381   }
382 
383   Type *I8Ty = Type::getInt8Ty(Context);
384   while (RemainingBytes) {
385     OpsOut.push_back(I8Ty);
386     --RemainingBytes;
387   }
388 }
389 
390 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) {
391   // Disable unrolling if the loop is not vectorized.
392   // TODO: Enable this again.
393   if (VF == 1)
394     return 1;
395 
396   return 8;
397 }
398 
399 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
400                                        MemIntrinsicInfo &Info) const {
401   switch (Inst->getIntrinsicID()) {
402   case Intrinsic::amdgcn_atomic_inc:
403   case Intrinsic::amdgcn_atomic_dec:
404   case Intrinsic::amdgcn_ds_ordered_add:
405   case Intrinsic::amdgcn_ds_ordered_swap:
406   case Intrinsic::amdgcn_ds_fadd:
407   case Intrinsic::amdgcn_ds_fmin:
408   case Intrinsic::amdgcn_ds_fmax: {
409     auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2));
410     auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4));
411     if (!Ordering || !Volatile)
412       return false; // Invalid.
413 
414     unsigned OrderingVal = Ordering->getZExtValue();
415     if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent))
416       return false;
417 
418     Info.PtrVal = Inst->getArgOperand(0);
419     Info.Ordering = static_cast<AtomicOrdering>(OrderingVal);
420     Info.ReadMem = true;
421     Info.WriteMem = true;
422     Info.IsVolatile = !Volatile->isNullValue();
423     return true;
424   }
425   default:
426     return false;
427   }
428 }
429 
430 int GCNTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
431                                        TTI::TargetCostKind CostKind,
432                                        TTI::OperandValueKind Opd1Info,
433                                        TTI::OperandValueKind Opd2Info,
434                                        TTI::OperandValueProperties Opd1PropInfo,
435                                        TTI::OperandValueProperties Opd2PropInfo,
436                                        ArrayRef<const Value *> Args,
437                                        const Instruction *CxtI) {
438   EVT OrigTy = TLI->getValueType(DL, Ty);
439   if (!OrigTy.isSimple()) {
440     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
441                                          Opd2Info,
442                                          Opd1PropInfo, Opd2PropInfo);
443   }
444 
445   // Legalize the type.
446   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
447   int ISD = TLI->InstructionOpcodeToISD(Opcode);
448 
449   // Because we don't have any legal vector operations, but the legal types, we
450   // need to account for split vectors.
451   unsigned NElts = LT.second.isVector() ?
452     LT.second.getVectorNumElements() : 1;
453 
454   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
455 
456   switch (ISD) {
457   case ISD::SHL:
458   case ISD::SRL:
459   case ISD::SRA:
460     if (SLT == MVT::i64)
461       return get64BitInstrCost() * LT.first * NElts;
462 
463     if (ST->has16BitInsts() && SLT == MVT::i16)
464       NElts = (NElts + 1) / 2;
465 
466     // i32
467     return getFullRateInstrCost() * LT.first * NElts;
468   case ISD::ADD:
469   case ISD::SUB:
470   case ISD::AND:
471   case ISD::OR:
472   case ISD::XOR:
473     if (SLT == MVT::i64) {
474       // and, or and xor are typically split into 2 VALU instructions.
475       return 2 * getFullRateInstrCost() * LT.first * NElts;
476     }
477 
478     if (ST->has16BitInsts() && SLT == MVT::i16)
479       NElts = (NElts + 1) / 2;
480 
481     return LT.first * NElts * getFullRateInstrCost();
482   case ISD::MUL: {
483     const int QuarterRateCost = getQuarterRateInstrCost();
484     if (SLT == MVT::i64) {
485       const int FullRateCost = getFullRateInstrCost();
486       return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts;
487     }
488 
489     if (ST->has16BitInsts() && SLT == MVT::i16)
490       NElts = (NElts + 1) / 2;
491 
492     // i32
493     return QuarterRateCost * NElts * LT.first;
494   }
495   case ISD::FADD:
496   case ISD::FSUB:
497   case ISD::FMUL:
498     if (SLT == MVT::f64)
499       return LT.first * NElts * get64BitInstrCost();
500 
501     if (ST->has16BitInsts() && SLT == MVT::f16)
502       NElts = (NElts + 1) / 2;
503 
504     if (SLT == MVT::f32 || SLT == MVT::f16)
505       return LT.first * NElts * getFullRateInstrCost();
506     break;
507   case ISD::FDIV:
508   case ISD::FREM:
509     // FIXME: frem should be handled separately. The fdiv in it is most of it,
510     // but the current lowering is also not entirely correct.
511     if (SLT == MVT::f64) {
512       int Cost = 4 * get64BitInstrCost() + 7 * getQuarterRateInstrCost();
513       // Add cost of workaround.
514       if (!ST->hasUsableDivScaleConditionOutput())
515         Cost += 3 * getFullRateInstrCost();
516 
517       return LT.first * Cost * NElts;
518     }
519 
520     if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) {
521       // TODO: This is more complicated, unsafe flags etc.
522       if ((SLT == MVT::f32 && !HasFP32Denormals) ||
523           (SLT == MVT::f16 && ST->has16BitInsts())) {
524         return LT.first * getQuarterRateInstrCost() * NElts;
525       }
526     }
527 
528     if (SLT == MVT::f16 && ST->has16BitInsts()) {
529       // 2 x v_cvt_f32_f16
530       // f32 rcp
531       // f32 fmul
532       // v_cvt_f16_f32
533       // f16 div_fixup
534       int Cost = 4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost();
535       return LT.first * Cost * NElts;
536     }
537 
538     if (SLT == MVT::f32 || SLT == MVT::f16) {
539       int Cost = 7 * getFullRateInstrCost() + 1 * getQuarterRateInstrCost();
540 
541       if (!HasFP32Denormals) {
542         // FP mode switches.
543         Cost += 2 * getFullRateInstrCost();
544       }
545 
546       return LT.first * NElts * Cost;
547     }
548     break;
549   default:
550     break;
551   }
552 
553   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
554                                        Opd2Info,
555                                        Opd1PropInfo, Opd2PropInfo);
556 }
557 
558 // Return true if there's a potential benefit from using v2f16 instructions for
559 // an intrinsic, even if it requires nontrivial legalization.
560 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) {
561   switch (ID) {
562   case Intrinsic::fma: // TODO: fmuladd
563   // There's a small benefit to using vector ops in the legalized code.
564   case Intrinsic::round:
565     return true;
566   default:
567     return false;
568   }
569 }
570 
571 int GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
572                                       TTI::TargetCostKind CostKind) {
573   if (ICA.getID() == Intrinsic::fabs)
574     return 0;
575 
576   if (!intrinsicHasPackedVectorBenefit(ICA.getID()))
577     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
578 
579   Type *RetTy = ICA.getReturnType();
580   EVT OrigTy = TLI->getValueType(DL, RetTy);
581   if (!OrigTy.isSimple()) {
582     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
583   }
584 
585   // Legalize the type.
586   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
587 
588   unsigned NElts = LT.second.isVector() ?
589     LT.second.getVectorNumElements() : 1;
590 
591   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
592 
593   if (SLT == MVT::f64)
594     return LT.first * NElts * get64BitInstrCost();
595 
596   if (ST->has16BitInsts() && SLT == MVT::f16)
597     NElts = (NElts + 1) / 2;
598 
599   // TODO: Get more refined intrinsic costs?
600   unsigned InstRate = getQuarterRateInstrCost();
601   if (ICA.getID() == Intrinsic::fma) {
602     InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost()
603                                    : getQuarterRateInstrCost();
604   }
605 
606   return LT.first * NElts * InstRate;
607 }
608 
609 unsigned GCNTTIImpl::getCFInstrCost(unsigned Opcode,
610                                     TTI::TargetCostKind CostKind) {
611   // XXX - For some reason this isn't called for switch.
612   switch (Opcode) {
613   case Instruction::Br:
614   case Instruction::Ret:
615     return 10;
616   default:
617     return BaseT::getCFInstrCost(Opcode, CostKind);
618   }
619 }
620 
621 int GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
622                                            bool IsPairwise,
623                                            TTI::TargetCostKind CostKind) {
624   EVT OrigTy = TLI->getValueType(DL, Ty);
625 
626   // Computes cost on targets that have packed math instructions(which support
627   // 16-bit types only).
628   if (IsPairwise ||
629       !ST->hasVOP3PInsts() ||
630       OrigTy.getScalarSizeInBits() != 16)
631     return BaseT::getArithmeticReductionCost(Opcode, Ty, IsPairwise, CostKind);
632 
633   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
634   return LT.first * getFullRateInstrCost();
635 }
636 
637 int GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
638                                        bool IsPairwise, bool IsUnsigned,
639                                        TTI::TargetCostKind CostKind) {
640   EVT OrigTy = TLI->getValueType(DL, Ty);
641 
642   // Computes cost on targets that have packed math instructions(which support
643   // 16-bit types only).
644   if (IsPairwise ||
645       !ST->hasVOP3PInsts() ||
646       OrigTy.getScalarSizeInBits() != 16)
647     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned,
648                                          CostKind);
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 (CI->isInlineAsm())
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 (CI->isInlineAsm())
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 (CI->isInlineAsm())
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 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
865                                                     Value *OldV,
866                                                     Value *NewV) const {
867   auto IntrID = II->getIntrinsicID();
868   switch (IntrID) {
869   case Intrinsic::amdgcn_atomic_inc:
870   case Intrinsic::amdgcn_atomic_dec:
871   case Intrinsic::amdgcn_ds_fadd:
872   case Intrinsic::amdgcn_ds_fmin:
873   case Intrinsic::amdgcn_ds_fmax: {
874     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
875     if (!IsVolatile->isZero())
876       return nullptr;
877     Module *M = II->getParent()->getParent()->getParent();
878     Type *DestTy = II->getType();
879     Type *SrcTy = NewV->getType();
880     Function *NewDecl =
881         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
882     II->setArgOperand(0, NewV);
883     II->setCalledFunction(NewDecl);
884     return II;
885   }
886   case Intrinsic::amdgcn_is_shared:
887   case Intrinsic::amdgcn_is_private: {
888     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
889       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
890     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
891     LLVMContext &Ctx = NewV->getType()->getContext();
892     ConstantInt *NewVal = (TrueAS == NewAS) ?
893       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
894     return NewVal;
895   }
896   case Intrinsic::ptrmask: {
897     unsigned OldAS = OldV->getType()->getPointerAddressSpace();
898     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
899     Value *MaskOp = II->getArgOperand(1);
900     Type *MaskTy = MaskOp->getType();
901 
902     bool DoTruncate = false;
903     if (!getTLI()->isNoopAddrSpaceCast(OldAS, NewAS)) {
904       // All valid 64-bit to 32-bit casts work by chopping off the high
905       // bits. Any masking only clearing the low bits will also apply in the new
906       // address space.
907       if (DL.getPointerSizeInBits(OldAS) != 64 ||
908           DL.getPointerSizeInBits(NewAS) != 32)
909         return nullptr;
910 
911       // TODO: Do we need to thread more context in here?
912       KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II);
913       if (Known.countMinLeadingOnes() < 32)
914         return nullptr;
915 
916       DoTruncate = true;
917     }
918 
919     IRBuilder<> B(II);
920     if (DoTruncate) {
921       MaskTy = B.getInt32Ty();
922       MaskOp = B.CreateTrunc(MaskOp, MaskTy);
923     }
924 
925     return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy},
926                              {NewV, MaskOp});
927   }
928   default:
929     return nullptr;
930   }
931 }
932 
933 unsigned GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *VT,
934                                     int Index, VectorType *SubTp) {
935   if (ST->hasVOP3PInsts()) {
936     if (cast<FixedVectorType>(VT)->getNumElements() == 2 &&
937         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
938       // With op_sel VOP3P instructions freely can access the low half or high
939       // half of a register, so any swizzle is free.
940 
941       switch (Kind) {
942       case TTI::SK_Broadcast:
943       case TTI::SK_Reverse:
944       case TTI::SK_PermuteSingleSrc:
945         return 0;
946       default:
947         break;
948       }
949     }
950   }
951 
952   return BaseT::getShuffleCost(Kind, VT, Index, SubTp);
953 }
954 
955 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
956                                      const Function *Callee) const {
957   const TargetMachine &TM = getTLI()->getTargetMachine();
958   const GCNSubtarget *CallerST
959     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
960   const GCNSubtarget *CalleeST
961     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
962 
963   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
964   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
965 
966   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
967   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
968   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
969     return false;
970 
971   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
972   // no way to support merge for backend defined attributes.
973   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller);
974   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee);
975   return CallerMode.isInlineCompatible(CalleeMode);
976 }
977 
978 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
979                                          TTI::UnrollingPreferences &UP) {
980   CommonTTI.getUnrollingPreferences(L, SE, UP);
981 }
982 
983 unsigned
984 GCNTTIImpl::getUserCost(const User *U, ArrayRef<const Value *> Operands,
985                         TTI::TargetCostKind CostKind) {
986   const Instruction *I = dyn_cast<Instruction>(U);
987   if (!I)
988     return BaseT::getUserCost(U, Operands, CostKind);
989 
990   // Estimate different operations to be optimized out
991   switch (I->getOpcode()) {
992   case Instruction::ExtractElement: {
993     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1));
994     unsigned Idx = -1;
995     if (CI)
996       Idx = CI->getZExtValue();
997     return getVectorInstrCost(I->getOpcode(), I->getOperand(0)->getType(), Idx);
998   }
999   case Instruction::InsertElement: {
1000     ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1001     unsigned Idx = -1;
1002     if (CI)
1003       Idx = CI->getZExtValue();
1004     return getVectorInstrCost(I->getOpcode(), I->getType(), Idx);
1005   }
1006   case Instruction::ShuffleVector: {
1007     const ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1008     auto *Ty = cast<VectorType>(Shuffle->getType());
1009     auto *SrcTy = cast<VectorType>(Shuffle->getOperand(0)->getType());
1010 
1011     // TODO: Identify and add costs for insert subvector, etc.
1012     int SubIndex;
1013     if (Shuffle->isExtractSubvectorMask(SubIndex))
1014       return getShuffleCost(TTI::SK_ExtractSubvector, SrcTy, SubIndex, Ty);
1015 
1016     if (Shuffle->changesLength())
1017       return BaseT::getUserCost(U, Operands, CostKind);
1018 
1019     if (Shuffle->isIdentity())
1020       return 0;
1021 
1022     if (Shuffle->isReverse())
1023       return getShuffleCost(TTI::SK_Reverse, Ty, 0, nullptr);
1024 
1025     if (Shuffle->isSelect())
1026       return getShuffleCost(TTI::SK_Select, Ty, 0, nullptr);
1027 
1028     if (Shuffle->isTranspose())
1029       return getShuffleCost(TTI::SK_Transpose, Ty, 0, nullptr);
1030 
1031     if (Shuffle->isZeroEltSplat())
1032       return getShuffleCost(TTI::SK_Broadcast, Ty, 0, nullptr);
1033 
1034     if (Shuffle->isSingleSource())
1035       return getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, 0, nullptr);
1036 
1037     return getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, 0, nullptr);
1038   }
1039   case Instruction::Add:
1040   case Instruction::FAdd:
1041   case Instruction::Sub:
1042   case Instruction::FSub:
1043   case Instruction::Mul:
1044   case Instruction::FMul:
1045   case Instruction::UDiv:
1046   case Instruction::SDiv:
1047   case Instruction::FDiv:
1048   case Instruction::URem:
1049   case Instruction::SRem:
1050   case Instruction::FRem:
1051   case Instruction::Shl:
1052   case Instruction::LShr:
1053   case Instruction::AShr:
1054   case Instruction::And:
1055   case Instruction::Or:
1056   case Instruction::Xor:
1057   case Instruction::FNeg: {
1058     return getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind,
1059                                   TTI::OK_AnyValue, TTI::OK_AnyValue,
1060                                   TTI::OP_None, TTI::OP_None, Operands, I);
1061   }
1062   default:
1063     break;
1064   }
1065 
1066   return BaseT::getUserCost(U, Operands, CostKind);
1067 }
1068 
1069 unsigned R600TTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
1070   return 4 * 128; // XXX - 4 channels. Should these count as vector instead?
1071 }
1072 
1073 unsigned R600TTIImpl::getNumberOfRegisters(bool Vec) const {
1074   return getHardwareNumberOfRegisters(Vec);
1075 }
1076 
1077 unsigned R600TTIImpl::getRegisterBitWidth(bool Vector) const {
1078   return 32;
1079 }
1080 
1081 unsigned R600TTIImpl::getMinVectorRegisterBitWidth() const {
1082   return 32;
1083 }
1084 
1085 unsigned R600TTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
1086   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
1087       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS)
1088     return 128;
1089   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1090       AddrSpace == AMDGPUAS::REGION_ADDRESS)
1091     return 64;
1092   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
1093     return 32;
1094 
1095   if ((AddrSpace == AMDGPUAS::PARAM_D_ADDRESS ||
1096       AddrSpace == AMDGPUAS::PARAM_I_ADDRESS ||
1097       (AddrSpace >= AMDGPUAS::CONSTANT_BUFFER_0 &&
1098       AddrSpace <= AMDGPUAS::CONSTANT_BUFFER_15)))
1099     return 128;
1100   llvm_unreachable("unhandled address space");
1101 }
1102 
1103 bool R600TTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
1104                                              unsigned Alignment,
1105                                              unsigned AddrSpace) const {
1106   // We allow vectorization of flat stores, even though we may need to decompose
1107   // them later if they may access private memory. We don't have enough context
1108   // here, and legalization can handle it.
1109   return (AddrSpace != AMDGPUAS::PRIVATE_ADDRESS);
1110 }
1111 
1112 bool R600TTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
1113                                               unsigned Alignment,
1114                                               unsigned AddrSpace) const {
1115   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1116 }
1117 
1118 bool R600TTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
1119                                                unsigned Alignment,
1120                                                unsigned AddrSpace) const {
1121   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
1122 }
1123 
1124 unsigned R600TTIImpl::getMaxInterleaveFactor(unsigned VF) {
1125   // Disable unrolling if the loop is not vectorized.
1126   // TODO: Enable this again.
1127   if (VF == 1)
1128     return 1;
1129 
1130   return 8;
1131 }
1132 
1133 unsigned R600TTIImpl::getCFInstrCost(unsigned Opcode,
1134                                      TTI::TargetCostKind CostKind) {
1135   // XXX - For some reason this isn't called for switch.
1136   switch (Opcode) {
1137   case Instruction::Br:
1138   case Instruction::Ret:
1139     return 10;
1140   default:
1141     return BaseT::getCFInstrCost(Opcode, CostKind);
1142   }
1143 }
1144 
1145 int R600TTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
1146                                     unsigned Index) {
1147   switch (Opcode) {
1148   case Instruction::ExtractElement:
1149   case Instruction::InsertElement: {
1150     unsigned EltSize
1151       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
1152     if (EltSize < 32) {
1153       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1154     }
1155 
1156     // Extracts are just reads of a subregister, so are free. Inserts are
1157     // considered free because we don't want to have any cost for scalarizing
1158     // operations, and we don't have to copy into a different register class.
1159 
1160     // Dynamic indexing isn't free and is best avoided.
1161     return Index == ~0u ? 2 : 0;
1162   }
1163   default:
1164     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
1165   }
1166 }
1167 
1168 void R600TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1169                                           TTI::UnrollingPreferences &UP) {
1170   CommonTTI.getUnrollingPreferences(L, SE, UP);
1171 }
1172