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