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