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