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