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