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