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