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