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