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