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