1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #include <cmath>
19 #endif
20 
21 #include "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIISelLowering.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/CodeGen/CallingConvLower.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/IR/DiagnosticInfo.h"
35 #include "llvm/IR/Function.h"
36 
37 using namespace llvm;
38 
39 // -amdgpu-fast-fdiv - Command line option to enable faster 2.5 ulp fdiv.
40 static cl::opt<bool> EnableAMDGPUFastFDIV(
41   "amdgpu-fast-fdiv",
42   cl::desc("Enable faster 2.5 ulp fdiv"),
43   cl::init(false));
44 
45 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
46   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
47   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
48     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
49       return AMDGPU::SGPR0 + Reg;
50     }
51   }
52   llvm_unreachable("Cannot allocate sgpr");
53 }
54 
55 SITargetLowering::SITargetLowering(const TargetMachine &TM,
56                                    const SISubtarget &STI)
57     : AMDGPUTargetLowering(TM, STI) {
58   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
59   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
60 
61   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
62   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
63 
64   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
65   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
66   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
67 
68   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
69   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
70 
71   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
72   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
73 
74   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
75   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
76 
77   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
78   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
79 
80   computeRegisterProperties(STI.getRegisterInfo());
81 
82   // We need to custom lower vector stores from local memory
83   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
84   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
85   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
86   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
87   setOperationAction(ISD::LOAD, MVT::i1, Custom);
88 
89   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
90   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
91   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
92   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
93   setOperationAction(ISD::STORE, MVT::i1, Custom);
94 
95   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
96   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
97   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
98   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
99 
100   setOperationAction(ISD::SELECT, MVT::i1, Promote);
101   setOperationAction(ISD::SELECT, MVT::i64, Custom);
102   setOperationAction(ISD::SELECT, MVT::f64, Promote);
103   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
104 
105   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
106   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
107   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
108   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
109   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
110 
111   setOperationAction(ISD::SETCC, MVT::i1, Promote);
112   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
113   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
114 
115   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
116   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
117 
118   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
125 
126   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
127   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
128   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
129 
130   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
131   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
132   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
133   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
134   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
135   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
136 
137   // We only support LOAD/STORE and vector manipulation ops for vectors
138   // with > 4 elements.
139   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
140     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
141       switch (Op) {
142       case ISD::LOAD:
143       case ISD::STORE:
144       case ISD::BUILD_VECTOR:
145       case ISD::BITCAST:
146       case ISD::EXTRACT_VECTOR_ELT:
147       case ISD::INSERT_VECTOR_ELT:
148       case ISD::INSERT_SUBVECTOR:
149       case ISD::EXTRACT_SUBVECTOR:
150       case ISD::SCALAR_TO_VECTOR:
151         break;
152       case ISD::CONCAT_VECTORS:
153         setOperationAction(Op, VT, Custom);
154         break;
155       default:
156         setOperationAction(Op, VT, Expand);
157         break;
158       }
159     }
160   }
161 
162   // Most operations are naturally 32-bit vector operations. We only support
163   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
164   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
165     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
166     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
167 
168     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
169     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
170 
171     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
172     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
173 
174     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
175     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
176   }
177 
178   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
179   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
180   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
181   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
182 
183   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
184   // and output demarshalling
185   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
186   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
187 
188   // We can't return success/failure, only the old value,
189   // let LLVM add the comparison
190   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
191   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
192 
193   if (getSubtarget()->hasFlatAddressSpace()) {
194     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
195     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
196   }
197 
198   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
199   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
200 
201   // On SI this is s_memtime and s_memrealtime on VI.
202   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
203   setOperationAction(ISD::TRAP, MVT::Other, Custom);
204 
205   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
206   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
207 
208   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
209     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
210     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
211     setOperationAction(ISD::FRINT, MVT::f64, Legal);
212   }
213 
214   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
215 
216   setOperationAction(ISD::FSIN, MVT::f32, Custom);
217   setOperationAction(ISD::FCOS, MVT::f32, Custom);
218   setOperationAction(ISD::FDIV, MVT::f32, Custom);
219   setOperationAction(ISD::FDIV, MVT::f64, Custom);
220 
221   setTargetDAGCombine(ISD::FADD);
222   setTargetDAGCombine(ISD::FSUB);
223   setTargetDAGCombine(ISD::FMINNUM);
224   setTargetDAGCombine(ISD::FMAXNUM);
225   setTargetDAGCombine(ISD::SMIN);
226   setTargetDAGCombine(ISD::SMAX);
227   setTargetDAGCombine(ISD::UMIN);
228   setTargetDAGCombine(ISD::UMAX);
229   setTargetDAGCombine(ISD::SETCC);
230   setTargetDAGCombine(ISD::AND);
231   setTargetDAGCombine(ISD::OR);
232   setTargetDAGCombine(ISD::UINT_TO_FP);
233   setTargetDAGCombine(ISD::FCANONICALIZE);
234 
235   // All memory operations. Some folding on the pointer operand is done to help
236   // matching the constant offsets in the addressing modes.
237   setTargetDAGCombine(ISD::LOAD);
238   setTargetDAGCombine(ISD::STORE);
239   setTargetDAGCombine(ISD::ATOMIC_LOAD);
240   setTargetDAGCombine(ISD::ATOMIC_STORE);
241   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
242   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
243   setTargetDAGCombine(ISD::ATOMIC_SWAP);
244   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
245   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
246   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
247   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
248   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
249   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
250   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
251   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
252   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
253   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
254 
255   setSchedulingPreference(Sched::RegPressure);
256 }
257 
258 const SISubtarget *SITargetLowering::getSubtarget() const {
259   return static_cast<const SISubtarget *>(Subtarget);
260 }
261 
262 //===----------------------------------------------------------------------===//
263 // TargetLowering queries
264 //===----------------------------------------------------------------------===//
265 
266 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
267                                           const CallInst &CI,
268                                           unsigned IntrID) const {
269   switch (IntrID) {
270   case Intrinsic::amdgcn_atomic_inc:
271   case Intrinsic::amdgcn_atomic_dec:
272     Info.opc = ISD::INTRINSIC_W_CHAIN;
273     Info.memVT = MVT::getVT(CI.getType());
274     Info.ptrVal = CI.getOperand(0);
275     Info.align = 0;
276     Info.vol = false;
277     Info.readMem = true;
278     Info.writeMem = true;
279     return true;
280   default:
281     return false;
282   }
283 }
284 
285 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
286                                           EVT) const {
287   // SI has some legal vector types, but no legal vector operations. Say no
288   // shuffles are legal in order to prefer scalarizing some vector operations.
289   return false;
290 }
291 
292 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
293   // Flat instructions do not have offsets, and only have the register
294   // address.
295   return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
296 }
297 
298 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
299   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
300   // additionally can do r + r + i with addr64. 32-bit has more addressing
301   // mode options. Depending on the resource constant, it can also do
302   // (i64 r0) + (i32 r1) * (i14 i).
303   //
304   // Private arrays end up using a scratch buffer most of the time, so also
305   // assume those use MUBUF instructions. Scratch loads / stores are currently
306   // implemented as mubuf instructions with offen bit set, so slightly
307   // different than the normal addr64.
308   if (!isUInt<12>(AM.BaseOffs))
309     return false;
310 
311   // FIXME: Since we can split immediate into soffset and immediate offset,
312   // would it make sense to allow any immediate?
313 
314   switch (AM.Scale) {
315   case 0: // r + i or just i, depending on HasBaseReg.
316     return true;
317   case 1:
318     return true; // We have r + r or r + i.
319   case 2:
320     if (AM.HasBaseReg) {
321       // Reject 2 * r + r.
322       return false;
323     }
324 
325     // Allow 2 * r as r + r
326     // Or  2 * r + i is allowed as r + r + i.
327     return true;
328   default: // Don't allow n * r
329     return false;
330   }
331 }
332 
333 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
334                                              const AddrMode &AM, Type *Ty,
335                                              unsigned AS) const {
336   // No global is ever allowed as a base.
337   if (AM.BaseGV)
338     return false;
339 
340   switch (AS) {
341   case AMDGPUAS::GLOBAL_ADDRESS: {
342     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
343       // Assume the we will use FLAT for all global memory accesses
344       // on VI.
345       // FIXME: This assumption is currently wrong.  On VI we still use
346       // MUBUF instructions for the r + i addressing mode.  As currently
347       // implemented, the MUBUF instructions only work on buffer < 4GB.
348       // It may be possible to support > 4GB buffers with MUBUF instructions,
349       // by setting the stride value in the resource descriptor which would
350       // increase the size limit to (stride * 4GB).  However, this is risky,
351       // because it has never been validated.
352       return isLegalFlatAddressingMode(AM);
353     }
354 
355     return isLegalMUBUFAddressingMode(AM);
356   }
357   case AMDGPUAS::CONSTANT_ADDRESS: {
358     // If the offset isn't a multiple of 4, it probably isn't going to be
359     // correctly aligned.
360     if (AM.BaseOffs % 4 != 0)
361       return isLegalMUBUFAddressingMode(AM);
362 
363     // There are no SMRD extloads, so if we have to do a small type access we
364     // will use a MUBUF load.
365     // FIXME?: We also need to do this if unaligned, but we don't know the
366     // alignment here.
367     if (DL.getTypeStoreSize(Ty) < 4)
368       return isLegalMUBUFAddressingMode(AM);
369 
370     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
371       // SMRD instructions have an 8-bit, dword offset on SI.
372       if (!isUInt<8>(AM.BaseOffs / 4))
373         return false;
374     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
375       // On CI+, this can also be a 32-bit literal constant offset. If it fits
376       // in 8-bits, it can use a smaller encoding.
377       if (!isUInt<32>(AM.BaseOffs / 4))
378         return false;
379     } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) {
380       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
381       if (!isUInt<20>(AM.BaseOffs))
382         return false;
383     } else
384       llvm_unreachable("unhandled generation");
385 
386     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
387       return true;
388 
389     if (AM.Scale == 1 && AM.HasBaseReg)
390       return true;
391 
392     return false;
393   }
394 
395   case AMDGPUAS::PRIVATE_ADDRESS:
396     return isLegalMUBUFAddressingMode(AM);
397 
398   case AMDGPUAS::LOCAL_ADDRESS:
399   case AMDGPUAS::REGION_ADDRESS: {
400     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
401     // field.
402     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
403     // an 8-bit dword offset but we don't know the alignment here.
404     if (!isUInt<16>(AM.BaseOffs))
405       return false;
406 
407     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
408       return true;
409 
410     if (AM.Scale == 1 && AM.HasBaseReg)
411       return true;
412 
413     return false;
414   }
415   case AMDGPUAS::FLAT_ADDRESS:
416   case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
417     // For an unknown address space, this usually means that this is for some
418     // reason being used for pure arithmetic, and not based on some addressing
419     // computation. We don't have instructions that compute pointers with any
420     // addressing modes, so treat them as having no offset like flat
421     // instructions.
422     return isLegalFlatAddressingMode(AM);
423 
424   default:
425     llvm_unreachable("unhandled address space");
426   }
427 }
428 
429 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
430                                                       unsigned AddrSpace,
431                                                       unsigned Align,
432                                                       bool *IsFast) const {
433   if (IsFast)
434     *IsFast = false;
435 
436   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
437   // which isn't a simple VT.
438   if (!VT.isSimple() || VT == MVT::Other)
439     return false;
440 
441   // TODO - CI+ supports unaligned memory accesses, but this requires driver
442   // support.
443 
444   // XXX - The only mention I see of this in the ISA manual is for LDS direct
445   // reads the "byte address and must be dword aligned". Is it also true for the
446   // normal loads and stores?
447   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS) {
448     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
449     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
450     // with adjacent offsets.
451     bool AlignedBy4 = (Align % 4 == 0);
452     if (IsFast)
453       *IsFast = AlignedBy4;
454     return AlignedBy4;
455   }
456 
457   // Smaller than dword value must be aligned.
458   // FIXME: This should be allowed on CI+
459   if (VT.bitsLT(MVT::i32))
460     return false;
461 
462   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
463   // byte-address are ignored, thus forcing Dword alignment.
464   // This applies to private, global, and constant memory.
465   if (IsFast)
466     *IsFast = true;
467 
468   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
469 }
470 
471 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
472                                           unsigned SrcAlign, bool IsMemset,
473                                           bool ZeroMemset,
474                                           bool MemcpyStrSrc,
475                                           MachineFunction &MF) const {
476   // FIXME: Should account for address space here.
477 
478   // The default fallback uses the private pointer size as a guess for a type to
479   // use. Make sure we switch these to 64-bit accesses.
480 
481   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
482     return MVT::v4i32;
483 
484   if (Size >= 8 && DstAlign >= 4)
485     return MVT::v2i32;
486 
487   // Use the default.
488   return MVT::Other;
489 }
490 
491 static bool isFlatGlobalAddrSpace(unsigned AS) {
492   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
493     AS == AMDGPUAS::FLAT_ADDRESS ||
494     AS == AMDGPUAS::CONSTANT_ADDRESS;
495 }
496 
497 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
498                                            unsigned DestAS) const {
499   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
500 }
501 
502 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
503   const MemSDNode *MemNode = cast<MemSDNode>(N);
504   const Value *Ptr = MemNode->getMemOperand()->getValue();
505 
506   // UndefValue means this is a load of a kernel input.  These are uniform.
507   // Sometimes LDS instructions have constant pointers
508   if (isa<UndefValue>(Ptr) || isa<Argument>(Ptr) || isa<Constant>(Ptr) ||
509       isa<GlobalValue>(Ptr))
510     return true;
511 
512   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
513   return I && I->getMetadata("amdgpu.uniform");
514 }
515 
516 TargetLoweringBase::LegalizeTypeAction
517 SITargetLowering::getPreferredVectorAction(EVT VT) const {
518   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
519     return TypeSplitVector;
520 
521   return TargetLoweringBase::getPreferredVectorAction(VT);
522 }
523 
524 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
525                                                          Type *Ty) const {
526   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
527   return TII->isInlineConstant(Imm);
528 }
529 
530 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
531 
532   // SimplifySetCC uses this function to determine whether or not it should
533   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
534   if (VT == MVT::i1 && Op == ISD::SETCC)
535     return false;
536 
537   return TargetLowering::isTypeDesirableForOp(Op, VT);
538 }
539 
540 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
541                                             const SDLoc &SL, SDValue Chain,
542                                             unsigned Offset) const {
543   const DataLayout &DL = DAG.getDataLayout();
544   MachineFunction &MF = DAG.getMachineFunction();
545   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
546   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
547 
548   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
549   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
550   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
551                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
552   return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
553                      DAG.getConstant(Offset, SL, PtrVT));
554 }
555 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
556                                          const SDLoc &SL, SDValue Chain,
557                                          unsigned Offset, bool Signed) const {
558   const DataLayout &DL = DAG.getDataLayout();
559   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
560   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
561   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
562   SDValue PtrOffset = DAG.getUNDEF(PtrVT);
563   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
564 
565   unsigned Align = DL.getABITypeAlignment(Ty);
566 
567   ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
568   if (MemVT.isFloatingPoint())
569     ExtTy = ISD::EXTLOAD;
570 
571   SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
572   return DAG.getLoad(ISD::UNINDEXED, ExtTy,
573                      VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
574                      false, // isVolatile
575                      true, // isNonTemporal
576                      true, // isInvariant
577                      Align); // Alignment
578 }
579 
580 SDValue SITargetLowering::LowerFormalArguments(
581     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
582     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
583     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
584   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
585 
586   MachineFunction &MF = DAG.getMachineFunction();
587   FunctionType *FType = MF.getFunction()->getFunctionType();
588   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
589   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
590 
591   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
592     const Function *Fn = MF.getFunction();
593     DiagnosticInfoUnsupported NoGraphicsHSA(
594         *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
595     DAG.getContext()->diagnose(NoGraphicsHSA);
596     return DAG.getEntryNode();
597   }
598 
599   // Create stack objects that are used for emitting debugger prologue if
600   // "amdgpu-debugger-emit-prologue" attribute was specified.
601   if (ST.debuggerEmitPrologue())
602     createDebuggerPrologueStackObjects(MF);
603 
604   SmallVector<ISD::InputArg, 16> Splits;
605   BitVector Skipped(Ins.size());
606 
607   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
608     const ISD::InputArg &Arg = Ins[i];
609 
610     // First check if it's a PS input addr
611     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
612         !Arg.Flags.isByVal() && PSInputNum <= 15) {
613 
614       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
615         // We can safely skip PS inputs
616         Skipped.set(i);
617         ++PSInputNum;
618         continue;
619       }
620 
621       Info->markPSInputAllocated(PSInputNum);
622       if (Arg.Used)
623         Info->PSInputEna |= 1 << PSInputNum;
624 
625       ++PSInputNum;
626     }
627 
628     if (AMDGPU::isShader(CallConv)) {
629       // Second split vertices into their elements
630       if (Arg.VT.isVector()) {
631         ISD::InputArg NewArg = Arg;
632         NewArg.Flags.setSplit();
633         NewArg.VT = Arg.VT.getVectorElementType();
634 
635         // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
636         // three or five element vertex only needs three or five registers,
637         // NOT four or eight.
638         Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
639         unsigned NumElements = ParamType->getVectorNumElements();
640 
641         for (unsigned j = 0; j != NumElements; ++j) {
642           Splits.push_back(NewArg);
643           NewArg.PartOffset += NewArg.VT.getStoreSize();
644         }
645       } else {
646         Splits.push_back(Arg);
647       }
648     }
649   }
650 
651   SmallVector<CCValAssign, 16> ArgLocs;
652   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
653                  *DAG.getContext());
654 
655   // At least one interpolation mode must be enabled or else the GPU will hang.
656   //
657   // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
658   // PSInputAddr, the user wants to enable some bits after the compilation
659   // based on run-time states. Since we can't know what the final PSInputEna
660   // will look like, so we shouldn't do anything here and the user should take
661   // responsibility for the correct programming.
662   //
663   // Otherwise, the following restrictions apply:
664   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
665   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
666   //   enabled too.
667   if (CallConv == CallingConv::AMDGPU_PS &&
668       ((Info->getPSInputAddr() & 0x7F) == 0 ||
669        ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
670     CCInfo.AllocateReg(AMDGPU::VGPR0);
671     CCInfo.AllocateReg(AMDGPU::VGPR1);
672     Info->markPSInputAllocated(0);
673     Info->PSInputEna |= 1;
674   }
675 
676   if (!AMDGPU::isShader(CallConv)) {
677     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
678                             Splits);
679 
680     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
681   } else {
682     assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() &&
683            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
684            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
685            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
686            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
687            !Info->hasWorkItemIDZ());
688   }
689 
690   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
691   if (Info->hasPrivateSegmentBuffer()) {
692     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
693     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
694     CCInfo.AllocateReg(PrivateSegmentBufferReg);
695   }
696 
697   if (Info->hasDispatchPtr()) {
698     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
699     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
700     CCInfo.AllocateReg(DispatchPtrReg);
701   }
702 
703   if (Info->hasQueuePtr()) {
704     unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
705     MF.addLiveIn(QueuePtrReg, &AMDGPU::SReg_64RegClass);
706     CCInfo.AllocateReg(QueuePtrReg);
707   }
708 
709   if (Info->hasKernargSegmentPtr()) {
710     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
711     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
712     CCInfo.AllocateReg(InputPtrReg);
713   }
714 
715   if (Info->hasFlatScratchInit()) {
716     unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
717     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SReg_64RegClass);
718     CCInfo.AllocateReg(FlatScratchInitReg);
719   }
720 
721   AnalyzeFormalArguments(CCInfo, Splits);
722 
723   SmallVector<SDValue, 16> Chains;
724 
725   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
726 
727     const ISD::InputArg &Arg = Ins[i];
728     if (Skipped[i]) {
729       InVals.push_back(DAG.getUNDEF(Arg.VT));
730       continue;
731     }
732 
733     CCValAssign &VA = ArgLocs[ArgIdx++];
734     MVT VT = VA.getLocVT();
735 
736     if (VA.isMemLoc()) {
737       VT = Ins[i].VT;
738       EVT MemVT = Splits[i].VT;
739       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
740                               VA.getLocMemOffset();
741       // The first 36 bytes of the input buffer contains information about
742       // thread group and global sizes.
743       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
744                                    Offset, Ins[i].Flags.isSExt());
745       Chains.push_back(Arg.getValue(1));
746 
747       auto *ParamTy =
748         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
749       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
750           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
751         // On SI local pointers are just offsets into LDS, so they are always
752         // less than 16-bits.  On CI and newer they could potentially be
753         // real pointers, so we can't guarantee their size.
754         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
755                           DAG.getValueType(MVT::i16));
756       }
757 
758       InVals.push_back(Arg);
759       Info->ABIArgOffset = Offset + MemVT.getStoreSize();
760       continue;
761     }
762     assert(VA.isRegLoc() && "Parameter must be in a register!");
763 
764     unsigned Reg = VA.getLocReg();
765 
766     if (VT == MVT::i64) {
767       // For now assume it is a pointer
768       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
769                                      &AMDGPU::SReg_64RegClass);
770       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
771       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
772       InVals.push_back(Copy);
773       continue;
774     }
775 
776     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
777 
778     Reg = MF.addLiveIn(Reg, RC);
779     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
780 
781     if (Arg.VT.isVector()) {
782 
783       // Build a vector from the registers
784       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
785       unsigned NumElements = ParamType->getVectorNumElements();
786 
787       SmallVector<SDValue, 4> Regs;
788       Regs.push_back(Val);
789       for (unsigned j = 1; j != NumElements; ++j) {
790         Reg = ArgLocs[ArgIdx++].getLocReg();
791         Reg = MF.addLiveIn(Reg, RC);
792 
793         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
794         Regs.push_back(Copy);
795       }
796 
797       // Fill up the missing vector elements
798       NumElements = Arg.VT.getVectorNumElements() - NumElements;
799       Regs.append(NumElements, DAG.getUNDEF(VT));
800 
801       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
802       continue;
803     }
804 
805     InVals.push_back(Val);
806   }
807 
808   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
809   // these from the dispatch pointer.
810 
811   // Start adding system SGPRs.
812   if (Info->hasWorkGroupIDX()) {
813     unsigned Reg = Info->addWorkGroupIDX();
814     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
815     CCInfo.AllocateReg(Reg);
816   }
817 
818   if (Info->hasWorkGroupIDY()) {
819     unsigned Reg = Info->addWorkGroupIDY();
820     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
821     CCInfo.AllocateReg(Reg);
822   }
823 
824   if (Info->hasWorkGroupIDZ()) {
825     unsigned Reg = Info->addWorkGroupIDZ();
826     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
827     CCInfo.AllocateReg(Reg);
828   }
829 
830   if (Info->hasWorkGroupInfo()) {
831     unsigned Reg = Info->addWorkGroupInfo();
832     MF.addLiveIn(Reg, &AMDGPU::SReg_32RegClass);
833     CCInfo.AllocateReg(Reg);
834   }
835 
836   if (Info->hasPrivateSegmentWaveByteOffset()) {
837     // Scratch wave offset passed in system SGPR.
838     unsigned PrivateSegmentWaveByteOffsetReg;
839 
840     if (AMDGPU::isShader(CallConv)) {
841       PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
842       Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
843     } else
844       PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
845 
846     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
847     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
848   }
849 
850   // Now that we've figured out where the scratch register inputs are, see if
851   // should reserve the arguments and use them directly.
852   bool HasStackObjects = MF.getFrameInfo()->hasStackObjects();
853   // Record that we know we have non-spill stack objects so we don't need to
854   // check all stack objects later.
855   if (HasStackObjects)
856     Info->setHasNonSpillStackObjects(true);
857 
858   if (ST.isAmdHsaOS()) {
859     // TODO: Assume we will spill without optimizations.
860     if (HasStackObjects) {
861       // If we have stack objects, we unquestionably need the private buffer
862       // resource. For the HSA ABI, this will be the first 4 user SGPR
863       // inputs. We can reserve those and use them directly.
864 
865       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
866         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
867       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
868 
869       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
870         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
871       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
872     } else {
873       unsigned ReservedBufferReg
874         = TRI->reservedPrivateSegmentBufferReg(MF);
875       unsigned ReservedOffsetReg
876         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
877 
878       // We tentatively reserve the last registers (skipping the last two
879       // which may contain VCC). After register allocation, we'll replace
880       // these with the ones immediately after those which were really
881       // allocated. In the prologue copies will be inserted from the argument
882       // to these reserved registers.
883       Info->setScratchRSrcReg(ReservedBufferReg);
884       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
885     }
886   } else {
887     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
888 
889     // Without HSA, relocations are used for the scratch pointer and the
890     // buffer resource setup is always inserted in the prologue. Scratch wave
891     // offset is still in an input SGPR.
892     Info->setScratchRSrcReg(ReservedBufferReg);
893 
894     if (HasStackObjects) {
895       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
896         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
897       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
898     } else {
899       unsigned ReservedOffsetReg
900         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
901       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
902     }
903   }
904 
905   if (Info->hasWorkItemIDX()) {
906     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
907     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
908     CCInfo.AllocateReg(Reg);
909   }
910 
911   if (Info->hasWorkItemIDY()) {
912     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
913     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
914     CCInfo.AllocateReg(Reg);
915   }
916 
917   if (Info->hasWorkItemIDZ()) {
918     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
919     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
920     CCInfo.AllocateReg(Reg);
921   }
922 
923   if (Chains.empty())
924     return Chain;
925 
926   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
927 }
928 
929 SDValue
930 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
931                               bool isVarArg,
932                               const SmallVectorImpl<ISD::OutputArg> &Outs,
933                               const SmallVectorImpl<SDValue> &OutVals,
934                               const SDLoc &DL, SelectionDAG &DAG) const {
935   MachineFunction &MF = DAG.getMachineFunction();
936   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
937 
938   if (!AMDGPU::isShader(CallConv))
939     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
940                                              OutVals, DL, DAG);
941 
942   Info->setIfReturnsVoid(Outs.size() == 0);
943 
944   SmallVector<ISD::OutputArg, 48> Splits;
945   SmallVector<SDValue, 48> SplitVals;
946 
947   // Split vectors into their elements.
948   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
949     const ISD::OutputArg &Out = Outs[i];
950 
951     if (Out.VT.isVector()) {
952       MVT VT = Out.VT.getVectorElementType();
953       ISD::OutputArg NewOut = Out;
954       NewOut.Flags.setSplit();
955       NewOut.VT = VT;
956 
957       // We want the original number of vector elements here, e.g.
958       // three or five, not four or eight.
959       unsigned NumElements = Out.ArgVT.getVectorNumElements();
960 
961       for (unsigned j = 0; j != NumElements; ++j) {
962         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
963                                    DAG.getConstant(j, DL, MVT::i32));
964         SplitVals.push_back(Elem);
965         Splits.push_back(NewOut);
966         NewOut.PartOffset += NewOut.VT.getStoreSize();
967       }
968     } else {
969       SplitVals.push_back(OutVals[i]);
970       Splits.push_back(Out);
971     }
972   }
973 
974   // CCValAssign - represent the assignment of the return value to a location.
975   SmallVector<CCValAssign, 48> RVLocs;
976 
977   // CCState - Info about the registers and stack slots.
978   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
979                  *DAG.getContext());
980 
981   // Analyze outgoing return values.
982   AnalyzeReturn(CCInfo, Splits);
983 
984   SDValue Flag;
985   SmallVector<SDValue, 48> RetOps;
986   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
987 
988   // Copy the result values into the output registers.
989   for (unsigned i = 0, realRVLocIdx = 0;
990        i != RVLocs.size();
991        ++i, ++realRVLocIdx) {
992     CCValAssign &VA = RVLocs[i];
993     assert(VA.isRegLoc() && "Can only return in registers!");
994 
995     SDValue Arg = SplitVals[realRVLocIdx];
996 
997     // Copied from other backends.
998     switch (VA.getLocInfo()) {
999     default: llvm_unreachable("Unknown loc info!");
1000     case CCValAssign::Full:
1001       break;
1002     case CCValAssign::BCvt:
1003       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1004       break;
1005     }
1006 
1007     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1008     Flag = Chain.getValue(1);
1009     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1010   }
1011 
1012   // Update chain and glue.
1013   RetOps[0] = Chain;
1014   if (Flag.getNode())
1015     RetOps.push_back(Flag);
1016 
1017   unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN;
1018   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1019 }
1020 
1021 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1022                                              SelectionDAG &DAG) const {
1023   unsigned Reg = StringSwitch<unsigned>(RegName)
1024     .Case("m0", AMDGPU::M0)
1025     .Case("exec", AMDGPU::EXEC)
1026     .Case("exec_lo", AMDGPU::EXEC_LO)
1027     .Case("exec_hi", AMDGPU::EXEC_HI)
1028     .Case("flat_scratch", AMDGPU::FLAT_SCR)
1029     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1030     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1031     .Default(AMDGPU::NoRegister);
1032 
1033   if (Reg == AMDGPU::NoRegister) {
1034     report_fatal_error(Twine("invalid register name \""
1035                              + StringRef(RegName)  + "\"."));
1036 
1037   }
1038 
1039   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1040       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1041     report_fatal_error(Twine("invalid register \""
1042                              + StringRef(RegName)  + "\" for subtarget."));
1043   }
1044 
1045   switch (Reg) {
1046   case AMDGPU::M0:
1047   case AMDGPU::EXEC_LO:
1048   case AMDGPU::EXEC_HI:
1049   case AMDGPU::FLAT_SCR_LO:
1050   case AMDGPU::FLAT_SCR_HI:
1051     if (VT.getSizeInBits() == 32)
1052       return Reg;
1053     break;
1054   case AMDGPU::EXEC:
1055   case AMDGPU::FLAT_SCR:
1056     if (VT.getSizeInBits() == 64)
1057       return Reg;
1058     break;
1059   default:
1060     llvm_unreachable("missing register type checking");
1061   }
1062 
1063   report_fatal_error(Twine("invalid type for register \""
1064                            + StringRef(RegName) + "\"."));
1065 }
1066 
1067 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1068   MachineInstr *MI, MachineBasicBlock *BB) const {
1069   switch (MI->getOpcode()) {
1070   case AMDGPU::SI_INIT_M0: {
1071     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1072     BuildMI(*BB, MI->getIterator(), MI->getDebugLoc(),
1073             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1074       .addOperand(MI->getOperand(0));
1075     MI->eraseFromParent();
1076     break;
1077   }
1078   case AMDGPU::BRANCH:
1079     return BB;
1080   case AMDGPU::GET_GROUPSTATICSIZE: {
1081     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1082 
1083     MachineFunction *MF = BB->getParent();
1084     SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1085     DebugLoc DL = MI->getDebugLoc();
1086     BuildMI (*BB, MI, DL, TII->get(AMDGPU::S_MOVK_I32))
1087       .addOperand(MI->getOperand(0))
1088       .addImm(MFI->LDSSize);
1089     MI->eraseFromParent();
1090     return BB;
1091   }
1092   default:
1093     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1094   }
1095   return BB;
1096 }
1097 
1098 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1099   // This currently forces unfolding various combinations of fsub into fma with
1100   // free fneg'd operands. As long as we have fast FMA (controlled by
1101   // isFMAFasterThanFMulAndFAdd), we should perform these.
1102 
1103   // When fma is quarter rate, for f64 where add / sub are at best half rate,
1104   // most of these combines appear to be cycle neutral but save on instruction
1105   // count / code size.
1106   return true;
1107 }
1108 
1109 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
1110                                          EVT VT) const {
1111   if (!VT.isVector()) {
1112     return MVT::i1;
1113   }
1114   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1115 }
1116 
1117 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
1118   return MVT::i32;
1119 }
1120 
1121 // Answering this is somewhat tricky and depends on the specific device which
1122 // have different rates for fma or all f64 operations.
1123 //
1124 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1125 // regardless of which device (although the number of cycles differs between
1126 // devices), so it is always profitable for f64.
1127 //
1128 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1129 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1130 // which we can always do even without fused FP ops since it returns the same
1131 // result as the separate operations and since it is always full
1132 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1133 // however does not support denormals, so we do report fma as faster if we have
1134 // a fast fma device and require denormals.
1135 //
1136 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1137   VT = VT.getScalarType();
1138 
1139   if (!VT.isSimple())
1140     return false;
1141 
1142   switch (VT.getSimpleVT().SimpleTy) {
1143   case MVT::f32:
1144     // This is as fast on some subtargets. However, we always have full rate f32
1145     // mad available which returns the same result as the separate operations
1146     // which we should prefer over fma. We can't use this if we want to support
1147     // denormals, so only report this in these cases.
1148     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1149   case MVT::f64:
1150     return true;
1151   default:
1152     break;
1153   }
1154 
1155   return false;
1156 }
1157 
1158 //===----------------------------------------------------------------------===//
1159 // Custom DAG Lowering Operations
1160 //===----------------------------------------------------------------------===//
1161 
1162 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1163   switch (Op.getOpcode()) {
1164   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1165   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
1166   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1167   case ISD::LOAD: {
1168     SDValue Result = LowerLOAD(Op, DAG);
1169     assert((!Result.getNode() ||
1170             Result.getNode()->getNumValues() == 2) &&
1171            "Load should return a value and a chain");
1172     return Result;
1173   }
1174 
1175   case ISD::FSIN:
1176   case ISD::FCOS:
1177     return LowerTrig(Op, DAG);
1178   case ISD::SELECT: return LowerSELECT(Op, DAG);
1179   case ISD::FDIV: return LowerFDIV(Op, DAG);
1180   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
1181   case ISD::STORE: return LowerSTORE(Op, DAG);
1182   case ISD::GlobalAddress: {
1183     MachineFunction &MF = DAG.getMachineFunction();
1184     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1185     return LowerGlobalAddress(MFI, Op, DAG);
1186   }
1187   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1188   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1189   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1190   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
1191   case ISD::TRAP: return lowerTRAP(Op, DAG);
1192   }
1193   return SDValue();
1194 }
1195 
1196 /// \brief Helper function for LowerBRCOND
1197 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1198 
1199   SDNode *Parent = Value.getNode();
1200   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1201        I != E; ++I) {
1202 
1203     if (I.getUse().get() != Value)
1204       continue;
1205 
1206     if (I->getOpcode() == Opcode)
1207       return *I;
1208   }
1209   return nullptr;
1210 }
1211 
1212 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
1213 
1214   SDLoc SL(Op);
1215   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
1216   unsigned FrameIndex = FINode->getIndex();
1217 
1218   // A FrameIndex node represents a 32-bit offset into scratch memory. If the
1219   // high bit of a frame index offset were to be set, this would mean that it
1220   // represented an offset of ~2GB * 64 = ~128GB from the start of the scratch
1221   // buffer, with 64 being the number of threads per wave.
1222   //
1223   // The maximum private allocation for the entire GPU is 4G, and we are
1224   // concerned with the largest the index could ever be for an individual
1225   // workitem. This will occur with the minmum dispatch size. If a program
1226   // requires more, the dispatch size will be reduced.
1227   //
1228   // With this limit, we can mark the high bit of the FrameIndex node as known
1229   // zero, which is important, because it means in most situations we can prove
1230   // that values derived from FrameIndex nodes are non-negative. This enables us
1231   // to take advantage of more addressing modes when accessing scratch buffers,
1232   // since for scratch reads/writes, the register offset must always be
1233   // positive.
1234 
1235   uint64_t MaxGPUAlloc = UINT64_C(4) * 1024 * 1024 * 1024;
1236 
1237   // XXX - It is unclear if partial dispatch works. Assume it works at half wave
1238   // granularity. It is probably a full wave.
1239   uint64_t MinGranularity = 32;
1240 
1241   unsigned KnownBits = Log2_64(MaxGPUAlloc / MinGranularity);
1242   EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), KnownBits);
1243 
1244   SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
1245   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
1246                      DAG.getValueType(ExtVT));
1247 }
1248 
1249 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
1250   if (Intr->getOpcode() != ISD::INTRINSIC_W_CHAIN)
1251     return false;
1252 
1253   switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
1254   default: return false;
1255   case AMDGPUIntrinsic::amdgcn_if:
1256   case AMDGPUIntrinsic::amdgcn_else:
1257   case AMDGPUIntrinsic::amdgcn_break:
1258   case AMDGPUIntrinsic::amdgcn_if_break:
1259   case AMDGPUIntrinsic::amdgcn_else_break:
1260   case AMDGPUIntrinsic::amdgcn_loop:
1261   case AMDGPUIntrinsic::amdgcn_end_cf:
1262     return true;
1263   }
1264 }
1265 
1266 void SITargetLowering::createDebuggerPrologueStackObjects(
1267     MachineFunction &MF) const {
1268   // Create stack objects that are used for emitting debugger prologue.
1269   //
1270   // Debugger prologue writes work group IDs and work item IDs to scratch memory
1271   // at fixed location in the following format:
1272   //   offset 0:  work group ID x
1273   //   offset 4:  work group ID y
1274   //   offset 8:  work group ID z
1275   //   offset 16: work item ID x
1276   //   offset 20: work item ID y
1277   //   offset 24: work item ID z
1278   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1279   int ObjectIdx = 0;
1280 
1281   // For each dimension:
1282   for (unsigned i = 0; i < 3; ++i) {
1283     // Create fixed stack object for work group ID.
1284     ObjectIdx = MF.getFrameInfo()->CreateFixedObject(4, i * 4, true);
1285     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
1286     // Create fixed stack object for work item ID.
1287     ObjectIdx = MF.getFrameInfo()->CreateFixedObject(4, i * 4 + 16, true);
1288     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
1289   }
1290 }
1291 
1292 /// This transforms the control flow intrinsics to get the branch destination as
1293 /// last parameter, also switches branch target with BR if the need arise
1294 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1295                                       SelectionDAG &DAG) const {
1296 
1297   SDLoc DL(BRCOND);
1298 
1299   SDNode *Intr = BRCOND.getOperand(1).getNode();
1300   SDValue Target = BRCOND.getOperand(2);
1301   SDNode *BR = nullptr;
1302   SDNode *SetCC = nullptr;
1303 
1304   if (Intr->getOpcode() == ISD::SETCC) {
1305     // As long as we negate the condition everything is fine
1306     SetCC = Intr;
1307     Intr = SetCC->getOperand(0).getNode();
1308 
1309   } else {
1310     // Get the target from BR if we don't negate the condition
1311     BR = findUser(BRCOND, ISD::BR);
1312     Target = BR->getOperand(1);
1313   }
1314 
1315   if (!isCFIntrinsic(Intr)) {
1316     // This is a uniform branch so we don't need to legalize.
1317     return BRCOND;
1318   }
1319 
1320   assert(!SetCC ||
1321         (SetCC->getConstantOperandVal(1) == 1 &&
1322          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1323                                                              ISD::SETNE));
1324 
1325   // Build the result and
1326   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
1327 
1328   // operands of the new intrinsic call
1329   SmallVector<SDValue, 4> Ops;
1330   Ops.push_back(BRCOND.getOperand(0));
1331   Ops.append(Intr->op_begin() + 1, Intr->op_end());
1332   Ops.push_back(Target);
1333 
1334   // build the new intrinsic call
1335   SDNode *Result = DAG.getNode(
1336     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
1337     DAG.getVTList(Res), Ops).getNode();
1338 
1339   if (BR) {
1340     // Give the branch instruction our target
1341     SDValue Ops[] = {
1342       BR->getOperand(0),
1343       BRCOND.getOperand(2)
1344     };
1345     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
1346     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
1347     BR = NewBR.getNode();
1348   }
1349 
1350   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
1351 
1352   // Copy the intrinsic results to registers
1353   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
1354     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
1355     if (!CopyToReg)
1356       continue;
1357 
1358     Chain = DAG.getCopyToReg(
1359       Chain, DL,
1360       CopyToReg->getOperand(1),
1361       SDValue(Result, i - 1),
1362       SDValue());
1363 
1364     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
1365   }
1366 
1367   // Remove the old intrinsic from the chain
1368   DAG.ReplaceAllUsesOfValueWith(
1369     SDValue(Intr, Intr->getNumValues() - 1),
1370     Intr->getOperand(0));
1371 
1372   return Chain;
1373 }
1374 
1375 SDValue SITargetLowering::getSegmentAperture(unsigned AS,
1376                                              SelectionDAG &DAG) const {
1377   SDLoc SL;
1378   MachineFunction &MF = DAG.getMachineFunction();
1379   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1380   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
1381   assert(UserSGPR != AMDGPU::NoRegister);
1382 
1383   SDValue QueuePtr = CreateLiveInRegister(
1384     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
1385 
1386   // Offset into amd_queue_t for group_segment_aperture_base_hi /
1387   // private_segment_aperture_base_hi.
1388   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
1389 
1390   SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
1391                             DAG.getConstant(StructOffset, SL, MVT::i64));
1392 
1393   // TODO: Use custom target PseudoSourceValue.
1394   // TODO: We should use the value from the IR intrinsic call, but it might not
1395   // be available and how do we get it?
1396   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
1397                                               AMDGPUAS::CONSTANT_ADDRESS));
1398 
1399   MachinePointerInfo PtrInfo(V, StructOffset);
1400   return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr,
1401                      PtrInfo, false,
1402                      false, true,
1403                      MinAlign(64, StructOffset));
1404 }
1405 
1406 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
1407                                              SelectionDAG &DAG) const {
1408   SDLoc SL(Op);
1409   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
1410 
1411   SDValue Src = ASC->getOperand(0);
1412 
1413   // FIXME: Really support non-0 null pointers.
1414   SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32);
1415   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
1416 
1417   // flat -> local/private
1418   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
1419     if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1420         ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1421       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
1422       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
1423 
1424       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
1425                          NonNull, Ptr, SegmentNullPtr);
1426     }
1427   }
1428 
1429   // local/private -> flat
1430   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
1431     if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
1432         ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1433       SDValue NonNull
1434         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
1435 
1436       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
1437       SDValue CvtPtr
1438         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
1439 
1440       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
1441                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
1442                          FlatNullPtr);
1443     }
1444   }
1445 
1446   // global <-> flat are no-ops and never emitted.
1447 
1448   const MachineFunction &MF = DAG.getMachineFunction();
1449   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
1450     *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
1451   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
1452 
1453   return DAG.getUNDEF(ASC->getValueType(0));
1454 }
1455 
1456 bool
1457 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1458   if (GA->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
1459     return false;
1460 
1461   return TargetLowering::isOffsetFoldingLegal(GA);
1462 }
1463 
1464 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1465                                              SDValue Op,
1466                                              SelectionDAG &DAG) const {
1467   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1468 
1469   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
1470       GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
1471     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1472 
1473   SDLoc DL(GSD);
1474   const GlobalValue *GV = GSD->getGlobal();
1475   EVT PtrVT = Op.getValueType();
1476 
1477   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
1478   // lowered to the following code sequence:
1479   // s_getpc_b64 s[0:1]
1480   // s_add_u32 s0, s0, $symbol
1481   // s_addc_u32 s1, s1, 0
1482   //
1483   // s_getpc_b64 returns the address of the s_add_u32 instruction and then
1484   // a fixup or relocation is emitted to replace $symbol with a literal
1485   // constant, which is a pc-relative offset from the encoding of the $symbol
1486   // operand to the global variable.
1487   //
1488   // What we want here is an offset from the value returned by s_getpc
1489   // (which is the address of the s_add_u32 instruction) to the global
1490   // variable, but since the encoding of $symbol starts 4 bytes after the start
1491   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
1492   // small. This requires us to add 4 to the global variable offset in order to
1493   // compute the correct address.
1494   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32,
1495                                           GSD->getOffset() + 4);
1496   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, GA);
1497 }
1498 
1499 SDValue SITargetLowering::lowerTRAP(SDValue Op,
1500                                     SelectionDAG &DAG) const {
1501   const MachineFunction &MF = DAG.getMachineFunction();
1502   DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
1503                                    "trap handler not supported",
1504                                    Op.getDebugLoc(),
1505                                    DS_Warning);
1506   DAG.getContext()->diagnose(NoTrap);
1507 
1508   // Emit s_endpgm.
1509 
1510   // FIXME: This should really be selected to s_trap, but that requires
1511   // setting up the trap handler for it o do anything.
1512   return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other,
1513                      Op.getOperand(0));
1514 }
1515 
1516 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
1517                                    const SDLoc &DL, SDValue V) const {
1518   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
1519   // the destination register.
1520   //
1521   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1522   // so we will end up with redundant moves to m0.
1523   //
1524   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
1525 
1526   // A Null SDValue creates a glue result.
1527   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
1528                                   V, Chain);
1529   return SDValue(M0, 0);
1530 }
1531 
1532 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1533                                                  SDValue Op,
1534                                                  MVT VT,
1535                                                  unsigned Offset) const {
1536   SDLoc SL(Op);
1537   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1538                                  DAG.getEntryNode(), Offset, false);
1539   // The local size values will have the hi 16-bits as zero.
1540   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1541                      DAG.getValueType(VT));
1542 }
1543 
1544 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
1545   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
1546                                       "non-hsa intrinsic with hsa target",
1547                                       DL.getDebugLoc());
1548   DAG.getContext()->diagnose(BadIntrin);
1549   return DAG.getUNDEF(VT);
1550 }
1551 
1552 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
1553   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
1554                                       "intrinsic not supported on subtarget",
1555                                       DL.getDebugLoc());
1556   DAG.getContext()->diagnose(BadIntrin);
1557   return DAG.getUNDEF(VT);
1558 }
1559 
1560 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1561                                                   SelectionDAG &DAG) const {
1562   MachineFunction &MF = DAG.getMachineFunction();
1563   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1564   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1565 
1566   EVT VT = Op.getValueType();
1567   SDLoc DL(Op);
1568   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1569 
1570   // TODO: Should this propagate fast-math-flags?
1571 
1572   switch (IntrinsicID) {
1573   case Intrinsic::amdgcn_dispatch_ptr:
1574   case Intrinsic::amdgcn_queue_ptr: {
1575     if (!Subtarget->isAmdHsaOS()) {
1576       DiagnosticInfoUnsupported BadIntrin(
1577           *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
1578           DL.getDebugLoc());
1579       DAG.getContext()->diagnose(BadIntrin);
1580       return DAG.getUNDEF(VT);
1581     }
1582 
1583     auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
1584       SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
1585     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1586                                 TRI->getPreloadedValue(MF, Reg), VT);
1587   }
1588   case Intrinsic::amdgcn_implicitarg_ptr: {
1589     unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
1590     return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
1591   }
1592   case Intrinsic::amdgcn_kernarg_segment_ptr: {
1593     unsigned Reg
1594       = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
1595     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
1596   }
1597   case Intrinsic::amdgcn_rcp:
1598     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
1599   case Intrinsic::amdgcn_rsq:
1600   case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name
1601     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
1602   case Intrinsic::amdgcn_rsq_legacy: {
1603     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
1604       return emitRemovedIntrinsicError(DAG, DL, VT);
1605 
1606     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
1607   }
1608   case Intrinsic::amdgcn_rsq_clamp:
1609   case AMDGPUIntrinsic::AMDGPU_rsq_clamped: { // Legacy name
1610     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
1611       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
1612 
1613     Type *Type = VT.getTypeForEVT(*DAG.getContext());
1614     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
1615     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
1616 
1617     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
1618     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
1619                               DAG.getConstantFP(Max, DL, VT));
1620     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
1621                        DAG.getConstantFP(Min, DL, VT));
1622   }
1623   case Intrinsic::r600_read_ngroups_x:
1624     if (Subtarget->isAmdHsaOS())
1625       return emitNonHSAIntrinsicError(DAG, DL, VT);
1626 
1627     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1628                           SI::KernelInputOffsets::NGROUPS_X, false);
1629   case Intrinsic::r600_read_ngroups_y:
1630     if (Subtarget->isAmdHsaOS())
1631       return emitNonHSAIntrinsicError(DAG, DL, VT);
1632 
1633     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1634                           SI::KernelInputOffsets::NGROUPS_Y, false);
1635   case Intrinsic::r600_read_ngroups_z:
1636     if (Subtarget->isAmdHsaOS())
1637       return emitNonHSAIntrinsicError(DAG, DL, VT);
1638 
1639     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1640                           SI::KernelInputOffsets::NGROUPS_Z, false);
1641   case Intrinsic::r600_read_global_size_x:
1642     if (Subtarget->isAmdHsaOS())
1643       return emitNonHSAIntrinsicError(DAG, DL, VT);
1644 
1645     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1646                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1647   case Intrinsic::r600_read_global_size_y:
1648     if (Subtarget->isAmdHsaOS())
1649       return emitNonHSAIntrinsicError(DAG, DL, VT);
1650 
1651     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1652                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1653   case Intrinsic::r600_read_global_size_z:
1654     if (Subtarget->isAmdHsaOS())
1655       return emitNonHSAIntrinsicError(DAG, DL, VT);
1656 
1657     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1658                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1659   case Intrinsic::r600_read_local_size_x:
1660     if (Subtarget->isAmdHsaOS())
1661       return emitNonHSAIntrinsicError(DAG, DL, VT);
1662 
1663     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1664                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
1665   case Intrinsic::r600_read_local_size_y:
1666     if (Subtarget->isAmdHsaOS())
1667       return emitNonHSAIntrinsicError(DAG, DL, VT);
1668 
1669     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1670                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
1671   case Intrinsic::r600_read_local_size_z:
1672     if (Subtarget->isAmdHsaOS())
1673       return emitNonHSAIntrinsicError(DAG, DL, VT);
1674 
1675     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1676                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
1677   case Intrinsic::amdgcn_read_workdim:
1678   case AMDGPUIntrinsic::AMDGPU_read_workdim: // Legacy name.
1679     // Really only 2 bits.
1680     return lowerImplicitZextParam(DAG, Op, MVT::i8,
1681                                   getImplicitParameterOffset(MFI, GRID_DIM));
1682   case Intrinsic::amdgcn_workgroup_id_x:
1683   case Intrinsic::r600_read_tgid_x:
1684     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1685       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1686   case Intrinsic::amdgcn_workgroup_id_y:
1687   case Intrinsic::r600_read_tgid_y:
1688     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1689       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1690   case Intrinsic::amdgcn_workgroup_id_z:
1691   case Intrinsic::r600_read_tgid_z:
1692     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1693       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1694   case Intrinsic::amdgcn_workitem_id_x:
1695   case Intrinsic::r600_read_tidig_x:
1696     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1697       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1698   case Intrinsic::amdgcn_workitem_id_y:
1699   case Intrinsic::r600_read_tidig_y:
1700     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1701       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1702   case Intrinsic::amdgcn_workitem_id_z:
1703   case Intrinsic::r600_read_tidig_z:
1704     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1705       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1706   case AMDGPUIntrinsic::SI_load_const: {
1707     SDValue Ops[] = {
1708       Op.getOperand(1),
1709       Op.getOperand(2)
1710     };
1711 
1712     MachineMemOperand *MMO = MF.getMachineMemOperand(
1713       MachinePointerInfo(),
1714       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1715       VT.getStoreSize(), 4);
1716     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1717                                    Op->getVTList(), Ops, VT, MMO);
1718   }
1719   case AMDGPUIntrinsic::SI_vs_load_input:
1720     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1721                        Op.getOperand(1),
1722                        Op.getOperand(2),
1723                        Op.getOperand(3));
1724 
1725   case AMDGPUIntrinsic::SI_fs_constant: {
1726     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1727     SDValue Glue = M0.getValue(1);
1728     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1729                        DAG.getConstant(2, DL, MVT::i32), // P0
1730                        Op.getOperand(1), Op.getOperand(2), Glue);
1731   }
1732   case AMDGPUIntrinsic::SI_packf16:
1733     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1734       return DAG.getUNDEF(MVT::i32);
1735     return Op;
1736   case AMDGPUIntrinsic::SI_fs_interp: {
1737     SDValue IJ = Op.getOperand(4);
1738     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1739                             DAG.getConstant(0, DL, MVT::i32));
1740     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1741                             DAG.getConstant(1, DL, MVT::i32));
1742     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1743     SDValue Glue = M0.getValue(1);
1744     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1745                              DAG.getVTList(MVT::f32, MVT::Glue),
1746                              I, Op.getOperand(1), Op.getOperand(2), Glue);
1747     Glue = SDValue(P1.getNode(), 1);
1748     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1749                              Op.getOperand(1), Op.getOperand(2), Glue);
1750   }
1751   case Intrinsic::amdgcn_interp_p1: {
1752     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
1753     SDValue Glue = M0.getValue(1);
1754     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
1755                        Op.getOperand(2), Op.getOperand(3), Glue);
1756   }
1757   case Intrinsic::amdgcn_interp_p2: {
1758     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
1759     SDValue Glue = SDValue(M0.getNode(), 1);
1760     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
1761                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
1762                        Glue);
1763   }
1764   case Intrinsic::amdgcn_sin:
1765     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
1766 
1767   case Intrinsic::amdgcn_cos:
1768     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
1769 
1770   case Intrinsic::amdgcn_log_clamp: {
1771     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
1772       return SDValue();
1773 
1774     DiagnosticInfoUnsupported BadIntrin(
1775       *MF.getFunction(), "intrinsic not supported on subtarget",
1776       DL.getDebugLoc());
1777       DAG.getContext()->diagnose(BadIntrin);
1778       return DAG.getUNDEF(VT);
1779   }
1780   case Intrinsic::amdgcn_ldexp:
1781     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
1782                        Op.getOperand(1), Op.getOperand(2));
1783 
1784   case Intrinsic::amdgcn_fract:
1785     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
1786 
1787   case Intrinsic::amdgcn_class:
1788     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
1789                        Op.getOperand(1), Op.getOperand(2));
1790   case Intrinsic::amdgcn_div_fmas:
1791     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
1792                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
1793                        Op.getOperand(4));
1794 
1795   case Intrinsic::amdgcn_div_fixup:
1796     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
1797                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
1798 
1799   case Intrinsic::amdgcn_trig_preop:
1800     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
1801                        Op.getOperand(1), Op.getOperand(2));
1802   case Intrinsic::amdgcn_div_scale: {
1803     // 3rd parameter required to be a constant.
1804     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
1805     if (!Param)
1806       return DAG.getUNDEF(VT);
1807 
1808     // Translate to the operands expected by the machine instruction. The
1809     // first parameter must be the same as the first instruction.
1810     SDValue Numerator = Op.getOperand(1);
1811     SDValue Denominator = Op.getOperand(2);
1812 
1813     // Note this order is opposite of the machine instruction's operations,
1814     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
1815     // intrinsic has the numerator as the first operand to match a normal
1816     // division operation.
1817 
1818     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
1819 
1820     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
1821                        Denominator, Numerator);
1822   }
1823   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte0:
1824     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Op.getOperand(1));
1825   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte1:
1826     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE1, DL, VT, Op.getOperand(1));
1827   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte2:
1828     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE2, DL, VT, Op.getOperand(1));
1829   case AMDGPUIntrinsic::AMDGPU_cvt_f32_ubyte3:
1830     return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE3, DL, VT, Op.getOperand(1));
1831   default:
1832     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1833   }
1834 }
1835 
1836 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
1837                                                  SelectionDAG &DAG) const {
1838   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1839   switch (IntrID) {
1840   case Intrinsic::amdgcn_atomic_inc:
1841   case Intrinsic::amdgcn_atomic_dec: {
1842     MemSDNode *M = cast<MemSDNode>(Op);
1843     unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
1844       AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
1845     SDValue Ops[] = {
1846       M->getOperand(0), // Chain
1847       M->getOperand(2), // Ptr
1848       M->getOperand(3)  // Value
1849     };
1850 
1851     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
1852                                    M->getMemoryVT(), M->getMemOperand());
1853   }
1854   default:
1855     return SDValue();
1856   }
1857 }
1858 
1859 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1860                                               SelectionDAG &DAG) const {
1861   MachineFunction &MF = DAG.getMachineFunction();
1862   SDLoc DL(Op);
1863   SDValue Chain = Op.getOperand(0);
1864   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1865 
1866   switch (IntrinsicID) {
1867   case AMDGPUIntrinsic::SI_sendmsg: {
1868     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1869     SDValue Glue = Chain.getValue(1);
1870     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1871                        Op.getOperand(2), Glue);
1872   }
1873   case AMDGPUIntrinsic::SI_tbuffer_store: {
1874     SDValue Ops[] = {
1875       Chain,
1876       Op.getOperand(2),
1877       Op.getOperand(3),
1878       Op.getOperand(4),
1879       Op.getOperand(5),
1880       Op.getOperand(6),
1881       Op.getOperand(7),
1882       Op.getOperand(8),
1883       Op.getOperand(9),
1884       Op.getOperand(10),
1885       Op.getOperand(11),
1886       Op.getOperand(12),
1887       Op.getOperand(13),
1888       Op.getOperand(14)
1889     };
1890 
1891     EVT VT = Op.getOperand(3).getValueType();
1892 
1893     MachineMemOperand *MMO = MF.getMachineMemOperand(
1894       MachinePointerInfo(),
1895       MachineMemOperand::MOStore,
1896       VT.getStoreSize(), 4);
1897     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1898                                    Op->getVTList(), Ops, VT, MMO);
1899   }
1900   default:
1901     return SDValue();
1902   }
1903 }
1904 
1905 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1906   SDLoc DL(Op);
1907   LoadSDNode *Load = cast<LoadSDNode>(Op);
1908   ISD::LoadExtType ExtType = Load->getExtensionType();
1909   EVT MemVT = Load->getMemoryVT();
1910 
1911   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
1912     assert(MemVT == MVT::i1 && "Only i1 non-extloads expected");
1913     // FIXME: Copied from PPC
1914     // First, load into 32 bits, then truncate to 1 bit.
1915 
1916     SDValue Chain = Load->getChain();
1917     SDValue BasePtr = Load->getBasePtr();
1918     MachineMemOperand *MMO = Load->getMemOperand();
1919 
1920     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
1921                                    BasePtr, MVT::i8, MMO);
1922 
1923     SDValue Ops[] = {
1924       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
1925       NewLD.getValue(1)
1926     };
1927 
1928     return DAG.getMergeValues(Ops, DL);
1929   }
1930 
1931   if (!MemVT.isVector())
1932     return SDValue();
1933 
1934   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1935          "Custom lowering for non-i32 vectors hasn't been implemented.");
1936 
1937   unsigned AS = Load->getAddressSpace();
1938   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
1939                           AS, Load->getAlignment())) {
1940     SDValue Ops[2];
1941     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
1942     return DAG.getMergeValues(Ops, DL);
1943   }
1944 
1945   unsigned NumElements = MemVT.getVectorNumElements();
1946   switch (AS) {
1947   case AMDGPUAS::CONSTANT_ADDRESS:
1948     if (isMemOpUniform(Load))
1949       return SDValue();
1950     // Non-uniform loads will be selected to MUBUF instructions, so they
1951     // have the same legalization requires ments as global and private
1952     // loads.
1953     //
1954     // Fall-through
1955   case AMDGPUAS::GLOBAL_ADDRESS:
1956   case AMDGPUAS::FLAT_ADDRESS:
1957     if (NumElements > 4)
1958       return SplitVectorLoad(Op, DAG);
1959     // v4 loads are supported for private and global memory.
1960     return SDValue();
1961   case AMDGPUAS::PRIVATE_ADDRESS: {
1962     // Depending on the setting of the private_element_size field in the
1963     // resource descriptor, we can only make private accesses up to a certain
1964     // size.
1965     switch (Subtarget->getMaxPrivateElementSize()) {
1966     case 4:
1967       return scalarizeVectorLoad(Load, DAG);
1968     case 8:
1969       if (NumElements > 2)
1970         return SplitVectorLoad(Op, DAG);
1971       return SDValue();
1972     case 16:
1973       // Same as global/flat
1974       if (NumElements > 4)
1975         return SplitVectorLoad(Op, DAG);
1976       return SDValue();
1977     default:
1978       llvm_unreachable("unsupported private_element_size");
1979     }
1980   }
1981   case AMDGPUAS::LOCAL_ADDRESS: {
1982     if (NumElements > 2)
1983       return SplitVectorLoad(Op, DAG);
1984 
1985     if (NumElements == 2)
1986       return SDValue();
1987 
1988     // If properly aligned, if we split we might be able to use ds_read_b64.
1989     return SplitVectorLoad(Op, DAG);
1990   }
1991   default:
1992     return SDValue();
1993   }
1994 }
1995 
1996 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1997   if (Op.getValueType() != MVT::i64)
1998     return SDValue();
1999 
2000   SDLoc DL(Op);
2001   SDValue Cond = Op.getOperand(0);
2002 
2003   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2004   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2005 
2006   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
2007   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
2008 
2009   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
2010   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
2011 
2012   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
2013 
2014   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
2015   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
2016 
2017   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
2018 
2019   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
2020   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
2021 }
2022 
2023 // Catch division cases where we can use shortcuts with rcp and rsq
2024 // instructions.
2025 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
2026   SDLoc SL(Op);
2027   SDValue LHS = Op.getOperand(0);
2028   SDValue RHS = Op.getOperand(1);
2029   EVT VT = Op.getValueType();
2030   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
2031 
2032   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
2033     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
2034         CLHS->isExactlyValue(1.0)) {
2035       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
2036       // the CI documentation has a worst case error of 1 ulp.
2037       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
2038       // use it as long as we aren't trying to use denormals.
2039 
2040       // 1.0 / sqrt(x) -> rsq(x)
2041       //
2042       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
2043       // error seems really high at 2^29 ULP.
2044       if (RHS.getOpcode() == ISD::FSQRT)
2045         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
2046 
2047       // 1.0 / x -> rcp(x)
2048       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2049     }
2050   }
2051 
2052   const SDNodeFlags *Flags = Op->getFlags();
2053 
2054   if (Unsafe || Flags->hasAllowReciprocal()) {
2055     // Turn into multiply by the reciprocal.
2056     // x / y -> x * (1.0 / y)
2057     SDNodeFlags Flags;
2058     Flags.setUnsafeAlgebra(true);
2059     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2060     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
2061   }
2062 
2063   return SDValue();
2064 }
2065 
2066 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
2067   if (SDValue FastLowered = LowerFastFDIV(Op, DAG))
2068     return FastLowered;
2069 
2070   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
2071   // selection error for now rather than do something incorrect.
2072   if (Subtarget->hasFP32Denormals())
2073     return SDValue();
2074 
2075   SDLoc SL(Op);
2076   SDValue LHS = Op.getOperand(0);
2077   SDValue RHS = Op.getOperand(1);
2078 
2079   // faster 2.5 ulp fdiv when using -amdgpu-fast-fdiv flag
2080   if (EnableAMDGPUFastFDIV) {
2081     SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
2082 
2083     const APFloat K0Val(BitsToFloat(0x6f800000));
2084     const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
2085 
2086     const APFloat K1Val(BitsToFloat(0x2f800000));
2087     const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
2088 
2089     const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
2090 
2091     EVT SetCCVT =
2092         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
2093 
2094     SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
2095 
2096     SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
2097 
2098     // TODO: Should this propagate fast-math-flags?
2099 
2100     r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
2101 
2102     SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
2103 
2104     SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
2105 
2106     return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
2107   }
2108 
2109   // Generates more precise fpdiv32.
2110   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
2111 
2112   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
2113 
2114   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, RHS, RHS, LHS);
2115   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, LHS, RHS, LHS);
2116 
2117   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, DenominatorScaled);
2118 
2119   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, DenominatorScaled);
2120 
2121   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, ApproxRcp, One);
2122   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, ApproxRcp);
2123 
2124   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, NumeratorScaled, Fma1);
2125 
2126   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, NumeratorScaled);
2127   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul);
2128   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, NumeratorScaled);
2129 
2130   SDValue Scale = NumeratorScaled.getValue(1);
2131   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, Fma4, Fma1, Fma3, Scale);
2132 
2133   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
2134 }
2135 
2136 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
2137   if (DAG.getTarget().Options.UnsafeFPMath)
2138     return LowerFastFDIV(Op, DAG);
2139 
2140   SDLoc SL(Op);
2141   SDValue X = Op.getOperand(0);
2142   SDValue Y = Op.getOperand(1);
2143 
2144   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2145 
2146   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
2147 
2148   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
2149 
2150   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
2151 
2152   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
2153 
2154   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
2155 
2156   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
2157 
2158   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
2159 
2160   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
2161 
2162   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
2163   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
2164 
2165   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
2166                              NegDivScale0, Mul, DivScale1);
2167 
2168   SDValue Scale;
2169 
2170   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
2171     // Workaround a hardware bug on SI where the condition output from div_scale
2172     // is not usable.
2173 
2174     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
2175 
2176     // Figure out if the scale to use for div_fmas.
2177     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2178     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
2179     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
2180     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
2181 
2182     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
2183     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
2184 
2185     SDValue Scale0Hi
2186       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
2187     SDValue Scale1Hi
2188       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
2189 
2190     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
2191     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
2192     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
2193   } else {
2194     Scale = DivScale1.getValue(1);
2195   }
2196 
2197   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
2198                              Fma4, Fma3, Mul, Scale);
2199 
2200   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
2201 }
2202 
2203 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
2204   EVT VT = Op.getValueType();
2205 
2206   if (VT == MVT::f32)
2207     return LowerFDIV32(Op, DAG);
2208 
2209   if (VT == MVT::f64)
2210     return LowerFDIV64(Op, DAG);
2211 
2212   llvm_unreachable("Unexpected type for fdiv");
2213 }
2214 
2215 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2216   SDLoc DL(Op);
2217   StoreSDNode *Store = cast<StoreSDNode>(Op);
2218   EVT VT = Store->getMemoryVT();
2219 
2220   if (VT == MVT::i1) {
2221     return DAG.getTruncStore(Store->getChain(), DL,
2222        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
2223        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
2224   }
2225 
2226   assert(VT.isVector() &&
2227          Store->getValue().getValueType().getScalarType() == MVT::i32);
2228 
2229   unsigned AS = Store->getAddressSpace();
2230   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
2231                           AS, Store->getAlignment())) {
2232     return expandUnalignedStore(Store, DAG);
2233   }
2234 
2235   unsigned NumElements = VT.getVectorNumElements();
2236   switch (AS) {
2237   case AMDGPUAS::GLOBAL_ADDRESS:
2238   case AMDGPUAS::FLAT_ADDRESS:
2239     if (NumElements > 4)
2240       return SplitVectorStore(Op, DAG);
2241     return SDValue();
2242   case AMDGPUAS::PRIVATE_ADDRESS: {
2243     switch (Subtarget->getMaxPrivateElementSize()) {
2244     case 4:
2245       return scalarizeVectorStore(Store, DAG);
2246     case 8:
2247       if (NumElements > 2)
2248         return SplitVectorStore(Op, DAG);
2249       return SDValue();
2250     case 16:
2251       if (NumElements > 4)
2252         return SplitVectorStore(Op, DAG);
2253       return SDValue();
2254     default:
2255       llvm_unreachable("unsupported private_element_size");
2256     }
2257   }
2258   case AMDGPUAS::LOCAL_ADDRESS: {
2259     if (NumElements > 2)
2260       return SplitVectorStore(Op, DAG);
2261 
2262     if (NumElements == 2)
2263       return Op;
2264 
2265     // If properly aligned, if we split we might be able to use ds_write_b64.
2266     return SplitVectorStore(Op, DAG);
2267   }
2268   default:
2269     llvm_unreachable("unhandled address space");
2270   }
2271 }
2272 
2273 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
2274   SDLoc DL(Op);
2275   EVT VT = Op.getValueType();
2276   SDValue Arg = Op.getOperand(0);
2277   // TODO: Should this propagate fast-math-flags?
2278   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
2279                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
2280                                               DAG.getConstantFP(0.5/M_PI, DL,
2281                                                                 VT)));
2282 
2283   switch (Op.getOpcode()) {
2284   case ISD::FCOS:
2285     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
2286   case ISD::FSIN:
2287     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
2288   default:
2289     llvm_unreachable("Wrong trig opcode");
2290   }
2291 }
2292 
2293 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
2294   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
2295   assert(AtomicNode->isCompareAndSwap());
2296   unsigned AS = AtomicNode->getAddressSpace();
2297 
2298   // No custom lowering required for local address space
2299   if (!isFlatGlobalAddrSpace(AS))
2300     return Op;
2301 
2302   // Non-local address space requires custom lowering for atomic compare
2303   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
2304   SDLoc DL(Op);
2305   SDValue ChainIn = Op.getOperand(0);
2306   SDValue Addr = Op.getOperand(1);
2307   SDValue Old = Op.getOperand(2);
2308   SDValue New = Op.getOperand(3);
2309   EVT VT = Op.getValueType();
2310   MVT SimpleVT = VT.getSimpleVT();
2311   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
2312 
2313   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
2314   SDValue Ops[] = { ChainIn, Addr, NewOld };
2315 
2316   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
2317                                  Ops, VT, AtomicNode->getMemOperand());
2318 }
2319 
2320 //===----------------------------------------------------------------------===//
2321 // Custom DAG optimizations
2322 //===----------------------------------------------------------------------===//
2323 
2324 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
2325                                                      DAGCombinerInfo &DCI) const {
2326   EVT VT = N->getValueType(0);
2327   EVT ScalarVT = VT.getScalarType();
2328   if (ScalarVT != MVT::f32)
2329     return SDValue();
2330 
2331   SelectionDAG &DAG = DCI.DAG;
2332   SDLoc DL(N);
2333 
2334   SDValue Src = N->getOperand(0);
2335   EVT SrcVT = Src.getValueType();
2336 
2337   // TODO: We could try to match extracting the higher bytes, which would be
2338   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
2339   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
2340   // about in practice.
2341   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
2342     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
2343       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
2344       DCI.AddToWorklist(Cvt.getNode());
2345       return Cvt;
2346     }
2347   }
2348 
2349   // We are primarily trying to catch operations on illegal vector types
2350   // before they are expanded.
2351   // For scalars, we can use the more flexible method of checking masked bits
2352   // after legalization.
2353   if (!DCI.isBeforeLegalize() ||
2354       !SrcVT.isVector() ||
2355       SrcVT.getVectorElementType() != MVT::i8) {
2356     return SDValue();
2357   }
2358 
2359   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
2360 
2361   // Weird sized vectors are a pain to handle, but we know 3 is really the same
2362   // size as 4.
2363   unsigned NElts = SrcVT.getVectorNumElements();
2364   if (!SrcVT.isSimple() && NElts != 3)
2365     return SDValue();
2366 
2367   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
2368   // prevent a mess from expanding to v4i32 and repacking.
2369   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
2370     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
2371     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
2372     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
2373     LoadSDNode *Load = cast<LoadSDNode>(Src);
2374 
2375     unsigned AS = Load->getAddressSpace();
2376     unsigned Align = Load->getAlignment();
2377     Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
2378     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
2379 
2380     // Don't try to replace the load if we have to expand it due to alignment
2381     // problems. Otherwise we will end up scalarizing the load, and trying to
2382     // repack into the vector for no real reason.
2383     if (Align < ABIAlignment &&
2384         !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
2385       return SDValue();
2386     }
2387 
2388     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
2389                                      Load->getChain(),
2390                                      Load->getBasePtr(),
2391                                      LoadVT,
2392                                      Load->getMemOperand());
2393 
2394     // Make sure successors of the original load stay after it by updating
2395     // them to use the new Chain.
2396     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
2397 
2398     SmallVector<SDValue, 4> Elts;
2399     if (RegVT.isVector())
2400       DAG.ExtractVectorElements(NewLoad, Elts);
2401     else
2402       Elts.push_back(NewLoad);
2403 
2404     SmallVector<SDValue, 4> Ops;
2405 
2406     unsigned EltIdx = 0;
2407     for (SDValue Elt : Elts) {
2408       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
2409       for (unsigned I = 0; I < ComponentsInElt; ++I) {
2410         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
2411         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
2412         DCI.AddToWorklist(Cvt.getNode());
2413         Ops.push_back(Cvt);
2414       }
2415 
2416       ++EltIdx;
2417     }
2418 
2419     assert(Ops.size() == NElts);
2420 
2421     return DAG.getBuildVector(FloatVT, DL, Ops);
2422   }
2423 
2424   return SDValue();
2425 }
2426 
2427 /// \brief Return true if the given offset Size in bytes can be folded into
2428 /// the immediate offsets of a memory instruction for the given address space.
2429 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
2430                           const SISubtarget &STI) {
2431   switch (AS) {
2432   case AMDGPUAS::GLOBAL_ADDRESS: {
2433     // MUBUF instructions a 12-bit offset in bytes.
2434     return isUInt<12>(OffsetSize);
2435   }
2436   case AMDGPUAS::CONSTANT_ADDRESS: {
2437     // SMRD instructions have an 8-bit offset in dwords on SI and
2438     // a 20-bit offset in bytes on VI.
2439     if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2440       return isUInt<20>(OffsetSize);
2441     else
2442       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
2443   }
2444   case AMDGPUAS::LOCAL_ADDRESS:
2445   case AMDGPUAS::REGION_ADDRESS: {
2446     // The single offset versions have a 16-bit offset in bytes.
2447     return isUInt<16>(OffsetSize);
2448   }
2449   case AMDGPUAS::PRIVATE_ADDRESS:
2450   // Indirect register addressing does not use any offsets.
2451   default:
2452     return 0;
2453   }
2454 }
2455 
2456 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
2457 
2458 // This is a variant of
2459 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
2460 //
2461 // The normal DAG combiner will do this, but only if the add has one use since
2462 // that would increase the number of instructions.
2463 //
2464 // This prevents us from seeing a constant offset that can be folded into a
2465 // memory instruction's addressing mode. If we know the resulting add offset of
2466 // a pointer can be folded into an addressing offset, we can replace the pointer
2467 // operand with the add of new constant offset. This eliminates one of the uses,
2468 // and may allow the remaining use to also be simplified.
2469 //
2470 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
2471                                                unsigned AddrSpace,
2472                                                DAGCombinerInfo &DCI) const {
2473   SDValue N0 = N->getOperand(0);
2474   SDValue N1 = N->getOperand(1);
2475 
2476   if (N0.getOpcode() != ISD::ADD)
2477     return SDValue();
2478 
2479   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
2480   if (!CN1)
2481     return SDValue();
2482 
2483   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2484   if (!CAdd)
2485     return SDValue();
2486 
2487   // If the resulting offset is too large, we can't fold it into the addressing
2488   // mode offset.
2489   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
2490   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
2491     return SDValue();
2492 
2493   SelectionDAG &DAG = DCI.DAG;
2494   SDLoc SL(N);
2495   EVT VT = N->getValueType(0);
2496 
2497   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
2498   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
2499 
2500   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
2501 }
2502 
2503 SDValue SITargetLowering::performAndCombine(SDNode *N,
2504                                             DAGCombinerInfo &DCI) const {
2505   if (DCI.isBeforeLegalize())
2506     return SDValue();
2507 
2508   if (SDValue Base = AMDGPUTargetLowering::performAndCombine(N, DCI))
2509     return Base;
2510 
2511   SelectionDAG &DAG = DCI.DAG;
2512 
2513   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
2514   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
2515   SDValue LHS = N->getOperand(0);
2516   SDValue RHS = N->getOperand(1);
2517 
2518   if (LHS.getOpcode() == ISD::SETCC &&
2519       RHS.getOpcode() == ISD::SETCC) {
2520     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
2521     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
2522 
2523     SDValue X = LHS.getOperand(0);
2524     SDValue Y = RHS.getOperand(0);
2525     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
2526       return SDValue();
2527 
2528     if (LCC == ISD::SETO) {
2529       if (X != LHS.getOperand(1))
2530         return SDValue();
2531 
2532       if (RCC == ISD::SETUNE) {
2533         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
2534         if (!C1 || !C1->isInfinity() || C1->isNegative())
2535           return SDValue();
2536 
2537         const uint32_t Mask = SIInstrFlags::N_NORMAL |
2538                               SIInstrFlags::N_SUBNORMAL |
2539                               SIInstrFlags::N_ZERO |
2540                               SIInstrFlags::P_ZERO |
2541                               SIInstrFlags::P_SUBNORMAL |
2542                               SIInstrFlags::P_NORMAL;
2543 
2544         static_assert(((~(SIInstrFlags::S_NAN |
2545                           SIInstrFlags::Q_NAN |
2546                           SIInstrFlags::N_INFINITY |
2547                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
2548                       "mask not equal");
2549 
2550         SDLoc DL(N);
2551         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
2552                            X, DAG.getConstant(Mask, DL, MVT::i32));
2553       }
2554     }
2555   }
2556 
2557   return SDValue();
2558 }
2559 
2560 SDValue SITargetLowering::performOrCombine(SDNode *N,
2561                                            DAGCombinerInfo &DCI) const {
2562   SelectionDAG &DAG = DCI.DAG;
2563   SDValue LHS = N->getOperand(0);
2564   SDValue RHS = N->getOperand(1);
2565 
2566   EVT VT = N->getValueType(0);
2567   if (VT == MVT::i64) {
2568     // TODO: This could be a generic combine with a predicate for extracting the
2569     // high half of an integer being free.
2570 
2571     // (or i64:x, (zero_extend i32:y)) ->
2572     //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
2573     if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
2574         RHS.getOpcode() != ISD::ZERO_EXTEND)
2575       std::swap(LHS, RHS);
2576 
2577     if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
2578       SDValue ExtSrc = RHS.getOperand(0);
2579       EVT SrcVT = ExtSrc.getValueType();
2580       if (SrcVT == MVT::i32) {
2581         SDLoc SL(N);
2582         SDValue LowLHS, HiBits;
2583         std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
2584         SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
2585 
2586         DCI.AddToWorklist(LowOr.getNode());
2587         DCI.AddToWorklist(HiBits.getNode());
2588 
2589         SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
2590                                   LowOr, HiBits);
2591         return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
2592       }
2593     }
2594   }
2595 
2596   // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
2597   if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
2598       RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
2599     SDValue Src = LHS.getOperand(0);
2600     if (Src != RHS.getOperand(0))
2601       return SDValue();
2602 
2603     const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
2604     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
2605     if (!CLHS || !CRHS)
2606       return SDValue();
2607 
2608     // Only 10 bits are used.
2609     static const uint32_t MaxMask = 0x3ff;
2610 
2611     uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
2612     SDLoc DL(N);
2613     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
2614                        Src, DAG.getConstant(NewMask, DL, MVT::i32));
2615   }
2616 
2617   return SDValue();
2618 }
2619 
2620 SDValue SITargetLowering::performClassCombine(SDNode *N,
2621                                               DAGCombinerInfo &DCI) const {
2622   SelectionDAG &DAG = DCI.DAG;
2623   SDValue Mask = N->getOperand(1);
2624 
2625   // fp_class x, 0 -> false
2626   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
2627     if (CMask->isNullValue())
2628       return DAG.getConstant(0, SDLoc(N), MVT::i1);
2629   }
2630 
2631   if (N->getOperand(0).isUndef())
2632     return DAG.getUNDEF(MVT::i1);
2633 
2634   return SDValue();
2635 }
2636 
2637 // Constant fold canonicalize.
2638 SDValue SITargetLowering::performFCanonicalizeCombine(
2639   SDNode *N,
2640   DAGCombinerInfo &DCI) const {
2641   ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
2642   if (!CFP)
2643     return SDValue();
2644 
2645   SelectionDAG &DAG = DCI.DAG;
2646   const APFloat &C = CFP->getValueAPF();
2647 
2648   // Flush denormals to 0 if not enabled.
2649   if (C.isDenormal()) {
2650     EVT VT = N->getValueType(0);
2651     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals())
2652       return DAG.getConstantFP(0.0, SDLoc(N), VT);
2653 
2654     if (VT == MVT::f64 && !Subtarget->hasFP64Denormals())
2655       return DAG.getConstantFP(0.0, SDLoc(N), VT);
2656   }
2657 
2658   if (C.isNaN()) {
2659     EVT VT = N->getValueType(0);
2660     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
2661     if (C.isSignaling()) {
2662       // Quiet a signaling NaN.
2663       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
2664     }
2665 
2666     // Make sure it is the canonical NaN bitpattern.
2667     //
2668     // TODO: Can we use -1 as the canonical NaN value since it's an inline
2669     // immediate?
2670     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
2671       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
2672   }
2673 
2674   return SDValue(CFP, 0);
2675 }
2676 
2677 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
2678   switch (Opc) {
2679   case ISD::FMAXNUM:
2680     return AMDGPUISD::FMAX3;
2681   case ISD::SMAX:
2682     return AMDGPUISD::SMAX3;
2683   case ISD::UMAX:
2684     return AMDGPUISD::UMAX3;
2685   case ISD::FMINNUM:
2686     return AMDGPUISD::FMIN3;
2687   case ISD::SMIN:
2688     return AMDGPUISD::SMIN3;
2689   case ISD::UMIN:
2690     return AMDGPUISD::UMIN3;
2691   default:
2692     llvm_unreachable("Not a min/max opcode");
2693   }
2694 }
2695 
2696 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
2697                                         SDValue Op0, SDValue Op1, bool Signed) {
2698   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
2699   if (!K1)
2700     return SDValue();
2701 
2702   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
2703   if (!K0)
2704     return SDValue();
2705 
2706   if (Signed) {
2707     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
2708       return SDValue();
2709   } else {
2710     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
2711       return SDValue();
2712   }
2713 
2714   EVT VT = K0->getValueType(0);
2715   return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT,
2716                      Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
2717 }
2718 
2719 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
2720   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
2721     return true;
2722 
2723   return DAG.isKnownNeverNaN(Op);
2724 }
2725 
2726 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
2727                                        SDValue Op0, SDValue Op1) {
2728   ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
2729   if (!K1)
2730     return SDValue();
2731 
2732   ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
2733   if (!K0)
2734     return SDValue();
2735 
2736   // Ordered >= (although NaN inputs should have folded away by now).
2737   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
2738   if (Cmp == APFloat::cmpGreaterThan)
2739     return SDValue();
2740 
2741   // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
2742   // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
2743   // give the other result, which is different from med3 with a NaN input.
2744   SDValue Var = Op0.getOperand(0);
2745   if (!isKnownNeverSNan(DAG, Var))
2746     return SDValue();
2747 
2748   return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
2749                      Var, SDValue(K0, 0), SDValue(K1, 0));
2750 }
2751 
2752 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
2753                                                DAGCombinerInfo &DCI) const {
2754   SelectionDAG &DAG = DCI.DAG;
2755 
2756   unsigned Opc = N->getOpcode();
2757   SDValue Op0 = N->getOperand(0);
2758   SDValue Op1 = N->getOperand(1);
2759 
2760   // Only do this if the inner op has one use since this will just increases
2761   // register pressure for no benefit.
2762 
2763   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) {
2764     // max(max(a, b), c) -> max3(a, b, c)
2765     // min(min(a, b), c) -> min3(a, b, c)
2766     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
2767       SDLoc DL(N);
2768       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2769                          DL,
2770                          N->getValueType(0),
2771                          Op0.getOperand(0),
2772                          Op0.getOperand(1),
2773                          Op1);
2774     }
2775 
2776     // Try commuted.
2777     // max(a, max(b, c)) -> max3(a, b, c)
2778     // min(a, min(b, c)) -> min3(a, b, c)
2779     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
2780       SDLoc DL(N);
2781       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
2782                          DL,
2783                          N->getValueType(0),
2784                          Op0,
2785                          Op1.getOperand(0),
2786                          Op1.getOperand(1));
2787     }
2788   }
2789 
2790   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
2791   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
2792     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
2793       return Med3;
2794   }
2795 
2796   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
2797     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
2798       return Med3;
2799   }
2800 
2801   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
2802   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
2803        (Opc == AMDGPUISD::FMIN_LEGACY &&
2804         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
2805       N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) {
2806     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
2807       return Res;
2808   }
2809 
2810   return SDValue();
2811 }
2812 
2813 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
2814                                               DAGCombinerInfo &DCI) const {
2815   SelectionDAG &DAG = DCI.DAG;
2816   SDLoc SL(N);
2817 
2818   SDValue LHS = N->getOperand(0);
2819   SDValue RHS = N->getOperand(1);
2820   EVT VT = LHS.getValueType();
2821 
2822   if (VT != MVT::f32 && VT != MVT::f64)
2823     return SDValue();
2824 
2825   // Match isinf pattern
2826   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
2827   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2828   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
2829     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
2830     if (!CRHS)
2831       return SDValue();
2832 
2833     const APFloat &APF = CRHS->getValueAPF();
2834     if (APF.isInfinity() && !APF.isNegative()) {
2835       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
2836       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
2837                          DAG.getConstant(Mask, SL, MVT::i32));
2838     }
2839   }
2840 
2841   return SDValue();
2842 }
2843 
2844 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
2845                                             DAGCombinerInfo &DCI) const {
2846   SelectionDAG &DAG = DCI.DAG;
2847   SDLoc DL(N);
2848 
2849   switch (N->getOpcode()) {
2850   default:
2851     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2852   case ISD::SETCC:
2853     return performSetCCCombine(N, DCI);
2854   case ISD::FMAXNUM:
2855   case ISD::FMINNUM:
2856   case ISD::SMAX:
2857   case ISD::SMIN:
2858   case ISD::UMAX:
2859   case ISD::UMIN:
2860   case AMDGPUISD::FMIN_LEGACY:
2861   case AMDGPUISD::FMAX_LEGACY: {
2862     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
2863         N->getValueType(0) != MVT::f64 &&
2864         getTargetMachine().getOptLevel() > CodeGenOpt::None)
2865       return performMinMaxCombine(N, DCI);
2866     break;
2867   }
2868 
2869   case AMDGPUISD::CVT_F32_UBYTE0:
2870   case AMDGPUISD::CVT_F32_UBYTE1:
2871   case AMDGPUISD::CVT_F32_UBYTE2:
2872   case AMDGPUISD::CVT_F32_UBYTE3: {
2873     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
2874     SDValue Src = N->getOperand(0);
2875 
2876     if (Src.getOpcode() == ISD::SRL) {
2877       // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
2878       // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
2879       // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
2880 
2881       if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {
2882         unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
2883         if (SrcOffset < 32 && SrcOffset % 8 == 0) {
2884           return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL,
2885                              MVT::f32, Src.getOperand(0));
2886         }
2887       }
2888     }
2889 
2890     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
2891 
2892     APInt KnownZero, KnownOne;
2893     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2894                                           !DCI.isBeforeLegalizeOps());
2895     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2896     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
2897         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
2898       DCI.CommitTargetLoweringOpt(TLO);
2899     }
2900 
2901     break;
2902   }
2903 
2904   case ISD::UINT_TO_FP: {
2905     return performUCharToFloatCombine(N, DCI);
2906   }
2907   case ISD::FADD: {
2908     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2909       break;
2910 
2911     EVT VT = N->getValueType(0);
2912     if (VT != MVT::f32)
2913       break;
2914 
2915     // Only do this if we are not trying to support denormals. v_mad_f32 does
2916     // not support denormals ever.
2917     if (Subtarget->hasFP32Denormals())
2918       break;
2919 
2920     SDValue LHS = N->getOperand(0);
2921     SDValue RHS = N->getOperand(1);
2922 
2923     // These should really be instruction patterns, but writing patterns with
2924     // source modiifiers is a pain.
2925 
2926     // fadd (fadd (a, a), b) -> mad 2.0, a, b
2927     if (LHS.getOpcode() == ISD::FADD) {
2928       SDValue A = LHS.getOperand(0);
2929       if (A == LHS.getOperand(1)) {
2930         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2931         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
2932       }
2933     }
2934 
2935     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
2936     if (RHS.getOpcode() == ISD::FADD) {
2937       SDValue A = RHS.getOperand(0);
2938       if (A == RHS.getOperand(1)) {
2939         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2940         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
2941       }
2942     }
2943 
2944     return SDValue();
2945   }
2946   case ISD::FSUB: {
2947     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
2948       break;
2949 
2950     EVT VT = N->getValueType(0);
2951 
2952     // Try to get the fneg to fold into the source modifier. This undoes generic
2953     // DAG combines and folds them into the mad.
2954     //
2955     // Only do this if we are not trying to support denormals. v_mad_f32 does
2956     // not support denormals ever.
2957     if (VT == MVT::f32 &&
2958         !Subtarget->hasFP32Denormals()) {
2959       SDValue LHS = N->getOperand(0);
2960       SDValue RHS = N->getOperand(1);
2961       if (LHS.getOpcode() == ISD::FADD) {
2962         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
2963 
2964         SDValue A = LHS.getOperand(0);
2965         if (A == LHS.getOperand(1)) {
2966           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
2967           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
2968 
2969           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
2970         }
2971       }
2972 
2973       if (RHS.getOpcode() == ISD::FADD) {
2974         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
2975 
2976         SDValue A = RHS.getOperand(0);
2977         if (A == RHS.getOperand(1)) {
2978           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
2979           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
2980         }
2981       }
2982 
2983       return SDValue();
2984     }
2985 
2986     break;
2987   }
2988   case ISD::LOAD:
2989   case ISD::STORE:
2990   case ISD::ATOMIC_LOAD:
2991   case ISD::ATOMIC_STORE:
2992   case ISD::ATOMIC_CMP_SWAP:
2993   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2994   case ISD::ATOMIC_SWAP:
2995   case ISD::ATOMIC_LOAD_ADD:
2996   case ISD::ATOMIC_LOAD_SUB:
2997   case ISD::ATOMIC_LOAD_AND:
2998   case ISD::ATOMIC_LOAD_OR:
2999   case ISD::ATOMIC_LOAD_XOR:
3000   case ISD::ATOMIC_LOAD_NAND:
3001   case ISD::ATOMIC_LOAD_MIN:
3002   case ISD::ATOMIC_LOAD_MAX:
3003   case ISD::ATOMIC_LOAD_UMIN:
3004   case ISD::ATOMIC_LOAD_UMAX:
3005   case AMDGPUISD::ATOMIC_INC:
3006   case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics.
3007     if (DCI.isBeforeLegalize())
3008       break;
3009 
3010     MemSDNode *MemNode = cast<MemSDNode>(N);
3011     SDValue Ptr = MemNode->getBasePtr();
3012 
3013     // TODO: We could also do this for multiplies.
3014     unsigned AS = MemNode->getAddressSpace();
3015     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3016       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3017       if (NewPtr) {
3018         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
3019 
3020         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3021         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
3022       }
3023     }
3024     break;
3025   }
3026   case ISD::AND:
3027     return performAndCombine(N, DCI);
3028   case ISD::OR:
3029     return performOrCombine(N, DCI);
3030   case AMDGPUISD::FP_CLASS:
3031     return performClassCombine(N, DCI);
3032   case ISD::FCANONICALIZE:
3033     return performFCanonicalizeCombine(N, DCI);
3034   case AMDGPUISD::FRACT:
3035   case AMDGPUISD::RCP:
3036   case AMDGPUISD::RSQ:
3037   case AMDGPUISD::RSQ_LEGACY:
3038   case AMDGPUISD::RSQ_CLAMP:
3039   case AMDGPUISD::LDEXP: {
3040     SDValue Src = N->getOperand(0);
3041     if (Src.isUndef())
3042       return Src;
3043     break;
3044   }
3045   }
3046   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
3047 }
3048 
3049 /// \brief Analyze the possible immediate value Op
3050 ///
3051 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
3052 /// and the immediate value if it's a literal immediate
3053 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
3054   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3055 
3056   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
3057     if (TII->isInlineConstant(Node->getAPIntValue()))
3058       return 0;
3059 
3060     uint64_t Val = Node->getZExtValue();
3061     return isUInt<32>(Val) ? Val : -1;
3062   }
3063 
3064   if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
3065     if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
3066       return 0;
3067 
3068     if (Node->getValueType(0) == MVT::f32)
3069       return FloatToBits(Node->getValueAPF().convertToFloat());
3070 
3071     return -1;
3072   }
3073 
3074   return -1;
3075 }
3076 
3077 /// \brief Helper function for adjustWritemask
3078 static unsigned SubIdx2Lane(unsigned Idx) {
3079   switch (Idx) {
3080   default: return 0;
3081   case AMDGPU::sub0: return 0;
3082   case AMDGPU::sub1: return 1;
3083   case AMDGPU::sub2: return 2;
3084   case AMDGPU::sub3: return 3;
3085   }
3086 }
3087 
3088 /// \brief Adjust the writemask of MIMG instructions
3089 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
3090                                        SelectionDAG &DAG) const {
3091   SDNode *Users[4] = { };
3092   unsigned Lane = 0;
3093   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
3094   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
3095   unsigned NewDmask = 0;
3096 
3097   // Try to figure out the used register components
3098   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
3099        I != E; ++I) {
3100 
3101     // Abort if we can't understand the usage
3102     if (!I->isMachineOpcode() ||
3103         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
3104       return;
3105 
3106     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
3107     // Note that subregs are packed, i.e. Lane==0 is the first bit set
3108     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
3109     // set, etc.
3110     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
3111 
3112     // Set which texture component corresponds to the lane.
3113     unsigned Comp;
3114     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
3115       assert(Dmask);
3116       Comp = countTrailingZeros(Dmask);
3117       Dmask &= ~(1 << Comp);
3118     }
3119 
3120     // Abort if we have more than one user per component
3121     if (Users[Lane])
3122       return;
3123 
3124     Users[Lane] = *I;
3125     NewDmask |= 1 << Comp;
3126   }
3127 
3128   // Abort if there's no change
3129   if (NewDmask == OldDmask)
3130     return;
3131 
3132   // Adjust the writemask in the node
3133   std::vector<SDValue> Ops;
3134   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
3135   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
3136   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
3137   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
3138 
3139   // If we only got one lane, replace it with a copy
3140   // (if NewDmask has only one bit set...)
3141   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
3142     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
3143                                        MVT::i32);
3144     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
3145                                       SDLoc(), Users[Lane]->getValueType(0),
3146                                       SDValue(Node, 0), RC);
3147     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
3148     return;
3149   }
3150 
3151   // Update the users of the node with the new indices
3152   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
3153 
3154     SDNode *User = Users[i];
3155     if (!User)
3156       continue;
3157 
3158     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
3159     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
3160 
3161     switch (Idx) {
3162     default: break;
3163     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
3164     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
3165     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
3166     }
3167   }
3168 }
3169 
3170 static bool isFrameIndexOp(SDValue Op) {
3171   if (Op.getOpcode() == ISD::AssertZext)
3172     Op = Op.getOperand(0);
3173 
3174   return isa<FrameIndexSDNode>(Op);
3175 }
3176 
3177 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
3178 /// with frame index operands.
3179 /// LLVM assumes that inputs are to these instructions are registers.
3180 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
3181                                                      SelectionDAG &DAG) const {
3182 
3183   SmallVector<SDValue, 8> Ops;
3184   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
3185     if (!isFrameIndexOp(Node->getOperand(i))) {
3186       Ops.push_back(Node->getOperand(i));
3187       continue;
3188     }
3189 
3190     SDLoc DL(Node);
3191     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
3192                                      Node->getOperand(i).getValueType(),
3193                                      Node->getOperand(i)), 0));
3194   }
3195 
3196   DAG.UpdateNodeOperands(Node, Ops);
3197 }
3198 
3199 /// \brief Fold the instructions after selecting them.
3200 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
3201                                           SelectionDAG &DAG) const {
3202   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3203   unsigned Opcode = Node->getMachineOpcode();
3204 
3205   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore())
3206     adjustWritemask(Node, DAG);
3207 
3208   if (Opcode == AMDGPU::INSERT_SUBREG ||
3209       Opcode == AMDGPU::REG_SEQUENCE) {
3210     legalizeTargetIndependentNode(Node, DAG);
3211     return Node;
3212   }
3213   return Node;
3214 }
3215 
3216 /// \brief Assign the register class depending on the number of
3217 /// bits set in the writemask
3218 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
3219                                                      SDNode *Node) const {
3220   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3221 
3222   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
3223 
3224   if (TII->isVOP3(MI->getOpcode())) {
3225     // Make sure constant bus requirements are respected.
3226     TII->legalizeOperandsVOP3(MRI, MI);
3227     return;
3228   }
3229 
3230   if (TII->isMIMG(*MI)) {
3231     unsigned VReg = MI->getOperand(0).getReg();
3232     unsigned DmaskIdx = MI->getNumOperands() == 12 ? 3 : 4;
3233     unsigned Writemask = MI->getOperand(DmaskIdx).getImm();
3234     unsigned BitsSet = 0;
3235     for (unsigned i = 0; i < 4; ++i)
3236       BitsSet += Writemask & (1 << i) ? 1 : 0;
3237 
3238     const TargetRegisterClass *RC;
3239     switch (BitsSet) {
3240     default: return;
3241     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
3242     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
3243     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
3244     }
3245 
3246     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
3247     MI->setDesc(TII->get(NewOpcode));
3248     MRI.setRegClass(VReg, RC);
3249     return;
3250   }
3251 
3252   // Replace unused atomics with the no return version.
3253   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
3254   if (NoRetAtomicOp != -1) {
3255     if (!Node->hasAnyUseOfValue(0)) {
3256       MI->setDesc(TII->get(NoRetAtomicOp));
3257       MI->RemoveOperand(0);
3258       return;
3259     }
3260 
3261     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
3262     // instruction, because the return type of these instructions is a vec2 of
3263     // the memory type, so it can be tied to the input operand.
3264     // This means these instructions always have a use, so we need to add a
3265     // special case to check if the atomic has only one extract_subreg use,
3266     // which itself has no uses.
3267     if ((Node->hasNUsesOfValue(1, 0) &&
3268          Node->use_begin()->isMachineOpcode() &&
3269          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
3270          !Node->use_begin()->hasAnyUseOfValue(0))) {
3271       unsigned Def = MI->getOperand(0).getReg();
3272 
3273       // Change this into a noret atomic.
3274       MI->setDesc(TII->get(NoRetAtomicOp));
3275       MI->RemoveOperand(0);
3276 
3277       // If we only remove the def operand from the atomic instruction, the
3278       // extract_subreg will be left with a use of a vreg without a def.
3279       // So we need to insert an implicit_def to avoid machine verifier
3280       // errors.
3281       BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
3282               TII->get(AMDGPU::IMPLICIT_DEF), Def);
3283     }
3284     return;
3285   }
3286 }
3287 
3288 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
3289                               uint64_t Val) {
3290   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
3291   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
3292 }
3293 
3294 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
3295                                                 const SDLoc &DL,
3296                                                 SDValue Ptr) const {
3297   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3298 
3299   // Build the half of the subregister with the constants before building the
3300   // full 128-bit register. If we are building multiple resource descriptors,
3301   // this will allow CSEing of the 2-component register.
3302   const SDValue Ops0[] = {
3303     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
3304     buildSMovImm32(DAG, DL, 0),
3305     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
3306     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
3307     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
3308   };
3309 
3310   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
3311                                                 MVT::v2i32, Ops0), 0);
3312 
3313   // Combine the constants and the pointer.
3314   const SDValue Ops1[] = {
3315     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
3316     Ptr,
3317     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
3318     SubRegHi,
3319     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
3320   };
3321 
3322   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
3323 }
3324 
3325 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
3326 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
3327 ///        of the resource descriptor) to create an offset, which is added to
3328 ///        the resource pointer.
3329 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
3330                                            SDValue Ptr, uint32_t RsrcDword1,
3331                                            uint64_t RsrcDword2And3) const {
3332   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
3333   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
3334   if (RsrcDword1) {
3335     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
3336                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
3337                     0);
3338   }
3339 
3340   SDValue DataLo = buildSMovImm32(DAG, DL,
3341                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
3342   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
3343 
3344   const SDValue Ops[] = {
3345     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
3346     PtrLo,
3347     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
3348     PtrHi,
3349     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
3350     DataLo,
3351     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
3352     DataHi,
3353     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
3354   };
3355 
3356   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
3357 }
3358 
3359 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
3360                                                const TargetRegisterClass *RC,
3361                                                unsigned Reg, EVT VT) const {
3362   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
3363 
3364   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
3365                             cast<RegisterSDNode>(VReg)->getReg(), VT);
3366 }
3367 
3368 //===----------------------------------------------------------------------===//
3369 //                         SI Inline Assembly Support
3370 //===----------------------------------------------------------------------===//
3371 
3372 std::pair<unsigned, const TargetRegisterClass *>
3373 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3374                                                StringRef Constraint,
3375                                                MVT VT) const {
3376 
3377   if (Constraint.size() == 1) {
3378     switch (Constraint[0]) {
3379     case 's':
3380     case 'r':
3381       switch (VT.getSizeInBits()) {
3382       default:
3383         return std::make_pair(0U, nullptr);
3384       case 32:
3385         return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
3386       case 64:
3387         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
3388       case 128:
3389         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
3390       case 256:
3391         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
3392       }
3393 
3394     case 'v':
3395       switch (VT.getSizeInBits()) {
3396       default:
3397         return std::make_pair(0U, nullptr);
3398       case 32:
3399         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
3400       case 64:
3401         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
3402       case 96:
3403         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
3404       case 128:
3405         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
3406       case 256:
3407         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
3408       case 512:
3409         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
3410       }
3411     }
3412   }
3413 
3414   if (Constraint.size() > 1) {
3415     const TargetRegisterClass *RC = nullptr;
3416     if (Constraint[1] == 'v') {
3417       RC = &AMDGPU::VGPR_32RegClass;
3418     } else if (Constraint[1] == 's') {
3419       RC = &AMDGPU::SGPR_32RegClass;
3420     }
3421 
3422     if (RC) {
3423       uint32_t Idx;
3424       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
3425       if (!Failed && Idx < RC->getNumRegs())
3426         return std::make_pair(RC->getRegister(Idx), RC);
3427     }
3428   }
3429   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3430 }
3431 
3432 SITargetLowering::ConstraintType
3433 SITargetLowering::getConstraintType(StringRef Constraint) const {
3434   if (Constraint.size() == 1) {
3435     switch (Constraint[0]) {
3436     default: break;
3437     case 's':
3438     case 'v':
3439       return C_RegisterClass;
3440     }
3441   }
3442   return TargetLowering::getConstraintType(Constraint);
3443 }
3444