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