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