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