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 "AMDGPUTargetMachine.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/IntrinsicsAMDGPU.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/Support/KnownBits.h"
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "AMDGPUtti"
30 
31 static cl::opt<unsigned> UnrollThresholdPrivate(
32   "amdgpu-unroll-threshold-private",
33   cl::desc("Unroll threshold for AMDGPU if private memory used in a loop"),
34   cl::init(2700), cl::Hidden);
35 
36 static cl::opt<unsigned> UnrollThresholdLocal(
37   "amdgpu-unroll-threshold-local",
38   cl::desc("Unroll threshold for AMDGPU if local memory used in a loop"),
39   cl::init(1000), cl::Hidden);
40 
41 static cl::opt<unsigned> UnrollThresholdIf(
42   "amdgpu-unroll-threshold-if",
43   cl::desc("Unroll threshold increment for AMDGPU for each if statement inside loop"),
44   cl::init(200), cl::Hidden);
45 
46 static cl::opt<bool> UnrollRuntimeLocal(
47   "amdgpu-unroll-runtime-local",
48   cl::desc("Allow runtime unroll for AMDGPU if local memory used in a loop"),
49   cl::init(true), cl::Hidden);
50 
51 static cl::opt<bool> UseLegacyDA(
52   "amdgpu-use-legacy-divergence-analysis",
53   cl::desc("Enable legacy divergence analysis for AMDGPU"),
54   cl::init(false), cl::Hidden);
55 
56 static cl::opt<unsigned> UnrollMaxBlockToAnalyze(
57     "amdgpu-unroll-max-block-to-analyze",
58     cl::desc("Inner loop block size threshold to analyze in unroll for AMDGPU"),
59     cl::init(32), cl::Hidden);
60 
61 static cl::opt<unsigned> ArgAllocaCost("amdgpu-inline-arg-alloca-cost",
62                                        cl::Hidden, cl::init(4000),
63                                        cl::desc("Cost of alloca argument"));
64 
65 // If the amount of scratch memory to eliminate exceeds our ability to allocate
66 // it into registers we gain nothing by aggressively inlining functions for that
67 // heuristic.
68 static cl::opt<unsigned>
69     ArgAllocaCutoff("amdgpu-inline-arg-alloca-cutoff", cl::Hidden,
70                     cl::init(256),
71                     cl::desc("Maximum alloca size to use for inline cost"));
72 
73 // Inliner constraint to achieve reasonable compilation time.
74 static cl::opt<size_t> InlineMaxBB(
75     "amdgpu-inline-max-bb", cl::Hidden, cl::init(1100),
76     cl::desc("Maximum number of BBs allowed in a function after inlining"
77              " (compile time constraint)"));
78 
79 static bool dependsOnLocalPhi(const Loop *L, const Value *Cond,
80                               unsigned Depth = 0) {
81   const Instruction *I = dyn_cast<Instruction>(Cond);
82   if (!I)
83     return false;
84 
85   for (const Value *V : I->operand_values()) {
86     if (!L->contains(I))
87       continue;
88     if (const PHINode *PHI = dyn_cast<PHINode>(V)) {
89       if (llvm::none_of(L->getSubLoops(), [PHI](const Loop* SubLoop) {
90                   return SubLoop->contains(PHI); }))
91         return true;
92     } else if (Depth < 10 && dependsOnLocalPhi(L, V, Depth+1))
93       return true;
94   }
95   return false;
96 }
97 
98 AMDGPUTTIImpl::AMDGPUTTIImpl(const AMDGPUTargetMachine *TM, const Function &F)
99     : BaseT(TM, F.getParent()->getDataLayout()),
100       TargetTriple(TM->getTargetTriple()),
101       ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))),
102       TLI(ST->getTargetLowering()) {}
103 
104 void AMDGPUTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
105                                             TTI::UnrollingPreferences &UP,
106                                             OptimizationRemarkEmitter *ORE) {
107   const Function &F = *L->getHeader()->getParent();
108   UP.Threshold = AMDGPU::getIntegerAttribute(F, "amdgpu-unroll-threshold", 300);
109   UP.MaxCount = std::numeric_limits<unsigned>::max();
110   UP.Partial = true;
111 
112   // Conditional branch in a loop back edge needs 3 additional exec
113   // manipulations in average.
114   UP.BEInsns += 3;
115 
116   // TODO: Do we want runtime unrolling?
117 
118   // Maximum alloca size than can fit registers. Reserve 16 registers.
119   const unsigned MaxAlloca = (256 - 16) * 4;
120   unsigned ThresholdPrivate = UnrollThresholdPrivate;
121   unsigned ThresholdLocal = UnrollThresholdLocal;
122 
123   // If this loop has the amdgpu.loop.unroll.threshold metadata we will use the
124   // provided threshold value as the default for Threshold
125   if (MDNode *LoopUnrollThreshold =
126           findOptionMDForLoop(L, "amdgpu.loop.unroll.threshold")) {
127     if (LoopUnrollThreshold->getNumOperands() == 2) {
128       ConstantInt *MetaThresholdValue = mdconst::extract_or_null<ConstantInt>(
129           LoopUnrollThreshold->getOperand(1));
130       if (MetaThresholdValue) {
131         // We will also use the supplied value for PartialThreshold for now.
132         // We may introduce additional metadata if it becomes necessary in the
133         // future.
134         UP.Threshold = MetaThresholdValue->getSExtValue();
135         UP.PartialThreshold = UP.Threshold;
136         ThresholdPrivate = std::min(ThresholdPrivate, UP.Threshold);
137         ThresholdLocal = std::min(ThresholdLocal, UP.Threshold);
138       }
139     }
140   }
141 
142   unsigned MaxBoost = std::max(ThresholdPrivate, ThresholdLocal);
143   for (const BasicBlock *BB : L->getBlocks()) {
144     const DataLayout &DL = BB->getModule()->getDataLayout();
145     unsigned LocalGEPsSeen = 0;
146 
147     if (llvm::any_of(L->getSubLoops(), [BB](const Loop* SubLoop) {
148                return SubLoop->contains(BB); }))
149         continue; // Block belongs to an inner loop.
150 
151     for (const Instruction &I : *BB) {
152       // Unroll a loop which contains an "if" statement whose condition
153       // defined by a PHI belonging to the loop. This may help to eliminate
154       // if region and potentially even PHI itself, saving on both divergence
155       // and registers used for the PHI.
156       // Add a small bonus for each of such "if" statements.
157       if (const BranchInst *Br = dyn_cast<BranchInst>(&I)) {
158         if (UP.Threshold < MaxBoost && Br->isConditional()) {
159           BasicBlock *Succ0 = Br->getSuccessor(0);
160           BasicBlock *Succ1 = Br->getSuccessor(1);
161           if ((L->contains(Succ0) && L->isLoopExiting(Succ0)) ||
162               (L->contains(Succ1) && L->isLoopExiting(Succ1)))
163             continue;
164           if (dependsOnLocalPhi(L, Br->getCondition())) {
165             UP.Threshold += UnrollThresholdIf;
166             LLVM_DEBUG(dbgs() << "Set unroll threshold " << UP.Threshold
167                               << " for loop:\n"
168                               << *L << " due to " << *Br << '\n');
169             if (UP.Threshold >= MaxBoost)
170               return;
171           }
172         }
173         continue;
174       }
175 
176       const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I);
177       if (!GEP)
178         continue;
179 
180       unsigned AS = GEP->getAddressSpace();
181       unsigned Threshold = 0;
182       if (AS == AMDGPUAS::PRIVATE_ADDRESS)
183         Threshold = ThresholdPrivate;
184       else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS)
185         Threshold = ThresholdLocal;
186       else
187         continue;
188 
189       if (UP.Threshold >= Threshold)
190         continue;
191 
192       if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
193         const Value *Ptr = GEP->getPointerOperand();
194         const AllocaInst *Alloca =
195             dyn_cast<AllocaInst>(getUnderlyingObject(Ptr));
196         if (!Alloca || !Alloca->isStaticAlloca())
197           continue;
198         Type *Ty = Alloca->getAllocatedType();
199         unsigned AllocaSize = Ty->isSized() ? DL.getTypeAllocSize(Ty) : 0;
200         if (AllocaSize > MaxAlloca)
201           continue;
202       } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
203                  AS == AMDGPUAS::REGION_ADDRESS) {
204         LocalGEPsSeen++;
205         // Inhibit unroll for local memory if we have seen addressing not to
206         // a variable, most likely we will be unable to combine it.
207         // Do not unroll too deep inner loops for local memory to give a chance
208         // to unroll an outer loop for a more important reason.
209         if (LocalGEPsSeen > 1 || L->getLoopDepth() > 2 ||
210             (!isa<GlobalVariable>(GEP->getPointerOperand()) &&
211              !isa<Argument>(GEP->getPointerOperand())))
212           continue;
213         LLVM_DEBUG(dbgs() << "Allow unroll runtime for loop:\n"
214                           << *L << " due to LDS use.\n");
215         UP.Runtime = UnrollRuntimeLocal;
216       }
217 
218       // Check if GEP depends on a value defined by this loop itself.
219       bool HasLoopDef = false;
220       for (const Value *Op : GEP->operands()) {
221         const Instruction *Inst = dyn_cast<Instruction>(Op);
222         if (!Inst || L->isLoopInvariant(Op))
223           continue;
224 
225         if (llvm::any_of(L->getSubLoops(), [Inst](const Loop* SubLoop) {
226              return SubLoop->contains(Inst); }))
227           continue;
228         HasLoopDef = true;
229         break;
230       }
231       if (!HasLoopDef)
232         continue;
233 
234       // We want to do whatever we can to limit the number of alloca
235       // instructions that make it through to the code generator.  allocas
236       // require us to use indirect addressing, which is slow and prone to
237       // compiler bugs.  If this loop does an address calculation on an
238       // alloca ptr, then we want to use a higher than normal loop unroll
239       // threshold. This will give SROA a better chance to eliminate these
240       // allocas.
241       //
242       // We also want to have more unrolling for local memory to let ds
243       // instructions with different offsets combine.
244       //
245       // Don't use the maximum allowed value here as it will make some
246       // programs way too big.
247       UP.Threshold = Threshold;
248       LLVM_DEBUG(dbgs() << "Set unroll threshold " << Threshold
249                         << " for loop:\n"
250                         << *L << " due to " << *GEP << '\n');
251       if (UP.Threshold >= MaxBoost)
252         return;
253     }
254 
255     // If we got a GEP in a small BB from inner loop then increase max trip
256     // count to analyze for better estimation cost in unroll
257     if (L->isInnermost() && BB->size() < UnrollMaxBlockToAnalyze)
258       UP.MaxIterationsCountToAnalyze = 32;
259   }
260 }
261 
262 void AMDGPUTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
263                                           TTI::PeelingPreferences &PP) {
264   BaseT::getPeelingPreferences(L, SE, PP);
265 }
266 
267 const FeatureBitset GCNTTIImpl::InlineFeatureIgnoreList = {
268     // Codegen control options which don't matter.
269     AMDGPU::FeatureEnableLoadStoreOpt, AMDGPU::FeatureEnableSIScheduler,
270     AMDGPU::FeatureEnableUnsafeDSOffsetFolding, AMDGPU::FeatureFlatForGlobal,
271     AMDGPU::FeaturePromoteAlloca, AMDGPU::FeatureUnalignedScratchAccess,
272     AMDGPU::FeatureUnalignedAccessMode,
273 
274     AMDGPU::FeatureAutoWaitcntBeforeBarrier,
275 
276     // Property of the kernel/environment which can't actually differ.
277     AMDGPU::FeatureSGPRInitBug, AMDGPU::FeatureXNACK,
278     AMDGPU::FeatureTrapHandler,
279 
280     // The default assumption needs to be ecc is enabled, but no directly
281     // exposed operations depend on it, so it can be safely inlined.
282     AMDGPU::FeatureSRAMECC,
283 
284     // Perf-tuning features
285     AMDGPU::FeatureFastFMAF32, AMDGPU::HalfRate64Ops};
286 
287 GCNTTIImpl::GCNTTIImpl(const AMDGPUTargetMachine *TM, const Function &F)
288     : BaseT(TM, F.getParent()->getDataLayout()),
289       ST(static_cast<const GCNSubtarget *>(TM->getSubtargetImpl(F))),
290       TLI(ST->getTargetLowering()), CommonTTI(TM, F),
291       IsGraphics(AMDGPU::isGraphics(F.getCallingConv())),
292       MaxVGPRs(ST->getMaxNumVGPRs(
293           std::max(ST->getWavesPerEU(F).first,
294                    ST->getWavesPerEUForWorkGroup(
295                        ST->getFlatWorkGroupSizes(F).second)))) {
296   AMDGPU::SIModeRegisterDefaults Mode(F);
297   HasFP32Denormals = Mode.allFP32Denormals();
298   HasFP64FP16Denormals = Mode.allFP64FP16Denormals();
299 }
300 
301 unsigned GCNTTIImpl::getHardwareNumberOfRegisters(bool Vec) const {
302   // The concept of vector registers doesn't really exist. Some packed vector
303   // operations operate on the normal 32-bit registers.
304   return MaxVGPRs;
305 }
306 
307 unsigned GCNTTIImpl::getNumberOfRegisters(bool Vec) const {
308   // This is really the number of registers to fill when vectorizing /
309   // interleaving loops, so we lie to avoid trying to use all registers.
310   return getHardwareNumberOfRegisters(Vec) >> 3;
311 }
312 
313 unsigned GCNTTIImpl::getNumberOfRegisters(unsigned RCID) const {
314   const SIRegisterInfo *TRI = ST->getRegisterInfo();
315   const TargetRegisterClass *RC = TRI->getRegClass(RCID);
316   unsigned NumVGPRs = (TRI->getRegSizeInBits(*RC) + 31) / 32;
317   return getHardwareNumberOfRegisters(false) / NumVGPRs;
318 }
319 
320 TypeSize
321 GCNTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
322   switch (K) {
323   case TargetTransformInfo::RGK_Scalar:
324     return TypeSize::getFixed(32);
325   case TargetTransformInfo::RGK_FixedWidthVector:
326     return TypeSize::getFixed(ST->hasPackedFP32Ops() ? 64 : 32);
327   case TargetTransformInfo::RGK_ScalableVector:
328     return TypeSize::getScalable(0);
329   }
330   llvm_unreachable("Unsupported register kind");
331 }
332 
333 unsigned GCNTTIImpl::getMinVectorRegisterBitWidth() const {
334   return 32;
335 }
336 
337 unsigned GCNTTIImpl::getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
338   if (Opcode == Instruction::Load || Opcode == Instruction::Store)
339     return 32 * 4 / ElemWidth;
340   return (ElemWidth == 16 && ST->has16BitInsts()) ? 2
341        : (ElemWidth == 32 && ST->hasPackedFP32Ops()) ? 2
342        : 1;
343 }
344 
345 unsigned GCNTTIImpl::getLoadVectorFactor(unsigned VF, unsigned LoadSize,
346                                          unsigned ChainSizeInBytes,
347                                          VectorType *VecTy) const {
348   unsigned VecRegBitWidth = VF * LoadSize;
349   if (VecRegBitWidth > 128 && VecTy->getScalarSizeInBits() < 32)
350     // TODO: Support element-size less than 32bit?
351     return 128 / LoadSize;
352 
353   return VF;
354 }
355 
356 unsigned GCNTTIImpl::getStoreVectorFactor(unsigned VF, unsigned StoreSize,
357                                              unsigned ChainSizeInBytes,
358                                              VectorType *VecTy) const {
359   unsigned VecRegBitWidth = VF * StoreSize;
360   if (VecRegBitWidth > 128)
361     return 128 / StoreSize;
362 
363   return VF;
364 }
365 
366 unsigned GCNTTIImpl::getLoadStoreVecRegBitWidth(unsigned AddrSpace) const {
367   if (AddrSpace == AMDGPUAS::GLOBAL_ADDRESS ||
368       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
369       AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
370       AddrSpace == AMDGPUAS::BUFFER_FAT_POINTER) {
371     return 512;
372   }
373 
374   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS)
375     return 8 * ST->getMaxPrivateElementSize();
376 
377   // Common to flat, global, local and region. Assume for unknown addrspace.
378   return 128;
379 }
380 
381 bool GCNTTIImpl::isLegalToVectorizeMemChain(unsigned ChainSizeInBytes,
382                                             Align Alignment,
383                                             unsigned AddrSpace) const {
384   // We allow vectorization of flat stores, even though we may need to decompose
385   // them later if they may access private memory. We don't have enough context
386   // here, and legalization can handle it.
387   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
388     return (Alignment >= 4 || ST->hasUnalignedScratchAccess()) &&
389       ChainSizeInBytes <= ST->getMaxPrivateElementSize();
390   }
391   return true;
392 }
393 
394 bool GCNTTIImpl::isLegalToVectorizeLoadChain(unsigned ChainSizeInBytes,
395                                              Align Alignment,
396                                              unsigned AddrSpace) const {
397   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
398 }
399 
400 bool GCNTTIImpl::isLegalToVectorizeStoreChain(unsigned ChainSizeInBytes,
401                                               Align Alignment,
402                                               unsigned AddrSpace) const {
403   return isLegalToVectorizeMemChain(ChainSizeInBytes, Alignment, AddrSpace);
404 }
405 
406 // FIXME: Really we would like to issue multiple 128-bit loads and stores per
407 // iteration. Should we report a larger size and let it legalize?
408 //
409 // FIXME: Should we use narrower types for local/region, or account for when
410 // unaligned access is legal?
411 //
412 // FIXME: This could use fine tuning and microbenchmarks.
413 Type *GCNTTIImpl::getMemcpyLoopLoweringType(
414     LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
415     unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign,
416     Optional<uint32_t> AtomicElementSize) const {
417 
418   if (AtomicElementSize)
419     return Type::getIntNTy(Context, *AtomicElementSize * 8);
420 
421   unsigned MinAlign = std::min(SrcAlign, DestAlign);
422 
423   // A (multi-)dword access at an address == 2 (mod 4) will be decomposed by the
424   // hardware into byte accesses. If you assume all alignments are equally
425   // probable, it's more efficient on average to use short accesses for this
426   // case.
427   if (MinAlign == 2)
428     return Type::getInt16Ty(Context);
429 
430   // Not all subtargets have 128-bit DS instructions, and we currently don't
431   // form them by default.
432   if (SrcAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
433       SrcAddrSpace == AMDGPUAS::REGION_ADDRESS ||
434       DestAddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
435       DestAddrSpace == AMDGPUAS::REGION_ADDRESS) {
436     return FixedVectorType::get(Type::getInt32Ty(Context), 2);
437   }
438 
439   // Global memory works best with 16-byte accesses. Private memory will also
440   // hit this, although they'll be decomposed.
441   return FixedVectorType::get(Type::getInt32Ty(Context), 4);
442 }
443 
444 void GCNTTIImpl::getMemcpyLoopResidualLoweringType(
445     SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
446     unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
447     unsigned SrcAlign, unsigned DestAlign,
448     Optional<uint32_t> AtomicCpySize) const {
449   assert(RemainingBytes < 16);
450 
451   if (AtomicCpySize)
452     BaseT::getMemcpyLoopResidualLoweringType(
453         OpsOut, Context, RemainingBytes, SrcAddrSpace, DestAddrSpace, SrcAlign,
454         DestAlign, AtomicCpySize);
455 
456   unsigned MinAlign = std::min(SrcAlign, DestAlign);
457 
458   if (MinAlign != 2) {
459     Type *I64Ty = Type::getInt64Ty(Context);
460     while (RemainingBytes >= 8) {
461       OpsOut.push_back(I64Ty);
462       RemainingBytes -= 8;
463     }
464 
465     Type *I32Ty = Type::getInt32Ty(Context);
466     while (RemainingBytes >= 4) {
467       OpsOut.push_back(I32Ty);
468       RemainingBytes -= 4;
469     }
470   }
471 
472   Type *I16Ty = Type::getInt16Ty(Context);
473   while (RemainingBytes >= 2) {
474     OpsOut.push_back(I16Ty);
475     RemainingBytes -= 2;
476   }
477 
478   Type *I8Ty = Type::getInt8Ty(Context);
479   while (RemainingBytes) {
480     OpsOut.push_back(I8Ty);
481     --RemainingBytes;
482   }
483 }
484 
485 unsigned GCNTTIImpl::getMaxInterleaveFactor(unsigned VF) {
486   // Disable unrolling if the loop is not vectorized.
487   // TODO: Enable this again.
488   if (VF == 1)
489     return 1;
490 
491   return 8;
492 }
493 
494 bool GCNTTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
495                                        MemIntrinsicInfo &Info) const {
496   switch (Inst->getIntrinsicID()) {
497   case Intrinsic::amdgcn_atomic_inc:
498   case Intrinsic::amdgcn_atomic_dec:
499   case Intrinsic::amdgcn_ds_ordered_add:
500   case Intrinsic::amdgcn_ds_ordered_swap:
501   case Intrinsic::amdgcn_ds_fadd:
502   case Intrinsic::amdgcn_ds_fmin:
503   case Intrinsic::amdgcn_ds_fmax: {
504     auto *Ordering = dyn_cast<ConstantInt>(Inst->getArgOperand(2));
505     auto *Volatile = dyn_cast<ConstantInt>(Inst->getArgOperand(4));
506     if (!Ordering || !Volatile)
507       return false; // Invalid.
508 
509     unsigned OrderingVal = Ordering->getZExtValue();
510     if (OrderingVal > static_cast<unsigned>(AtomicOrdering::SequentiallyConsistent))
511       return false;
512 
513     Info.PtrVal = Inst->getArgOperand(0);
514     Info.Ordering = static_cast<AtomicOrdering>(OrderingVal);
515     Info.ReadMem = true;
516     Info.WriteMem = true;
517     Info.IsVolatile = !Volatile->isZero();
518     return true;
519   }
520   default:
521     return false;
522   }
523 }
524 
525 InstructionCost GCNTTIImpl::getArithmeticInstrCost(
526     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
527     TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
528     TTI::OperandValueProperties Opd1PropInfo,
529     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
530     const Instruction *CxtI) {
531 
532   // Legalize the type.
533   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
534   int ISD = TLI->InstructionOpcodeToISD(Opcode);
535 
536   // Because we don't have any legal vector operations, but the legal types, we
537   // need to account for split vectors.
538   unsigned NElts = LT.second.isVector() ?
539     LT.second.getVectorNumElements() : 1;
540 
541   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
542 
543   switch (ISD) {
544   case ISD::SHL:
545   case ISD::SRL:
546   case ISD::SRA:
547     if (SLT == MVT::i64)
548       return get64BitInstrCost(CostKind) * LT.first * NElts;
549 
550     if (ST->has16BitInsts() && SLT == MVT::i16)
551       NElts = (NElts + 1) / 2;
552 
553     // i32
554     return getFullRateInstrCost() * LT.first * NElts;
555   case ISD::ADD:
556   case ISD::SUB:
557   case ISD::AND:
558   case ISD::OR:
559   case ISD::XOR:
560     if (SLT == MVT::i64) {
561       // and, or and xor are typically split into 2 VALU instructions.
562       return 2 * getFullRateInstrCost() * LT.first * NElts;
563     }
564 
565     if (ST->has16BitInsts() && SLT == MVT::i16)
566       NElts = (NElts + 1) / 2;
567 
568     return LT.first * NElts * getFullRateInstrCost();
569   case ISD::MUL: {
570     const int QuarterRateCost = getQuarterRateInstrCost(CostKind);
571     if (SLT == MVT::i64) {
572       const int FullRateCost = getFullRateInstrCost();
573       return (4 * QuarterRateCost + (2 * 2) * FullRateCost) * LT.first * NElts;
574     }
575 
576     if (ST->has16BitInsts() && SLT == MVT::i16)
577       NElts = (NElts + 1) / 2;
578 
579     // i32
580     return QuarterRateCost * NElts * LT.first;
581   }
582   case ISD::FMUL:
583     // Check possible fuse {fadd|fsub}(a,fmul(b,c)) and return zero cost for
584     // fmul(b,c) supposing the fadd|fsub will get estimated cost for the whole
585     // fused operation.
586     if (CxtI && CxtI->hasOneUse())
587       if (const auto *FAdd = dyn_cast<BinaryOperator>(*CxtI->user_begin())) {
588         const int OPC = TLI->InstructionOpcodeToISD(FAdd->getOpcode());
589         if (OPC == ISD::FADD || OPC == ISD::FSUB) {
590           if (ST->hasMadMacF32Insts() && SLT == MVT::f32 && !HasFP32Denormals)
591             return TargetTransformInfo::TCC_Free;
592           if (ST->has16BitInsts() && SLT == MVT::f16 && !HasFP64FP16Denormals)
593             return TargetTransformInfo::TCC_Free;
594 
595           // Estimate all types may be fused with contract/unsafe flags
596           const TargetOptions &Options = TLI->getTargetMachine().Options;
597           if (Options.AllowFPOpFusion == FPOpFusion::Fast ||
598               Options.UnsafeFPMath ||
599               (FAdd->hasAllowContract() && CxtI->hasAllowContract()))
600             return TargetTransformInfo::TCC_Free;
601         }
602       }
603     LLVM_FALLTHROUGH;
604   case ISD::FADD:
605   case ISD::FSUB:
606     if (ST->hasPackedFP32Ops() && SLT == MVT::f32)
607       NElts = (NElts + 1) / 2;
608     if (SLT == MVT::f64)
609       return LT.first * NElts * get64BitInstrCost(CostKind);
610 
611     if (ST->has16BitInsts() && SLT == MVT::f16)
612       NElts = (NElts + 1) / 2;
613 
614     if (SLT == MVT::f32 || SLT == MVT::f16)
615       return LT.first * NElts * getFullRateInstrCost();
616     break;
617   case ISD::FDIV:
618   case ISD::FREM:
619     // FIXME: frem should be handled separately. The fdiv in it is most of it,
620     // but the current lowering is also not entirely correct.
621     if (SLT == MVT::f64) {
622       int Cost = 7 * get64BitInstrCost(CostKind) +
623                  getQuarterRateInstrCost(CostKind) +
624                  3 * getHalfRateInstrCost(CostKind);
625       // Add cost of workaround.
626       if (!ST->hasUsableDivScaleConditionOutput())
627         Cost += 3 * getFullRateInstrCost();
628 
629       return LT.first * Cost * NElts;
630     }
631 
632     if (!Args.empty() && match(Args[0], PatternMatch::m_FPOne())) {
633       // TODO: This is more complicated, unsafe flags etc.
634       if ((SLT == MVT::f32 && !HasFP32Denormals) ||
635           (SLT == MVT::f16 && ST->has16BitInsts())) {
636         return LT.first * getQuarterRateInstrCost(CostKind) * NElts;
637       }
638     }
639 
640     if (SLT == MVT::f16 && ST->has16BitInsts()) {
641       // 2 x v_cvt_f32_f16
642       // f32 rcp
643       // f32 fmul
644       // v_cvt_f16_f32
645       // f16 div_fixup
646       int Cost =
647           4 * getFullRateInstrCost() + 2 * getQuarterRateInstrCost(CostKind);
648       return LT.first * Cost * NElts;
649     }
650 
651     if (SLT == MVT::f32 || SLT == MVT::f16) {
652       // 4 more v_cvt_* insts without f16 insts support
653       int Cost = (SLT == MVT::f16 ? 14 : 10) * getFullRateInstrCost() +
654                  1 * getQuarterRateInstrCost(CostKind);
655 
656       if (!HasFP32Denormals) {
657         // FP mode switches.
658         Cost += 2 * getFullRateInstrCost();
659       }
660 
661       return LT.first * NElts * Cost;
662     }
663     break;
664   case ISD::FNEG:
665     // Use the backend' estimation. If fneg is not free each element will cost
666     // one additional instruction.
667     return TLI->isFNegFree(SLT) ? 0 : NElts;
668   default:
669     break;
670   }
671 
672   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
673                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
674 }
675 
676 // Return true if there's a potential benefit from using v2f16/v2i16
677 // instructions for an intrinsic, even if it requires nontrivial legalization.
678 static bool intrinsicHasPackedVectorBenefit(Intrinsic::ID ID) {
679   switch (ID) {
680   case Intrinsic::fma: // TODO: fmuladd
681   // There's a small benefit to using vector ops in the legalized code.
682   case Intrinsic::round:
683   case Intrinsic::uadd_sat:
684   case Intrinsic::usub_sat:
685   case Intrinsic::sadd_sat:
686   case Intrinsic::ssub_sat:
687     return true;
688   default:
689     return false;
690   }
691 }
692 
693 InstructionCost
694 GCNTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
695                                   TTI::TargetCostKind CostKind) {
696   if (ICA.getID() == Intrinsic::fabs)
697     return 0;
698 
699   if (!intrinsicHasPackedVectorBenefit(ICA.getID()))
700     return BaseT::getIntrinsicInstrCost(ICA, CostKind);
701 
702   Type *RetTy = ICA.getReturnType();
703 
704   // Legalize the type.
705   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
706 
707   unsigned NElts = LT.second.isVector() ?
708     LT.second.getVectorNumElements() : 1;
709 
710   MVT::SimpleValueType SLT = LT.second.getScalarType().SimpleTy;
711 
712   if (SLT == MVT::f64)
713     return LT.first * NElts * get64BitInstrCost(CostKind);
714 
715   if ((ST->has16BitInsts() && SLT == MVT::f16) ||
716       (ST->hasPackedFP32Ops() && SLT == MVT::f32))
717     NElts = (NElts + 1) / 2;
718 
719   // TODO: Get more refined intrinsic costs?
720   unsigned InstRate = getQuarterRateInstrCost(CostKind);
721 
722   switch (ICA.getID()) {
723   case Intrinsic::fma:
724     InstRate = ST->hasFastFMAF32() ? getHalfRateInstrCost(CostKind)
725                                    : getQuarterRateInstrCost(CostKind);
726     break;
727   case Intrinsic::uadd_sat:
728   case Intrinsic::usub_sat:
729   case Intrinsic::sadd_sat:
730   case Intrinsic::ssub_sat:
731     static const auto ValidSatTys = {MVT::v2i16, MVT::v4i16};
732     if (any_of(ValidSatTys, [&LT](MVT M) { return M == LT.second; }))
733       NElts = 1;
734     break;
735   }
736 
737   return LT.first * NElts * InstRate;
738 }
739 
740 InstructionCost GCNTTIImpl::getCFInstrCost(unsigned Opcode,
741                                            TTI::TargetCostKind CostKind,
742                                            const Instruction *I) {
743   assert((I == nullptr || I->getOpcode() == Opcode) &&
744          "Opcode should reflect passed instruction.");
745   const bool SCost =
746       (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency);
747   const int CBrCost = SCost ? 5 : 7;
748   switch (Opcode) {
749   case Instruction::Br: {
750     // Branch instruction takes about 4 slots on gfx900.
751     auto BI = dyn_cast_or_null<BranchInst>(I);
752     if (BI && BI->isUnconditional())
753       return SCost ? 1 : 4;
754     // Suppose conditional branch takes additional 3 exec manipulations
755     // instructions in average.
756     return CBrCost;
757   }
758   case Instruction::Switch: {
759     auto SI = dyn_cast_or_null<SwitchInst>(I);
760     // Each case (including default) takes 1 cmp + 1 cbr instructions in
761     // average.
762     return (SI ? (SI->getNumCases() + 1) : 4) * (CBrCost + 1);
763   }
764   case Instruction::Ret:
765     return SCost ? 1 : 10;
766   }
767   return BaseT::getCFInstrCost(Opcode, CostKind, I);
768 }
769 
770 InstructionCost
771 GCNTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
772                                        Optional<FastMathFlags> FMF,
773                                        TTI::TargetCostKind CostKind) {
774   if (TTI::requiresOrderedReduction(FMF))
775     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
776 
777   EVT OrigTy = TLI->getValueType(DL, Ty);
778 
779   // Computes cost on targets that have packed math instructions(which support
780   // 16-bit types only).
781   if (!ST->hasVOP3PInsts() || OrigTy.getScalarSizeInBits() != 16)
782     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
783 
784   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
785   return LT.first * getFullRateInstrCost();
786 }
787 
788 InstructionCost
789 GCNTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
790                                    bool IsUnsigned,
791                                    TTI::TargetCostKind CostKind) {
792   EVT OrigTy = TLI->getValueType(DL, Ty);
793 
794   // Computes cost on targets that have packed math instructions(which support
795   // 16-bit types only).
796   if (!ST->hasVOP3PInsts() || OrigTy.getScalarSizeInBits() != 16)
797     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
798 
799   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
800   return LT.first * getHalfRateInstrCost(CostKind);
801 }
802 
803 InstructionCost GCNTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
804                                                unsigned Index) {
805   switch (Opcode) {
806   case Instruction::ExtractElement:
807   case Instruction::InsertElement: {
808     unsigned EltSize
809       = DL.getTypeSizeInBits(cast<VectorType>(ValTy)->getElementType());
810     if (EltSize < 32) {
811       if (EltSize == 16 && Index == 0 && ST->has16BitInsts())
812         return 0;
813       return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
814     }
815 
816     // Extracts are just reads of a subregister, so are free. Inserts are
817     // considered free because we don't want to have any cost for scalarizing
818     // operations, and we don't have to copy into a different register class.
819 
820     // Dynamic indexing isn't free and is best avoided.
821     return Index == ~0u ? 2 : 0;
822   }
823   default:
824     return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
825   }
826 }
827 
828 /// Analyze if the results of inline asm are divergent. If \p Indices is empty,
829 /// this is analyzing the collective result of all output registers. Otherwise,
830 /// this is only querying a specific result index if this returns multiple
831 /// registers in a struct.
832 bool GCNTTIImpl::isInlineAsmSourceOfDivergence(
833   const CallInst *CI, ArrayRef<unsigned> Indices) const {
834   // TODO: Handle complex extract indices
835   if (Indices.size() > 1)
836     return true;
837 
838   const DataLayout &DL = CI->getModule()->getDataLayout();
839   const SIRegisterInfo *TRI = ST->getRegisterInfo();
840   TargetLowering::AsmOperandInfoVector TargetConstraints =
841       TLI->ParseConstraints(DL, ST->getRegisterInfo(), *CI);
842 
843   const int TargetOutputIdx = Indices.empty() ? -1 : Indices[0];
844 
845   int OutputIdx = 0;
846   for (auto &TC : TargetConstraints) {
847     if (TC.Type != InlineAsm::isOutput)
848       continue;
849 
850     // Skip outputs we don't care about.
851     if (TargetOutputIdx != -1 && TargetOutputIdx != OutputIdx++)
852       continue;
853 
854     TLI->ComputeConstraintToUse(TC, SDValue());
855 
856     const TargetRegisterClass *RC = TLI->getRegForInlineAsmConstraint(
857         TRI, TC.ConstraintCode, TC.ConstraintVT).second;
858 
859     // For AGPR constraints null is returned on subtargets without AGPRs, so
860     // assume divergent for null.
861     if (!RC || !TRI->isSGPRClass(RC))
862       return true;
863   }
864 
865   return false;
866 }
867 
868 /// \returns true if the new GPU divergence analysis is enabled.
869 bool GCNTTIImpl::useGPUDivergenceAnalysis() const {
870   return !UseLegacyDA;
871 }
872 
873 /// \returns true if the result of the value could potentially be
874 /// different across workitems in a wavefront.
875 bool GCNTTIImpl::isSourceOfDivergence(const Value *V) const {
876   if (const Argument *A = dyn_cast<Argument>(V))
877     return !AMDGPU::isArgPassedInSGPR(A);
878 
879   // Loads from the private and flat address spaces are divergent, because
880   // threads can execute the load instruction with the same inputs and get
881   // different results.
882   //
883   // All other loads are not divergent, because if threads issue loads with the
884   // same arguments, they will always get the same result.
885   if (const LoadInst *Load = dyn_cast<LoadInst>(V))
886     return Load->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS ||
887            Load->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS;
888 
889   // Atomics are divergent because they are executed sequentially: when an
890   // atomic operation refers to the same address in each thread, then each
891   // thread after the first sees the value written by the previous thread as
892   // original value.
893   if (isa<AtomicRMWInst>(V) || isa<AtomicCmpXchgInst>(V))
894     return true;
895 
896   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V))
897     return AMDGPU::isIntrinsicSourceOfDivergence(Intrinsic->getIntrinsicID());
898 
899   // Assume all function calls are a source of divergence.
900   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
901     if (CI->isInlineAsm())
902       return isInlineAsmSourceOfDivergence(CI);
903     return true;
904   }
905 
906   // Assume all function calls are a source of divergence.
907   if (isa<InvokeInst>(V))
908     return true;
909 
910   return false;
911 }
912 
913 bool GCNTTIImpl::isAlwaysUniform(const Value *V) const {
914   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
915     switch (Intrinsic->getIntrinsicID()) {
916     default:
917       return false;
918     case Intrinsic::amdgcn_readfirstlane:
919     case Intrinsic::amdgcn_readlane:
920     case Intrinsic::amdgcn_icmp:
921     case Intrinsic::amdgcn_fcmp:
922     case Intrinsic::amdgcn_ballot:
923     case Intrinsic::amdgcn_if_break:
924       return true;
925     }
926   }
927 
928   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
929     if (CI->isInlineAsm())
930       return !isInlineAsmSourceOfDivergence(CI);
931     return false;
932   }
933 
934   const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V);
935   if (!ExtValue)
936     return false;
937 
938   const CallInst *CI = dyn_cast<CallInst>(ExtValue->getOperand(0));
939   if (!CI)
940     return false;
941 
942   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(CI)) {
943     switch (Intrinsic->getIntrinsicID()) {
944     default:
945       return false;
946     case Intrinsic::amdgcn_if:
947     case Intrinsic::amdgcn_else: {
948       ArrayRef<unsigned> Indices = ExtValue->getIndices();
949       return Indices.size() == 1 && Indices[0] == 1;
950     }
951     }
952   }
953 
954   // If we have inline asm returning mixed SGPR and VGPR results, we inferred
955   // divergent for the overall struct return. We need to override it in the
956   // case we're extracting an SGPR component here.
957   if (CI->isInlineAsm())
958     return !isInlineAsmSourceOfDivergence(CI, ExtValue->getIndices());
959 
960   return false;
961 }
962 
963 bool GCNTTIImpl::collectFlatAddressOperands(SmallVectorImpl<int> &OpIndexes,
964                                             Intrinsic::ID IID) const {
965   switch (IID) {
966   case Intrinsic::amdgcn_atomic_inc:
967   case Intrinsic::amdgcn_atomic_dec:
968   case Intrinsic::amdgcn_ds_fadd:
969   case Intrinsic::amdgcn_ds_fmin:
970   case Intrinsic::amdgcn_ds_fmax:
971   case Intrinsic::amdgcn_is_shared:
972   case Intrinsic::amdgcn_is_private:
973     OpIndexes.push_back(0);
974     return true;
975   default:
976     return false;
977   }
978 }
979 
980 Value *GCNTTIImpl::rewriteIntrinsicWithAddressSpace(IntrinsicInst *II,
981                                                     Value *OldV,
982                                                     Value *NewV) const {
983   auto IntrID = II->getIntrinsicID();
984   switch (IntrID) {
985   case Intrinsic::amdgcn_atomic_inc:
986   case Intrinsic::amdgcn_atomic_dec:
987   case Intrinsic::amdgcn_ds_fadd:
988   case Intrinsic::amdgcn_ds_fmin:
989   case Intrinsic::amdgcn_ds_fmax: {
990     const ConstantInt *IsVolatile = cast<ConstantInt>(II->getArgOperand(4));
991     if (!IsVolatile->isZero())
992       return nullptr;
993     Module *M = II->getParent()->getParent()->getParent();
994     Type *DestTy = II->getType();
995     Type *SrcTy = NewV->getType();
996     Function *NewDecl =
997         Intrinsic::getDeclaration(M, II->getIntrinsicID(), {DestTy, SrcTy});
998     II->setArgOperand(0, NewV);
999     II->setCalledFunction(NewDecl);
1000     return II;
1001   }
1002   case Intrinsic::amdgcn_is_shared:
1003   case Intrinsic::amdgcn_is_private: {
1004     unsigned TrueAS = IntrID == Intrinsic::amdgcn_is_shared ?
1005       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
1006     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1007     LLVMContext &Ctx = NewV->getType()->getContext();
1008     ConstantInt *NewVal = (TrueAS == NewAS) ?
1009       ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
1010     return NewVal;
1011   }
1012   case Intrinsic::ptrmask: {
1013     unsigned OldAS = OldV->getType()->getPointerAddressSpace();
1014     unsigned NewAS = NewV->getType()->getPointerAddressSpace();
1015     Value *MaskOp = II->getArgOperand(1);
1016     Type *MaskTy = MaskOp->getType();
1017 
1018     bool DoTruncate = false;
1019 
1020     const GCNTargetMachine &TM =
1021         static_cast<const GCNTargetMachine &>(getTLI()->getTargetMachine());
1022     if (!TM.isNoopAddrSpaceCast(OldAS, NewAS)) {
1023       // All valid 64-bit to 32-bit casts work by chopping off the high
1024       // bits. Any masking only clearing the low bits will also apply in the new
1025       // address space.
1026       if (DL.getPointerSizeInBits(OldAS) != 64 ||
1027           DL.getPointerSizeInBits(NewAS) != 32)
1028         return nullptr;
1029 
1030       // TODO: Do we need to thread more context in here?
1031       KnownBits Known = computeKnownBits(MaskOp, DL, 0, nullptr, II);
1032       if (Known.countMinLeadingOnes() < 32)
1033         return nullptr;
1034 
1035       DoTruncate = true;
1036     }
1037 
1038     IRBuilder<> B(II);
1039     if (DoTruncate) {
1040       MaskTy = B.getInt32Ty();
1041       MaskOp = B.CreateTrunc(MaskOp, MaskTy);
1042     }
1043 
1044     return B.CreateIntrinsic(Intrinsic::ptrmask, {NewV->getType(), MaskTy},
1045                              {NewV, MaskOp});
1046   }
1047   default:
1048     return nullptr;
1049   }
1050 }
1051 
1052 InstructionCost GCNTTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
1053                                            VectorType *VT, ArrayRef<int> Mask,
1054                                            int Index, VectorType *SubTp,
1055                                            ArrayRef<Value *> Args) {
1056   Kind = improveShuffleKindFromMask(Kind, Mask);
1057   if (ST->hasVOP3PInsts()) {
1058     if (cast<FixedVectorType>(VT)->getNumElements() == 2 &&
1059         DL.getTypeSizeInBits(VT->getElementType()) == 16) {
1060       // With op_sel VOP3P instructions freely can access the low half or high
1061       // half of a register, so any swizzle is free.
1062 
1063       switch (Kind) {
1064       case TTI::SK_Broadcast:
1065       case TTI::SK_Reverse:
1066       case TTI::SK_PermuteSingleSrc:
1067         return 0;
1068       default:
1069         break;
1070       }
1071     }
1072   }
1073 
1074   return BaseT::getShuffleCost(Kind, VT, Mask, Index, SubTp);
1075 }
1076 
1077 bool GCNTTIImpl::areInlineCompatible(const Function *Caller,
1078                                      const Function *Callee) const {
1079   const TargetMachine &TM = getTLI()->getTargetMachine();
1080   const GCNSubtarget *CallerST
1081     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Caller));
1082   const GCNSubtarget *CalleeST
1083     = static_cast<const GCNSubtarget *>(TM.getSubtargetImpl(*Callee));
1084 
1085   const FeatureBitset &CallerBits = CallerST->getFeatureBits();
1086   const FeatureBitset &CalleeBits = CalleeST->getFeatureBits();
1087 
1088   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
1089   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
1090   if ((RealCallerBits & RealCalleeBits) != RealCalleeBits)
1091     return false;
1092 
1093   // FIXME: dx10_clamp can just take the caller setting, but there seems to be
1094   // no way to support merge for backend defined attributes.
1095   AMDGPU::SIModeRegisterDefaults CallerMode(*Caller);
1096   AMDGPU::SIModeRegisterDefaults CalleeMode(*Callee);
1097   if (!CallerMode.isInlineCompatible(CalleeMode))
1098     return false;
1099 
1100   if (Callee->hasFnAttribute(Attribute::AlwaysInline) ||
1101       Callee->hasFnAttribute(Attribute::InlineHint))
1102     return true;
1103 
1104   // Hack to make compile times reasonable.
1105   if (InlineMaxBB) {
1106     // Single BB does not increase total BB amount.
1107     if (Callee->size() == 1)
1108       return true;
1109     size_t BBSize = Caller->size() + Callee->size() - 1;
1110     return BBSize <= InlineMaxBB;
1111   }
1112 
1113   return true;
1114 }
1115 
1116 unsigned GCNTTIImpl::adjustInliningThreshold(const CallBase *CB) const {
1117   // If we have a pointer to private array passed into a function
1118   // it will not be optimized out, leaving scratch usage.
1119   // Increase the inline threshold to allow inlining in this case.
1120   uint64_t AllocaSize = 0;
1121   SmallPtrSet<const AllocaInst *, 8> AIVisited;
1122   for (Value *PtrArg : CB->args()) {
1123     PointerType *Ty = dyn_cast<PointerType>(PtrArg->getType());
1124     if (!Ty || (Ty->getAddressSpace() != AMDGPUAS::PRIVATE_ADDRESS &&
1125                 Ty->getAddressSpace() != AMDGPUAS::FLAT_ADDRESS))
1126       continue;
1127 
1128     PtrArg = getUnderlyingObject(PtrArg);
1129     if (const AllocaInst *AI = dyn_cast<AllocaInst>(PtrArg)) {
1130       if (!AI->isStaticAlloca() || !AIVisited.insert(AI).second)
1131         continue;
1132       AllocaSize += DL.getTypeAllocSize(AI->getAllocatedType());
1133       // If the amount of stack memory is excessive we will not be able
1134       // to get rid of the scratch anyway, bail out.
1135       if (AllocaSize > ArgAllocaCutoff) {
1136         AllocaSize = 0;
1137         break;
1138       }
1139     }
1140   }
1141   if (AllocaSize)
1142     return ArgAllocaCost;
1143   return 0;
1144 }
1145 
1146 void GCNTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1147                                          TTI::UnrollingPreferences &UP,
1148                                          OptimizationRemarkEmitter *ORE) {
1149   CommonTTI.getUnrollingPreferences(L, SE, UP, ORE);
1150 }
1151 
1152 void GCNTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1153                                        TTI::PeelingPreferences &PP) {
1154   CommonTTI.getPeelingPreferences(L, SE, PP);
1155 }
1156 
1157 int GCNTTIImpl::get64BitInstrCost(TTI::TargetCostKind CostKind) const {
1158   return ST->hasFullRate64Ops()
1159              ? getFullRateInstrCost()
1160              : ST->hasHalfRate64Ops() ? getHalfRateInstrCost(CostKind)
1161                                       : getQuarterRateInstrCost(CostKind);
1162 }
1163