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