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