AMDGPU: Rename enums to be consistent with HSA code object terminology
[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
111   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Legal);
112   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
113   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
114
115   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Legal);
116   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
117   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
118
119   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Legal);
120   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
122
123   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
125
126   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
127   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
128   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v16i8, Custom);
129   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
130
131   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
132   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
133
134   for (MVT VT : MVT::integer_valuetypes()) {
135     if (VT == MVT::i64)
136       continue;
137
138     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
139     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Legal);
140     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Legal);
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
142
143     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
144     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i8, Legal);
145     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i16, Legal);
146     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i32, Expand);
147
148     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
149     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i8, Legal);
150     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i16, Legal);
151     setLoadExtAction(ISD::EXTLOAD, VT, MVT::i32, Expand);
152   }
153
154   for (MVT VT : MVT::integer_vector_valuetypes()) {
155     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i16, Expand);
156     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v16i16, Expand);
157   }
158
159   for (MVT VT : MVT::fp_valuetypes())
160     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
161
162   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f16, Expand);
163   setLoadExtAction(ISD::EXTLOAD, MVT::v2f64, MVT::v2f32, Expand);
164
165   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
166   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
167   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
168   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
169
170
171   setTruncStoreAction(MVT::v2i64, MVT::v2i32, Expand);
172
173   setTruncStoreAction(MVT::v2f64, MVT::v2f32, Expand);
174   setTruncStoreAction(MVT::v2f64, MVT::v2f16, Expand);
175
176   setOperationAction(ISD::LOAD, MVT::i1, Custom);
177
178   setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
179   AddPromotedToType(ISD::LOAD, MVT::v2i64, MVT::v4i32);
180
181   setOperationAction(ISD::STORE, MVT::v2i64, Promote);
182   AddPromotedToType(ISD::STORE, MVT::v2i64, MVT::v4i32);
183
184   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
185
186   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
187   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
188   setOperationAction(ISD::FrameIndex, MVT::i32, Custom);
189
190   // These should use UDIVREM, so set them to expand
191   setOperationAction(ISD::UDIV, MVT::i64, Expand);
192   setOperationAction(ISD::UREM, MVT::i64, Expand);
193
194   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
195   setOperationAction(ISD::SELECT, MVT::i1, Promote);
196
197   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
198
199
200   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
201
202   // We only support LOAD/STORE and vector manipulation ops for vectors
203   // with > 4 elements.
204   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
205     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
206       switch(Op) {
207       case ISD::LOAD:
208       case ISD::STORE:
209       case ISD::BUILD_VECTOR:
210       case ISD::BITCAST:
211       case ISD::EXTRACT_VECTOR_ELT:
212       case ISD::INSERT_VECTOR_ELT:
213       case ISD::INSERT_SUBVECTOR:
214       case ISD::EXTRACT_SUBVECTOR:
215       case ISD::SCALAR_TO_VECTOR:
216         break;
217       case ISD::CONCAT_VECTORS:
218         setOperationAction(Op, VT, Custom);
219         break;
220       default:
221         setOperationAction(Op, VT, Expand);
222         break;
223       }
224     }
225   }
226
227   // Most operations are naturally 32-bit vector operations. We only support
228   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
229   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
230     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
231     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
232
233     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
234     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
235
236     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
237     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
238
239     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
240     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
241   }
242
243   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
244     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
245     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
246     setOperationAction(ISD::FRINT, MVT::f64, Legal);
247   }
248
249   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
250   setOperationAction(ISD::FDIV, MVT::f32, Custom);
251   setOperationAction(ISD::FDIV, MVT::f64, Custom);
252
253   setTargetDAGCombine(ISD::FADD);
254   setTargetDAGCombine(ISD::FSUB);
255   setTargetDAGCombine(ISD::FMINNUM);
256   setTargetDAGCombine(ISD::FMAXNUM);
257   setTargetDAGCombine(ISD::SMIN);
258   setTargetDAGCombine(ISD::SMAX);
259   setTargetDAGCombine(ISD::UMIN);
260   setTargetDAGCombine(ISD::UMAX);
261   setTargetDAGCombine(ISD::SELECT_CC);
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 TargetLoweringBase::LegalizeTypeAction
496 SITargetLowering::getPreferredVectorAction(EVT VT) const {
497   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
498     return TypeSplitVector;
499
500   return TargetLoweringBase::getPreferredVectorAction(VT);
501 }
502
503 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
504                                                          Type *Ty) const {
505   const SIInstrInfo *TII =
506       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
507   return TII->isInlineConstant(Imm);
508 }
509
510 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
511                                          SDLoc SL, SDValue Chain,
512                                          unsigned Offset, bool Signed) const {
513   const DataLayout &DL = DAG.getDataLayout();
514   MachineFunction &MF = DAG.getMachineFunction();
515   const SIRegisterInfo *TRI =
516       static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
517   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
518
519   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
520
521   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
522   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
523   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
524   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
525                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
526   SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
527                             DAG.getConstant(Offset, SL, PtrVT));
528   SDValue PtrOffset = DAG.getUNDEF(PtrVT);
529   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
530
531   unsigned Align = DL.getABITypeAlignment(Ty);
532
533   ISD::LoadExtType ExtTy = Signed ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
534   if (MemVT.isFloatingPoint())
535     ExtTy = ISD::EXTLOAD;
536
537   return DAG.getLoad(ISD::UNINDEXED, ExtTy,
538                      VT, SL, Chain, Ptr, PtrOffset, PtrInfo, MemVT,
539                      false, // isVolatile
540                      true, // isNonTemporal
541                      true, // isInvariant
542                      Align); // Alignment
543 }
544
545 SDValue SITargetLowering::LowerFormalArguments(
546     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
547     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
548     SmallVectorImpl<SDValue> &InVals) const {
549   const SIRegisterInfo *TRI =
550       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
551
552   MachineFunction &MF = DAG.getMachineFunction();
553   FunctionType *FType = MF.getFunction()->getFunctionType();
554   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
555   const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
556
557   if (Subtarget->isAmdHsaOS() && Info->getShaderType() != ShaderType::COMPUTE) {
558     const Function *Fn = MF.getFunction();
559     DiagnosticInfoUnsupported NoGraphicsHSA(*Fn, "non-compute shaders with HSA");
560     DAG.getContext()->diagnose(NoGraphicsHSA);
561     return SDValue();
562   }
563
564   // FIXME: We currently assume all calling conventions are kernels.
565
566   SmallVector<ISD::InputArg, 16> Splits;
567   BitVector Skipped(Ins.size());
568
569   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
570     const ISD::InputArg &Arg = Ins[i];
571
572     // First check if it's a PS input addr
573     if (Info->getShaderType() == ShaderType::PIXEL && !Arg.Flags.isInReg() &&
574         !Arg.Flags.isByVal()) {
575
576       assert((PSInputNum <= 15) && "Too many PS inputs!");
577
578       if (!Arg.Used) {
579         // We can safely skip PS inputs
580         Skipped.set(i);
581         ++PSInputNum;
582         continue;
583       }
584
585       Info->PSInputAddr |= 1 << PSInputNum++;
586     }
587
588     // Second split vertices into their elements
589     if (Info->getShaderType() != ShaderType::COMPUTE && Arg.VT.isVector()) {
590       ISD::InputArg NewArg = Arg;
591       NewArg.Flags.setSplit();
592       NewArg.VT = Arg.VT.getVectorElementType();
593
594       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
595       // three or five element vertex only needs three or five registers,
596       // NOT four or eight.
597       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
598       unsigned NumElements = ParamType->getVectorNumElements();
599
600       for (unsigned j = 0; j != NumElements; ++j) {
601         Splits.push_back(NewArg);
602         NewArg.PartOffset += NewArg.VT.getStoreSize();
603       }
604
605     } else if (Info->getShaderType() != ShaderType::COMPUTE) {
606       Splits.push_back(Arg);
607     }
608   }
609
610   SmallVector<CCValAssign, 16> ArgLocs;
611   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
612                  *DAG.getContext());
613
614   // At least one interpolation mode must be enabled or else the GPU will hang.
615   if (Info->getShaderType() == ShaderType::PIXEL &&
616       (Info->PSInputAddr & 0x7F) == 0) {
617     Info->PSInputAddr |= 1;
618     CCInfo.AllocateReg(AMDGPU::VGPR0);
619     CCInfo.AllocateReg(AMDGPU::VGPR1);
620   }
621
622   // The pointer to the list of arguments is stored in SGPR0, SGPR1
623   // The pointer to the scratch buffer is stored in SGPR2, SGPR3
624   if (Info->getShaderType() == ShaderType::COMPUTE) {
625     if (Subtarget->isAmdHsaOS())
626       Info->NumUserSGPRs += 4;  // FIXME: Need to support scratch buffers.
627     else
628       Info->NumUserSGPRs += 4;
629
630     unsigned InputPtrReg =
631         TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
632     unsigned InputPtrRegLo =
633         TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 0);
634     unsigned InputPtrRegHi =
635         TRI->getPhysRegSubReg(InputPtrReg, &AMDGPU::SReg_32RegClass, 1);
636
637     CCInfo.AllocateReg(InputPtrRegLo);
638     CCInfo.AllocateReg(InputPtrRegHi);
639     MF.addLiveIn(InputPtrReg, &AMDGPU::SReg_64RegClass);
640
641     const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
642
643     if (MFI->hasDispatchPtr()) {
644       unsigned DispatchPtrReg
645         = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR);
646       MF.addLiveIn(DispatchPtrReg, &AMDGPU::SReg_64RegClass);
647     }
648   }
649
650   if (Info->getShaderType() == ShaderType::COMPUTE) {
651     getOriginalFunctionArgs(DAG, DAG.getMachineFunction().getFunction(), Ins,
652                             Splits);
653   }
654
655   AnalyzeFormalArguments(CCInfo, Splits);
656
657   SmallVector<SDValue, 16> Chains;
658
659   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
660
661     const ISD::InputArg &Arg = Ins[i];
662     if (Skipped[i]) {
663       InVals.push_back(DAG.getUNDEF(Arg.VT));
664       continue;
665     }
666
667     CCValAssign &VA = ArgLocs[ArgIdx++];
668     MVT VT = VA.getLocVT();
669
670     if (VA.isMemLoc()) {
671       VT = Ins[i].VT;
672       EVT MemVT = Splits[i].VT;
673       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
674                               VA.getLocMemOffset();
675       // The first 36 bytes of the input buffer contains information about
676       // thread group and global sizes.
677       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
678                                    Offset, Ins[i].Flags.isSExt());
679       Chains.push_back(Arg.getValue(1));
680
681       auto *ParamTy =
682         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
683       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
684           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
685         // On SI local pointers are just offsets into LDS, so they are always
686         // less than 16-bits.  On CI and newer they could potentially be
687         // real pointers, so we can't guarantee their size.
688         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
689                           DAG.getValueType(MVT::i16));
690       }
691
692       InVals.push_back(Arg);
693       Info->ABIArgOffset = Offset + MemVT.getStoreSize();
694       continue;
695     }
696     assert(VA.isRegLoc() && "Parameter must be in a register!");
697
698     unsigned Reg = VA.getLocReg();
699
700     if (VT == MVT::i64) {
701       // For now assume it is a pointer
702       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
703                                      &AMDGPU::SReg_64RegClass);
704       Reg = MF.addLiveIn(Reg, &AMDGPU::SReg_64RegClass);
705       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
706       InVals.push_back(Copy);
707       continue;
708     }
709
710     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
711
712     Reg = MF.addLiveIn(Reg, RC);
713     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
714
715     if (Arg.VT.isVector()) {
716
717       // Build a vector from the registers
718       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
719       unsigned NumElements = ParamType->getVectorNumElements();
720
721       SmallVector<SDValue, 4> Regs;
722       Regs.push_back(Val);
723       for (unsigned j = 1; j != NumElements; ++j) {
724         Reg = ArgLocs[ArgIdx++].getLocReg();
725         Reg = MF.addLiveIn(Reg, RC);
726
727         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
728         Regs.push_back(Copy);
729       }
730
731       // Fill up the missing vector elements
732       NumElements = Arg.VT.getVectorNumElements() - NumElements;
733       Regs.append(NumElements, DAG.getUNDEF(VT));
734
735       InVals.push_back(DAG.getNode(ISD::BUILD_VECTOR, DL, Arg.VT, Regs));
736       continue;
737     }
738
739     InVals.push_back(Val);
740   }
741
742   if (Info->getShaderType() != ShaderType::COMPUTE) {
743     unsigned ScratchIdx = CCInfo.getFirstUnallocated(makeArrayRef(
744         AMDGPU::SGPR_32RegClass.begin(), AMDGPU::SGPR_32RegClass.getNumRegs()));
745     Info->ScratchOffsetReg = AMDGPU::SGPR_32RegClass.getRegister(ScratchIdx);
746   }
747
748   if (MF.getFrameInfo()->hasStackObjects() || ST.isVGPRSpillingEnabled(Info))
749     Info->setScratchRSrcReg(TRI);
750
751   if (Chains.empty())
752     return Chain;
753
754   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
755 }
756
757 MachineBasicBlock * SITargetLowering::EmitInstrWithCustomInserter(
758     MachineInstr * MI, MachineBasicBlock * BB) const {
759
760   MachineBasicBlock::iterator I = *MI;
761   const SIInstrInfo *TII =
762       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
763
764   switch (MI->getOpcode()) {
765   default:
766     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
767   case AMDGPU::BRANCH:
768     return BB;
769   case AMDGPU::SI_RegisterStorePseudo: {
770     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
771     unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
772     MachineInstrBuilder MIB =
773         BuildMI(*BB, I, MI->getDebugLoc(), TII->get(AMDGPU::SI_RegisterStore),
774                 Reg);
775     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
776       MIB.addOperand(MI->getOperand(i));
777
778     MI->eraseFromParent();
779     break;
780   }
781   }
782   return BB;
783 }
784
785 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
786   // This currently forces unfolding various combinations of fsub into fma with
787   // free fneg'd operands. As long as we have fast FMA (controlled by
788   // isFMAFasterThanFMulAndFAdd), we should perform these.
789
790   // When fma is quarter rate, for f64 where add / sub are at best half rate,
791   // most of these combines appear to be cycle neutral but save on instruction
792   // count / code size.
793   return true;
794 }
795
796 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
797                                          EVT VT) const {
798   if (!VT.isVector()) {
799     return MVT::i1;
800   }
801   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
802 }
803
804 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
805   return MVT::i32;
806 }
807
808 // Answering this is somewhat tricky and depends on the specific device which
809 // have different rates for fma or all f64 operations.
810 //
811 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
812 // regardless of which device (although the number of cycles differs between
813 // devices), so it is always profitable for f64.
814 //
815 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
816 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
817 // which we can always do even without fused FP ops since it returns the same
818 // result as the separate operations and since it is always full
819 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
820 // however does not support denormals, so we do report fma as faster if we have
821 // a fast fma device and require denormals.
822 //
823 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
824   VT = VT.getScalarType();
825
826   if (!VT.isSimple())
827     return false;
828
829   switch (VT.getSimpleVT().SimpleTy) {
830   case MVT::f32:
831     // This is as fast on some subtargets. However, we always have full rate f32
832     // mad available which returns the same result as the separate operations
833     // which we should prefer over fma. We can't use this if we want to support
834     // denormals, so only report this in these cases.
835     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
836   case MVT::f64:
837     return true;
838   default:
839     break;
840   }
841
842   return false;
843 }
844
845 //===----------------------------------------------------------------------===//
846 // Custom DAG Lowering Operations
847 //===----------------------------------------------------------------------===//
848
849 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
850   switch (Op.getOpcode()) {
851   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
852   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
853   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
854   case ISD::LOAD: {
855     SDValue Result = LowerLOAD(Op, DAG);
856     assert((!Result.getNode() ||
857             Result.getNode()->getNumValues() == 2) &&
858            "Load should return a value and a chain");
859     return Result;
860   }
861
862   case ISD::FSIN:
863   case ISD::FCOS:
864     return LowerTrig(Op, DAG);
865   case ISD::SELECT: return LowerSELECT(Op, DAG);
866   case ISD::FDIV: return LowerFDIV(Op, DAG);
867   case ISD::STORE: return LowerSTORE(Op, DAG);
868   case ISD::GlobalAddress: {
869     MachineFunction &MF = DAG.getMachineFunction();
870     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
871     return LowerGlobalAddress(MFI, Op, DAG);
872   }
873   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
874   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
875   }
876   return SDValue();
877 }
878
879 /// \brief Helper function for LowerBRCOND
880 static SDNode *findUser(SDValue Value, unsigned Opcode) {
881
882   SDNode *Parent = Value.getNode();
883   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
884        I != E; ++I) {
885
886     if (I.getUse().get() != Value)
887       continue;
888
889     if (I->getOpcode() == Opcode)
890       return *I;
891   }
892   return nullptr;
893 }
894
895 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
896
897   SDLoc SL(Op);
898   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
899   unsigned FrameIndex = FINode->getIndex();
900
901   // A FrameIndex node represents a 32-bit offset into scratch memory.  If
902   // the high bit of a frame index offset were to be set, this would mean
903   // that it represented an offset of ~2GB * 64 = ~128GB from the start of the
904   // scratch buffer, with 64 being the number of threads per wave.
905   //
906   // If we know the machine uses less than 128GB of scratch, then we can
907   // amrk the high bit of the FrameIndex node as known zero,
908   // which is important, because it means in most situations we can
909   // prove that values derived from FrameIndex nodes are non-negative.
910   // This enables us to take advantage of more addressing modes when
911   // accessing scratch buffers, since for scratch reads/writes, the register
912   // offset must always be positive.
913
914   SDValue TFI = DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
915   if (Subtarget->enableHugeScratchBuffer())
916     return TFI;
917
918   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, TFI,
919                     DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), 31)));
920 }
921
922 /// This transforms the control flow intrinsics to get the branch destination as
923 /// last parameter, also switches branch target with BR if the need arise
924 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
925                                       SelectionDAG &DAG) const {
926
927   SDLoc DL(BRCOND);
928
929   SDNode *Intr = BRCOND.getOperand(1).getNode();
930   SDValue Target = BRCOND.getOperand(2);
931   SDNode *BR = nullptr;
932
933   if (Intr->getOpcode() == ISD::SETCC) {
934     // As long as we negate the condition everything is fine
935     SDNode *SetCC = Intr;
936     assert(SetCC->getConstantOperandVal(1) == 1);
937     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
938            ISD::SETNE);
939     Intr = SetCC->getOperand(0).getNode();
940
941   } else {
942     // Get the target from BR if we don't negate the condition
943     BR = findUser(BRCOND, ISD::BR);
944     Target = BR->getOperand(1);
945   }
946
947   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
948
949   // Build the result and
950   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
951
952   // operands of the new intrinsic call
953   SmallVector<SDValue, 4> Ops;
954   Ops.push_back(BRCOND.getOperand(0));
955   Ops.append(Intr->op_begin() + 1, Intr->op_end());
956   Ops.push_back(Target);
957
958   // build the new intrinsic call
959   SDNode *Result = DAG.getNode(
960     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
961     DAG.getVTList(Res), Ops).getNode();
962
963   if (BR) {
964     // Give the branch instruction our target
965     SDValue Ops[] = {
966       BR->getOperand(0),
967       BRCOND.getOperand(2)
968     };
969     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
970     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
971     BR = NewBR.getNode();
972   }
973
974   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
975
976   // Copy the intrinsic results to registers
977   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
978     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
979     if (!CopyToReg)
980       continue;
981
982     Chain = DAG.getCopyToReg(
983       Chain, DL,
984       CopyToReg->getOperand(1),
985       SDValue(Result, i - 1),
986       SDValue());
987
988     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
989   }
990
991   // Remove the old intrinsic from the chain
992   DAG.ReplaceAllUsesOfValueWith(
993     SDValue(Intr, Intr->getNumValues() - 1),
994     Intr->getOperand(0));
995
996   return Chain;
997 }
998
999 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
1000                                              SDValue Op,
1001                                              SelectionDAG &DAG) const {
1002   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
1003
1004   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
1005     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
1006
1007   SDLoc DL(GSD);
1008   const GlobalValue *GV = GSD->getGlobal();
1009   MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
1010
1011   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
1012   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
1013
1014   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
1015                               DAG.getConstant(0, DL, MVT::i32));
1016   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
1017                               DAG.getConstant(1, DL, MVT::i32));
1018
1019   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
1020                            PtrLo, GA);
1021   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
1022                            PtrHi, DAG.getConstant(0, DL, MVT::i32),
1023                            SDValue(Lo.getNode(), 1));
1024   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
1025 }
1026
1027 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
1028                                    SDValue V) const {
1029   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
1030   // so we will end up with redundant moves to m0.
1031   //
1032   // We can't use S_MOV_B32, because there is no way to specify m0 as the
1033   // destination register.
1034   //
1035   // We have to use them both.  Machine cse will combine all the S_MOV_B32
1036   // instructions and the register coalescer eliminate the extra copies.
1037   SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
1038   return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
1039                           SDValue(M0, 0), SDValue()); // Glue
1040                                                       // A Null SDValue creates
1041                                                       // a glue result.
1042 }
1043
1044 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
1045                                                  SDValue Op,
1046                                                  MVT VT,
1047                                                  unsigned Offset) const {
1048   SDLoc SL(Op);
1049   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
1050                                  DAG.getEntryNode(), Offset, false);
1051   // The local size values will have the hi 16-bits as zero.
1052   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
1053                      DAG.getValueType(VT));
1054 }
1055
1056 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
1057                                                   SelectionDAG &DAG) const {
1058   MachineFunction &MF = DAG.getMachineFunction();
1059   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
1060   const SIRegisterInfo *TRI =
1061       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
1062
1063   EVT VT = Op.getValueType();
1064   SDLoc DL(Op);
1065   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1066
1067   // TODO: Should this propagate fast-math-flags?
1068
1069   switch (IntrinsicID) {
1070   case Intrinsic::amdgcn_dispatch_ptr:
1071     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
1072       TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_PTR), VT);
1073
1074   case Intrinsic::r600_read_ngroups_x:
1075     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1076                           SI::KernelInputOffsets::NGROUPS_X, false);
1077   case Intrinsic::r600_read_ngroups_y:
1078     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1079                           SI::KernelInputOffsets::NGROUPS_Y, false);
1080   case Intrinsic::r600_read_ngroups_z:
1081     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1082                           SI::KernelInputOffsets::NGROUPS_Z, false);
1083   case Intrinsic::r600_read_global_size_x:
1084     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1085                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
1086   case Intrinsic::r600_read_global_size_y:
1087     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1088                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
1089   case Intrinsic::r600_read_global_size_z:
1090     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
1091                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
1092   case Intrinsic::r600_read_local_size_x:
1093     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1094                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
1095   case Intrinsic::r600_read_local_size_y:
1096     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1097                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
1098   case Intrinsic::r600_read_local_size_z:
1099     return lowerImplicitZextParam(DAG, Op, MVT::i16,
1100                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
1101   case Intrinsic::AMDGPU_read_workdim:
1102     // Really only 2 bits.
1103     return lowerImplicitZextParam(DAG, Op, MVT::i8,
1104                                   getImplicitParameterOffset(MFI, GRID_DIM));
1105   case Intrinsic::r600_read_tgid_x:
1106     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1107       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
1108   case Intrinsic::r600_read_tgid_y:
1109     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1110       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
1111   case Intrinsic::r600_read_tgid_z:
1112     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
1113       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
1114   case Intrinsic::r600_read_tidig_x:
1115     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1116       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
1117   case Intrinsic::r600_read_tidig_y:
1118     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1119       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
1120   case Intrinsic::r600_read_tidig_z:
1121     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
1122       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
1123   case AMDGPUIntrinsic::SI_load_const: {
1124     SDValue Ops[] = {
1125       Op.getOperand(1),
1126       Op.getOperand(2)
1127     };
1128
1129     MachineMemOperand *MMO = MF.getMachineMemOperand(
1130       MachinePointerInfo(),
1131       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
1132       VT.getStoreSize(), 4);
1133     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1134                                    Op->getVTList(), Ops, VT, MMO);
1135   }
1136   case AMDGPUIntrinsic::SI_sample:
1137     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1138   case AMDGPUIntrinsic::SI_sampleb:
1139     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1140   case AMDGPUIntrinsic::SI_sampled:
1141     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1142   case AMDGPUIntrinsic::SI_samplel:
1143     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1144   case AMDGPUIntrinsic::SI_vs_load_input:
1145     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1146                        Op.getOperand(1),
1147                        Op.getOperand(2),
1148                        Op.getOperand(3));
1149
1150   case AMDGPUIntrinsic::AMDGPU_fract:
1151   case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1152     return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1153                        DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1154   case AMDGPUIntrinsic::SI_fs_constant: {
1155     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1156     SDValue Glue = M0.getValue(1);
1157     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1158                        DAG.getConstant(2, DL, MVT::i32), // P0
1159                        Op.getOperand(1), Op.getOperand(2), Glue);
1160   }
1161   case AMDGPUIntrinsic::SI_packf16:
1162     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
1163       return DAG.getUNDEF(MVT::i32);
1164     return Op;
1165   case AMDGPUIntrinsic::SI_fs_interp: {
1166     SDValue IJ = Op.getOperand(4);
1167     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1168                             DAG.getConstant(0, DL, MVT::i32));
1169     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1170                             DAG.getConstant(1, DL, MVT::i32));
1171     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1172     SDValue Glue = M0.getValue(1);
1173     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1174                              DAG.getVTList(MVT::f32, MVT::Glue),
1175                              I, Op.getOperand(1), Op.getOperand(2), Glue);
1176     Glue = SDValue(P1.getNode(), 1);
1177     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1178                              Op.getOperand(1), Op.getOperand(2), Glue);
1179   }
1180   default:
1181     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1182   }
1183 }
1184
1185 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1186                                               SelectionDAG &DAG) const {
1187   MachineFunction &MF = DAG.getMachineFunction();
1188   SDLoc DL(Op);
1189   SDValue Chain = Op.getOperand(0);
1190   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1191
1192   switch (IntrinsicID) {
1193   case AMDGPUIntrinsic::SI_sendmsg: {
1194     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1195     SDValue Glue = Chain.getValue(1);
1196     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1197                        Op.getOperand(2), Glue);
1198   }
1199   case AMDGPUIntrinsic::SI_tbuffer_store: {
1200     SDValue Ops[] = {
1201       Chain,
1202       Op.getOperand(2),
1203       Op.getOperand(3),
1204       Op.getOperand(4),
1205       Op.getOperand(5),
1206       Op.getOperand(6),
1207       Op.getOperand(7),
1208       Op.getOperand(8),
1209       Op.getOperand(9),
1210       Op.getOperand(10),
1211       Op.getOperand(11),
1212       Op.getOperand(12),
1213       Op.getOperand(13),
1214       Op.getOperand(14)
1215     };
1216
1217     EVT VT = Op.getOperand(3).getValueType();
1218
1219     MachineMemOperand *MMO = MF.getMachineMemOperand(
1220       MachinePointerInfo(),
1221       MachineMemOperand::MOStore,
1222       VT.getStoreSize(), 4);
1223     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1224                                    Op->getVTList(), Ops, VT, MMO);
1225   }
1226   default:
1227     return SDValue();
1228   }
1229 }
1230
1231 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1232   SDLoc DL(Op);
1233   LoadSDNode *Load = cast<LoadSDNode>(Op);
1234
1235   if (Op.getValueType().isVector()) {
1236     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1237            "Custom lowering for non-i32 vectors hasn't been implemented.");
1238     unsigned NumElements = Op.getValueType().getVectorNumElements();
1239     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1240
1241     switch (Load->getAddressSpace()) {
1242       default: break;
1243       case AMDGPUAS::GLOBAL_ADDRESS:
1244       case AMDGPUAS::PRIVATE_ADDRESS:
1245         if (NumElements >= 8)
1246           return SplitVectorLoad(Op, DAG);
1247
1248         // v4 loads are supported for private and global memory.
1249         if (NumElements <= 4)
1250           break;
1251         // fall-through
1252       case AMDGPUAS::LOCAL_ADDRESS:
1253         // If properly aligned, if we split we might be able to use ds_read_b64.
1254         return SplitVectorLoad(Op, DAG);
1255     }
1256   }
1257
1258   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1259 }
1260
1261 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1262                                                const SDValue &Op,
1263                                                SelectionDAG &DAG) const {
1264   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1265                      Op.getOperand(2),
1266                      Op.getOperand(3),
1267                      Op.getOperand(4));
1268 }
1269
1270 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1271   if (Op.getValueType() != MVT::i64)
1272     return SDValue();
1273
1274   SDLoc DL(Op);
1275   SDValue Cond = Op.getOperand(0);
1276
1277   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1278   SDValue One = DAG.getConstant(1, DL, MVT::i32);
1279
1280   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1281   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1282
1283   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1284   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1285
1286   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1287
1288   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1289   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1290
1291   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1292
1293   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1294   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1295 }
1296
1297 // Catch division cases where we can use shortcuts with rcp and rsq
1298 // instructions.
1299 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1300   SDLoc SL(Op);
1301   SDValue LHS = Op.getOperand(0);
1302   SDValue RHS = Op.getOperand(1);
1303   EVT VT = Op.getValueType();
1304   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1305
1306   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1307     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1308         CLHS->isExactlyValue(1.0)) {
1309       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1310       // the CI documentation has a worst case error of 1 ulp.
1311       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1312       // use it as long as we aren't trying to use denormals.
1313
1314       // 1.0 / sqrt(x) -> rsq(x)
1315       //
1316       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1317       // error seems really high at 2^29 ULP.
1318       if (RHS.getOpcode() == ISD::FSQRT)
1319         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1320
1321       // 1.0 / x -> rcp(x)
1322       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1323     }
1324   }
1325
1326   if (Unsafe) {
1327     // Turn into multiply by the reciprocal.
1328     // x / y -> x * (1.0 / y)
1329     SDNodeFlags Flags;
1330     Flags.setUnsafeAlgebra(true);
1331     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1332     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
1333   }
1334
1335   return SDValue();
1336 }
1337
1338 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1339   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1340   if (FastLowered.getNode())
1341     return FastLowered;
1342
1343   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1344   // selection error for now rather than do something incorrect.
1345   if (Subtarget->hasFP32Denormals())
1346     return SDValue();
1347
1348   SDLoc SL(Op);
1349   SDValue LHS = Op.getOperand(0);
1350   SDValue RHS = Op.getOperand(1);
1351
1352   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1353
1354   const APFloat K0Val(BitsToFloat(0x6f800000));
1355   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1356
1357   const APFloat K1Val(BitsToFloat(0x2f800000));
1358   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1359
1360   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1361
1362   EVT SetCCVT =
1363       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1364
1365   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1366
1367   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1368
1369   // TODO: Should this propagate fast-math-flags?
1370
1371   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1372
1373   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1374
1375   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1376
1377   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1378 }
1379
1380 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1381   if (DAG.getTarget().Options.UnsafeFPMath)
1382     return LowerFastFDIV(Op, DAG);
1383
1384   SDLoc SL(Op);
1385   SDValue X = Op.getOperand(0);
1386   SDValue Y = Op.getOperand(1);
1387
1388   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1389
1390   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1391
1392   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1393
1394   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1395
1396   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1397
1398   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1399
1400   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1401
1402   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1403
1404   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1405
1406   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1407   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1408
1409   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1410                              NegDivScale0, Mul, DivScale1);
1411
1412   SDValue Scale;
1413
1414   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1415     // Workaround a hardware bug on SI where the condition output from div_scale
1416     // is not usable.
1417
1418     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1419
1420     // Figure out if the scale to use for div_fmas.
1421     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1422     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1423     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1424     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1425
1426     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1427     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1428
1429     SDValue Scale0Hi
1430       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1431     SDValue Scale1Hi
1432       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1433
1434     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1435     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1436     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1437   } else {
1438     Scale = DivScale1.getValue(1);
1439   }
1440
1441   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1442                              Fma4, Fma3, Mul, Scale);
1443
1444   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1445 }
1446
1447 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1448   EVT VT = Op.getValueType();
1449
1450   if (VT == MVT::f32)
1451     return LowerFDIV32(Op, DAG);
1452
1453   if (VT == MVT::f64)
1454     return LowerFDIV64(Op, DAG);
1455
1456   llvm_unreachable("Unexpected type for fdiv");
1457 }
1458
1459 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1460   SDLoc DL(Op);
1461   StoreSDNode *Store = cast<StoreSDNode>(Op);
1462   EVT VT = Store->getMemoryVT();
1463
1464   // These stores are legal.
1465   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1466     if (VT.isVector() && VT.getVectorNumElements() > 4)
1467       return ScalarizeVectorStore(Op, DAG);
1468     return SDValue();
1469   }
1470
1471   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1472   if (Ret.getNode())
1473     return Ret;
1474
1475   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1476       return SplitVectorStore(Op, DAG);
1477
1478   if (VT == MVT::i1)
1479     return DAG.getTruncStore(Store->getChain(), DL,
1480                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1481                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1482
1483   return SDValue();
1484 }
1485
1486 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1487   SDLoc DL(Op);
1488   EVT VT = Op.getValueType();
1489   SDValue Arg = Op.getOperand(0);
1490   // TODO: Should this propagate fast-math-flags?
1491   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1492                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
1493                                               DAG.getConstantFP(0.5/M_PI, DL,
1494                                                                 VT)));
1495
1496   switch (Op.getOpcode()) {
1497   case ISD::FCOS:
1498     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1499   case ISD::FSIN:
1500     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1501   default:
1502     llvm_unreachable("Wrong trig opcode");
1503   }
1504 }
1505
1506 //===----------------------------------------------------------------------===//
1507 // Custom DAG optimizations
1508 //===----------------------------------------------------------------------===//
1509
1510 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1511                                                      DAGCombinerInfo &DCI) const {
1512   EVT VT = N->getValueType(0);
1513   EVT ScalarVT = VT.getScalarType();
1514   if (ScalarVT != MVT::f32)
1515     return SDValue();
1516
1517   SelectionDAG &DAG = DCI.DAG;
1518   SDLoc DL(N);
1519
1520   SDValue Src = N->getOperand(0);
1521   EVT SrcVT = Src.getValueType();
1522
1523   // TODO: We could try to match extracting the higher bytes, which would be
1524   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1525   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1526   // about in practice.
1527   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1528     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1529       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1530       DCI.AddToWorklist(Cvt.getNode());
1531       return Cvt;
1532     }
1533   }
1534
1535   // We are primarily trying to catch operations on illegal vector types
1536   // before they are expanded.
1537   // For scalars, we can use the more flexible method of checking masked bits
1538   // after legalization.
1539   if (!DCI.isBeforeLegalize() ||
1540       !SrcVT.isVector() ||
1541       SrcVT.getVectorElementType() != MVT::i8) {
1542     return SDValue();
1543   }
1544
1545   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1546
1547   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1548   // size as 4.
1549   unsigned NElts = SrcVT.getVectorNumElements();
1550   if (!SrcVT.isSimple() && NElts != 3)
1551     return SDValue();
1552
1553   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1554   // prevent a mess from expanding to v4i32 and repacking.
1555   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1556     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1557     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1558     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1559     LoadSDNode *Load = cast<LoadSDNode>(Src);
1560
1561     unsigned AS = Load->getAddressSpace();
1562     unsigned Align = Load->getAlignment();
1563     Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1564     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
1565
1566     // Don't try to replace the load if we have to expand it due to alignment
1567     // problems. Otherwise we will end up scalarizing the load, and trying to
1568     // repack into the vector for no real reason.
1569     if (Align < ABIAlignment &&
1570         !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1571       return SDValue();
1572     }
1573
1574     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1575                                      Load->getChain(),
1576                                      Load->getBasePtr(),
1577                                      LoadVT,
1578                                      Load->getMemOperand());
1579
1580     // Make sure successors of the original load stay after it by updating
1581     // them to use the new Chain.
1582     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1583
1584     SmallVector<SDValue, 4> Elts;
1585     if (RegVT.isVector())
1586       DAG.ExtractVectorElements(NewLoad, Elts);
1587     else
1588       Elts.push_back(NewLoad);
1589
1590     SmallVector<SDValue, 4> Ops;
1591
1592     unsigned EltIdx = 0;
1593     for (SDValue Elt : Elts) {
1594       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1595       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1596         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1597         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1598         DCI.AddToWorklist(Cvt.getNode());
1599         Ops.push_back(Cvt);
1600       }
1601
1602       ++EltIdx;
1603     }
1604
1605     assert(Ops.size() == NElts);
1606
1607     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1608   }
1609
1610   return SDValue();
1611 }
1612
1613 /// \brief Return true if the given offset Size in bytes can be folded into
1614 /// the immediate offsets of a memory instruction for the given address space.
1615 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1616                           const AMDGPUSubtarget &STI) {
1617   switch (AS) {
1618   case AMDGPUAS::GLOBAL_ADDRESS: {
1619     // MUBUF instructions a 12-bit offset in bytes.
1620     return isUInt<12>(OffsetSize);
1621   }
1622   case AMDGPUAS::CONSTANT_ADDRESS: {
1623     // SMRD instructions have an 8-bit offset in dwords on SI and
1624     // a 20-bit offset in bytes on VI.
1625     if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1626       return isUInt<20>(OffsetSize);
1627     else
1628       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1629   }
1630   case AMDGPUAS::LOCAL_ADDRESS:
1631   case AMDGPUAS::REGION_ADDRESS: {
1632     // The single offset versions have a 16-bit offset in bytes.
1633     return isUInt<16>(OffsetSize);
1634   }
1635   case AMDGPUAS::PRIVATE_ADDRESS:
1636   // Indirect register addressing does not use any offsets.
1637   default:
1638     return 0;
1639   }
1640 }
1641
1642 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1643
1644 // This is a variant of
1645 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1646 //
1647 // The normal DAG combiner will do this, but only if the add has one use since
1648 // that would increase the number of instructions.
1649 //
1650 // This prevents us from seeing a constant offset that can be folded into a
1651 // memory instruction's addressing mode. If we know the resulting add offset of
1652 // a pointer can be folded into an addressing offset, we can replace the pointer
1653 // operand with the add of new constant offset. This eliminates one of the uses,
1654 // and may allow the remaining use to also be simplified.
1655 //
1656 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1657                                                unsigned AddrSpace,
1658                                                DAGCombinerInfo &DCI) const {
1659   SDValue N0 = N->getOperand(0);
1660   SDValue N1 = N->getOperand(1);
1661
1662   if (N0.getOpcode() != ISD::ADD)
1663     return SDValue();
1664
1665   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1666   if (!CN1)
1667     return SDValue();
1668
1669   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1670   if (!CAdd)
1671     return SDValue();
1672
1673   // If the resulting offset is too large, we can't fold it into the addressing
1674   // mode offset.
1675   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1676   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1677     return SDValue();
1678
1679   SelectionDAG &DAG = DCI.DAG;
1680   SDLoc SL(N);
1681   EVT VT = N->getValueType(0);
1682
1683   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1684   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1685
1686   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1687 }
1688
1689 SDValue SITargetLowering::performAndCombine(SDNode *N,
1690                                             DAGCombinerInfo &DCI) const {
1691   if (DCI.isBeforeLegalize())
1692     return SDValue();
1693
1694   SelectionDAG &DAG = DCI.DAG;
1695
1696   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1697   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1698   SDValue LHS = N->getOperand(0);
1699   SDValue RHS = N->getOperand(1);
1700
1701   if (LHS.getOpcode() == ISD::SETCC &&
1702       RHS.getOpcode() == ISD::SETCC) {
1703     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1704     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1705
1706     SDValue X = LHS.getOperand(0);
1707     SDValue Y = RHS.getOperand(0);
1708     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1709       return SDValue();
1710
1711     if (LCC == ISD::SETO) {
1712       if (X != LHS.getOperand(1))
1713         return SDValue();
1714
1715       if (RCC == ISD::SETUNE) {
1716         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1717         if (!C1 || !C1->isInfinity() || C1->isNegative())
1718           return SDValue();
1719
1720         const uint32_t Mask = SIInstrFlags::N_NORMAL |
1721                               SIInstrFlags::N_SUBNORMAL |
1722                               SIInstrFlags::N_ZERO |
1723                               SIInstrFlags::P_ZERO |
1724                               SIInstrFlags::P_SUBNORMAL |
1725                               SIInstrFlags::P_NORMAL;
1726
1727         static_assert(((~(SIInstrFlags::S_NAN |
1728                           SIInstrFlags::Q_NAN |
1729                           SIInstrFlags::N_INFINITY |
1730                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1731                       "mask not equal");
1732
1733         SDLoc DL(N);
1734         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1735                            X, DAG.getConstant(Mask, DL, MVT::i32));
1736       }
1737     }
1738   }
1739
1740   return SDValue();
1741 }
1742
1743 SDValue SITargetLowering::performOrCombine(SDNode *N,
1744                                            DAGCombinerInfo &DCI) const {
1745   SelectionDAG &DAG = DCI.DAG;
1746   SDValue LHS = N->getOperand(0);
1747   SDValue RHS = N->getOperand(1);
1748
1749   // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1750   if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1751       RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1752     SDValue Src = LHS.getOperand(0);
1753     if (Src != RHS.getOperand(0))
1754       return SDValue();
1755
1756     const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1757     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1758     if (!CLHS || !CRHS)
1759       return SDValue();
1760
1761     // Only 10 bits are used.
1762     static const uint32_t MaxMask = 0x3ff;
1763
1764     uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1765     SDLoc DL(N);
1766     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1767                        Src, DAG.getConstant(NewMask, DL, MVT::i32));
1768   }
1769
1770   return SDValue();
1771 }
1772
1773 SDValue SITargetLowering::performClassCombine(SDNode *N,
1774                                               DAGCombinerInfo &DCI) const {
1775   SelectionDAG &DAG = DCI.DAG;
1776   SDValue Mask = N->getOperand(1);
1777
1778   // fp_class x, 0 -> false
1779   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1780     if (CMask->isNullValue())
1781       return DAG.getConstant(0, SDLoc(N), MVT::i1);
1782   }
1783
1784   return SDValue();
1785 }
1786
1787 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1788   switch (Opc) {
1789   case ISD::FMAXNUM:
1790     return AMDGPUISD::FMAX3;
1791   case ISD::SMAX:
1792     return AMDGPUISD::SMAX3;
1793   case ISD::UMAX:
1794     return AMDGPUISD::UMAX3;
1795   case ISD::FMINNUM:
1796     return AMDGPUISD::FMIN3;
1797   case ISD::SMIN:
1798     return AMDGPUISD::SMIN3;
1799   case ISD::UMIN:
1800     return AMDGPUISD::UMIN3;
1801   default:
1802     llvm_unreachable("Not a min/max opcode");
1803   }
1804 }
1805
1806 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1807                                                  DAGCombinerInfo &DCI) const {
1808   SelectionDAG &DAG = DCI.DAG;
1809
1810   unsigned Opc = N->getOpcode();
1811   SDValue Op0 = N->getOperand(0);
1812   SDValue Op1 = N->getOperand(1);
1813
1814   // Only do this if the inner op has one use since this will just increases
1815   // register pressure for no benefit.
1816
1817   // max(max(a, b), c)
1818   if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1819     SDLoc DL(N);
1820     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1821                        DL,
1822                        N->getValueType(0),
1823                        Op0.getOperand(0),
1824                        Op0.getOperand(1),
1825                        Op1);
1826   }
1827
1828   // max(a, max(b, c))
1829   if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1830     SDLoc DL(N);
1831     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1832                        DL,
1833                        N->getValueType(0),
1834                        Op0,
1835                        Op1.getOperand(0),
1836                        Op1.getOperand(1));
1837   }
1838
1839   return SDValue();
1840 }
1841
1842 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1843                                               DAGCombinerInfo &DCI) const {
1844   SelectionDAG &DAG = DCI.DAG;
1845   SDLoc SL(N);
1846
1847   SDValue LHS = N->getOperand(0);
1848   SDValue RHS = N->getOperand(1);
1849   EVT VT = LHS.getValueType();
1850
1851   if (VT != MVT::f32 && VT != MVT::f64)
1852     return SDValue();
1853
1854   // Match isinf pattern
1855   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1856   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1857   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1858     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1859     if (!CRHS)
1860       return SDValue();
1861
1862     const APFloat &APF = CRHS->getValueAPF();
1863     if (APF.isInfinity() && !APF.isNegative()) {
1864       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1865       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1866                          DAG.getConstant(Mask, SL, MVT::i32));
1867     }
1868   }
1869
1870   return SDValue();
1871 }
1872
1873 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1874                                             DAGCombinerInfo &DCI) const {
1875   SelectionDAG &DAG = DCI.DAG;
1876   SDLoc DL(N);
1877
1878   switch (N->getOpcode()) {
1879   default:
1880     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1881   case ISD::SETCC:
1882     return performSetCCCombine(N, DCI);
1883   case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1884   case ISD::FMINNUM:
1885   case ISD::SMAX:
1886   case ISD::SMIN:
1887   case ISD::UMAX:
1888   case ISD::UMIN: {
1889     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1890         N->getValueType(0) != MVT::f64 &&
1891         getTargetMachine().getOptLevel() > CodeGenOpt::None)
1892       return performMin3Max3Combine(N, DCI);
1893     break;
1894   }
1895
1896   case AMDGPUISD::CVT_F32_UBYTE0:
1897   case AMDGPUISD::CVT_F32_UBYTE1:
1898   case AMDGPUISD::CVT_F32_UBYTE2:
1899   case AMDGPUISD::CVT_F32_UBYTE3: {
1900     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1901
1902     SDValue Src = N->getOperand(0);
1903     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1904
1905     APInt KnownZero, KnownOne;
1906     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1907                                           !DCI.isBeforeLegalizeOps());
1908     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1909     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1910         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1911       DCI.CommitTargetLoweringOpt(TLO);
1912     }
1913
1914     break;
1915   }
1916
1917   case ISD::UINT_TO_FP: {
1918     return performUCharToFloatCombine(N, DCI);
1919
1920   case ISD::FADD: {
1921     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1922       break;
1923
1924     EVT VT = N->getValueType(0);
1925     if (VT != MVT::f32)
1926       break;
1927
1928     // Only do this if we are not trying to support denormals. v_mad_f32 does
1929     // not support denormals ever.
1930     if (Subtarget->hasFP32Denormals())
1931       break;
1932
1933     SDValue LHS = N->getOperand(0);
1934     SDValue RHS = N->getOperand(1);
1935
1936     // These should really be instruction patterns, but writing patterns with
1937     // source modiifiers is a pain.
1938
1939     // fadd (fadd (a, a), b) -> mad 2.0, a, b
1940     if (LHS.getOpcode() == ISD::FADD) {
1941       SDValue A = LHS.getOperand(0);
1942       if (A == LHS.getOperand(1)) {
1943         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1944         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1945       }
1946     }
1947
1948     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1949     if (RHS.getOpcode() == ISD::FADD) {
1950       SDValue A = RHS.getOperand(0);
1951       if (A == RHS.getOperand(1)) {
1952         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1953         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1954       }
1955     }
1956
1957     return SDValue();
1958   }
1959   case ISD::FSUB: {
1960     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1961       break;
1962
1963     EVT VT = N->getValueType(0);
1964
1965     // Try to get the fneg to fold into the source modifier. This undoes generic
1966     // DAG combines and folds them into the mad.
1967     //
1968     // Only do this if we are not trying to support denormals. v_mad_f32 does
1969     // not support denormals ever.
1970     if (VT == MVT::f32 &&
1971         !Subtarget->hasFP32Denormals()) {
1972       SDValue LHS = N->getOperand(0);
1973       SDValue RHS = N->getOperand(1);
1974       if (LHS.getOpcode() == ISD::FADD) {
1975         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1976
1977         SDValue A = LHS.getOperand(0);
1978         if (A == LHS.getOperand(1)) {
1979           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1980           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1981
1982           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1983         }
1984       }
1985
1986       if (RHS.getOpcode() == ISD::FADD) {
1987         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1988
1989         SDValue A = RHS.getOperand(0);
1990         if (A == RHS.getOperand(1)) {
1991           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1992           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1993         }
1994       }
1995
1996       return SDValue();
1997     }
1998
1999     break;
2000   }
2001   }
2002   case ISD::LOAD:
2003   case ISD::STORE:
2004   case ISD::ATOMIC_LOAD:
2005   case ISD::ATOMIC_STORE:
2006   case ISD::ATOMIC_CMP_SWAP:
2007   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2008   case ISD::ATOMIC_SWAP:
2009   case ISD::ATOMIC_LOAD_ADD:
2010   case ISD::ATOMIC_LOAD_SUB:
2011   case ISD::ATOMIC_LOAD_AND:
2012   case ISD::ATOMIC_LOAD_OR:
2013   case ISD::ATOMIC_LOAD_XOR:
2014   case ISD::ATOMIC_LOAD_NAND:
2015   case ISD::ATOMIC_LOAD_MIN:
2016   case ISD::ATOMIC_LOAD_MAX:
2017   case ISD::ATOMIC_LOAD_UMIN:
2018   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
2019     if (DCI.isBeforeLegalize())
2020       break;
2021
2022     MemSDNode *MemNode = cast<MemSDNode>(N);
2023     SDValue Ptr = MemNode->getBasePtr();
2024
2025     // TODO: We could also do this for multiplies.
2026     unsigned AS = MemNode->getAddressSpace();
2027     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
2028       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
2029       if (NewPtr) {
2030         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
2031
2032         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
2033         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
2034       }
2035     }
2036     break;
2037   }
2038   case ISD::AND:
2039     return performAndCombine(N, DCI);
2040   case ISD::OR:
2041     return performOrCombine(N, DCI);
2042   case AMDGPUISD::FP_CLASS:
2043     return performClassCombine(N, DCI);
2044   }
2045   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
2046 }
2047
2048 /// \brief Analyze the possible immediate value Op
2049 ///
2050 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
2051 /// and the immediate value if it's a literal immediate
2052 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
2053
2054   const SIInstrInfo *TII =
2055       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2056
2057   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
2058     if (TII->isInlineConstant(Node->getAPIntValue()))
2059       return 0;
2060
2061     uint64_t Val = Node->getZExtValue();
2062     return isUInt<32>(Val) ? Val : -1;
2063   }
2064
2065   if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
2066     if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
2067       return 0;
2068
2069     if (Node->getValueType(0) == MVT::f32)
2070       return FloatToBits(Node->getValueAPF().convertToFloat());
2071
2072     return -1;
2073   }
2074
2075   return -1;
2076 }
2077
2078 /// \brief Helper function for adjustWritemask
2079 static unsigned SubIdx2Lane(unsigned Idx) {
2080   switch (Idx) {
2081   default: return 0;
2082   case AMDGPU::sub0: return 0;
2083   case AMDGPU::sub1: return 1;
2084   case AMDGPU::sub2: return 2;
2085   case AMDGPU::sub3: return 3;
2086   }
2087 }
2088
2089 /// \brief Adjust the writemask of MIMG instructions
2090 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
2091                                        SelectionDAG &DAG) const {
2092   SDNode *Users[4] = { };
2093   unsigned Lane = 0;
2094   unsigned OldDmask = Node->getConstantOperandVal(0);
2095   unsigned NewDmask = 0;
2096
2097   // Try to figure out the used register components
2098   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
2099        I != E; ++I) {
2100
2101     // Abort if we can't understand the usage
2102     if (!I->isMachineOpcode() ||
2103         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
2104       return;
2105
2106     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
2107     // Note that subregs are packed, i.e. Lane==0 is the first bit set
2108     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
2109     // set, etc.
2110     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
2111
2112     // Set which texture component corresponds to the lane.
2113     unsigned Comp;
2114     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
2115       assert(Dmask);
2116       Comp = countTrailingZeros(Dmask);
2117       Dmask &= ~(1 << Comp);
2118     }
2119
2120     // Abort if we have more than one user per component
2121     if (Users[Lane])
2122       return;
2123
2124     Users[Lane] = *I;
2125     NewDmask |= 1 << Comp;
2126   }
2127
2128   // Abort if there's no change
2129   if (NewDmask == OldDmask)
2130     return;
2131
2132   // Adjust the writemask in the node
2133   std::vector<SDValue> Ops;
2134   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
2135   Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
2136   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
2137
2138   // If we only got one lane, replace it with a copy
2139   // (if NewDmask has only one bit set...)
2140   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
2141     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
2142                                        MVT::i32);
2143     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
2144                                       SDLoc(), Users[Lane]->getValueType(0),
2145                                       SDValue(Node, 0), RC);
2146     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
2147     return;
2148   }
2149
2150   // Update the users of the node with the new indices
2151   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2152
2153     SDNode *User = Users[i];
2154     if (!User)
2155       continue;
2156
2157     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2158     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2159
2160     switch (Idx) {
2161     default: break;
2162     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2163     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2164     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2165     }
2166   }
2167 }
2168
2169 static bool isFrameIndexOp(SDValue Op) {
2170   if (Op.getOpcode() == ISD::AssertZext)
2171     Op = Op.getOperand(0);
2172
2173   return isa<FrameIndexSDNode>(Op);
2174 }
2175
2176 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2177 /// with frame index operands.
2178 /// LLVM assumes that inputs are to these instructions are registers.
2179 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2180                                                      SelectionDAG &DAG) const {
2181
2182   SmallVector<SDValue, 8> Ops;
2183   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2184     if (!isFrameIndexOp(Node->getOperand(i))) {
2185       Ops.push_back(Node->getOperand(i));
2186       continue;
2187     }
2188
2189     SDLoc DL(Node);
2190     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2191                                      Node->getOperand(i).getValueType(),
2192                                      Node->getOperand(i)), 0));
2193   }
2194
2195   DAG.UpdateNodeOperands(Node, Ops);
2196 }
2197
2198 /// \brief Fold the instructions after selecting them.
2199 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2200                                           SelectionDAG &DAG) const {
2201   const SIInstrInfo *TII =
2202       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2203
2204   if (TII->isMIMG(Node->getMachineOpcode()))
2205     adjustWritemask(Node, DAG);
2206
2207   if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2208       Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2209     legalizeTargetIndependentNode(Node, DAG);
2210     return Node;
2211   }
2212   return Node;
2213 }
2214
2215 /// \brief Assign the register class depending on the number of
2216 /// bits set in the writemask
2217 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2218                                                      SDNode *Node) const {
2219   const SIInstrInfo *TII =
2220       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2221
2222   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2223
2224   if (TII->isVOP3(MI->getOpcode())) {
2225     // Make sure constant bus requirements are respected.
2226     TII->legalizeOperandsVOP3(MRI, MI);
2227     return;
2228   }
2229
2230   if (TII->isMIMG(*MI)) {
2231     unsigned VReg = MI->getOperand(0).getReg();
2232     unsigned Writemask = MI->getOperand(1).getImm();
2233     unsigned BitsSet = 0;
2234     for (unsigned i = 0; i < 4; ++i)
2235       BitsSet += Writemask & (1 << i) ? 1 : 0;
2236
2237     const TargetRegisterClass *RC;
2238     switch (BitsSet) {
2239     default: return;
2240     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
2241     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
2242     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
2243     }
2244
2245     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2246     MI->setDesc(TII->get(NewOpcode));
2247     MRI.setRegClass(VReg, RC);
2248     return;
2249   }
2250
2251   // Replace unused atomics with the no return version.
2252   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2253   if (NoRetAtomicOp != -1) {
2254     if (!Node->hasAnyUseOfValue(0)) {
2255       MI->setDesc(TII->get(NoRetAtomicOp));
2256       MI->RemoveOperand(0);
2257     }
2258
2259     return;
2260   }
2261 }
2262
2263 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2264   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2265   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2266 }
2267
2268 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2269                                                 SDLoc DL,
2270                                                 SDValue Ptr) const {
2271   const SIInstrInfo *TII =
2272     static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2273
2274   // Build the half of the subregister with the constants before building the
2275   // full 128-bit register. If we are building multiple resource descriptors,
2276   // this will allow CSEing of the 2-component register.
2277   const SDValue Ops0[] = {
2278     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2279     buildSMovImm32(DAG, DL, 0),
2280     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2281     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2282     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2283   };
2284
2285   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2286                                                 MVT::v2i32, Ops0), 0);
2287
2288   // Combine the constants and the pointer.
2289   const SDValue Ops1[] = {
2290     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2291     Ptr,
2292     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2293     SubRegHi,
2294     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2295   };
2296
2297   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2298 }
2299
2300 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2301 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
2302 ///        of the resource descriptor) to create an offset, which is added to
2303 ///        the resource pointer.
2304 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2305                                            SDLoc DL,
2306                                            SDValue Ptr,
2307                                            uint32_t RsrcDword1,
2308                                            uint64_t RsrcDword2And3) const {
2309   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2310   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2311   if (RsrcDword1) {
2312     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2313                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2314                     0);
2315   }
2316
2317   SDValue DataLo = buildSMovImm32(DAG, DL,
2318                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2319   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2320
2321   const SDValue Ops[] = {
2322     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2323     PtrLo,
2324     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2325     PtrHi,
2326     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2327     DataLo,
2328     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2329     DataHi,
2330     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2331   };
2332
2333   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2334 }
2335
2336 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2337                                                const TargetRegisterClass *RC,
2338                                                unsigned Reg, EVT VT) const {
2339   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2340
2341   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2342                             cast<RegisterSDNode>(VReg)->getReg(), VT);
2343 }
2344
2345 //===----------------------------------------------------------------------===//
2346 //                         SI Inline Assembly Support
2347 //===----------------------------------------------------------------------===//
2348
2349 std::pair<unsigned, const TargetRegisterClass *>
2350 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2351                                                StringRef Constraint,
2352                                                MVT VT) const {
2353   if (Constraint == "r") {
2354     switch(VT.SimpleTy) {
2355       default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2356       case MVT::i64:
2357         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2358       case MVT::i32:
2359         return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2360     }
2361   }
2362
2363   if (Constraint.size() > 1) {
2364     const TargetRegisterClass *RC = nullptr;
2365     if (Constraint[1] == 'v') {
2366       RC = &AMDGPU::VGPR_32RegClass;
2367     } else if (Constraint[1] == 's') {
2368       RC = &AMDGPU::SGPR_32RegClass;
2369     }
2370
2371     if (RC) {
2372       uint32_t Idx;
2373       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2374       if (!Failed && Idx < RC->getNumRegs())
2375         return std::make_pair(RC->getRegister(Idx), RC);
2376     }
2377   }
2378   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2379 }