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