Make TargetLowering::getPointerTy() taking DataLayout as an argument
[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(DAG.getDataLayout(), 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(PtrVT);
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(const DataLayout &DL, LLVMContext &Ctx,
699                                          EVT VT) const {
700   if (!VT.isVector()) {
701     return MVT::i1;
702   }
703   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
704 }
705
706 MVT SITargetLowering::getScalarShiftAmountTy(EVT VT) const {
707   return MVT::i32;
708 }
709
710 // Answering this is somewhat tricky and depends on the specific device which
711 // have different rates for fma or all f64 operations.
712 //
713 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
714 // regardless of which device (although the number of cycles differs between
715 // devices), so it is always profitable for f64.
716 //
717 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
718 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
719 // which we can always do even without fused FP ops since it returns the same
720 // result as the separate operations and since it is always full
721 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
722 // however does not support denormals, so we do report fma as faster if we have
723 // a fast fma device and require denormals.
724 //
725 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
726   VT = VT.getScalarType();
727
728   if (!VT.isSimple())
729     return false;
730
731   switch (VT.getSimpleVT().SimpleTy) {
732   case MVT::f32:
733     // This is as fast on some subtargets. However, we always have full rate f32
734     // mad available which returns the same result as the separate operations
735     // which we should prefer over fma. We can't use this if we want to support
736     // denormals, so only report this in these cases.
737     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
738   case MVT::f64:
739     return true;
740   default:
741     break;
742   }
743
744   return false;
745 }
746
747 //===----------------------------------------------------------------------===//
748 // Custom DAG Lowering Operations
749 //===----------------------------------------------------------------------===//
750
751 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
752   switch (Op.getOpcode()) {
753   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
754   case ISD::FrameIndex: return LowerFrameIndex(Op, DAG);
755   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
756   case ISD::LOAD: {
757     SDValue Result = LowerLOAD(Op, DAG);
758     assert((!Result.getNode() ||
759             Result.getNode()->getNumValues() == 2) &&
760            "Load should return a value and a chain");
761     return Result;
762   }
763
764   case ISD::FSIN:
765   case ISD::FCOS:
766     return LowerTrig(Op, DAG);
767   case ISD::SELECT: return LowerSELECT(Op, DAG);
768   case ISD::FDIV: return LowerFDIV(Op, DAG);
769   case ISD::STORE: return LowerSTORE(Op, DAG);
770   case ISD::GlobalAddress: {
771     MachineFunction &MF = DAG.getMachineFunction();
772     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
773     return LowerGlobalAddress(MFI, Op, DAG);
774   }
775   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
776   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
777   }
778   return SDValue();
779 }
780
781 /// \brief Helper function for LowerBRCOND
782 static SDNode *findUser(SDValue Value, unsigned Opcode) {
783
784   SDNode *Parent = Value.getNode();
785   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
786        I != E; ++I) {
787
788     if (I.getUse().get() != Value)
789       continue;
790
791     if (I->getOpcode() == Opcode)
792       return *I;
793   }
794   return nullptr;
795 }
796
797 SDValue SITargetLowering::LowerFrameIndex(SDValue Op, SelectionDAG &DAG) const {
798
799   FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Op);
800   unsigned FrameIndex = FINode->getIndex();
801
802   return DAG.getTargetFrameIndex(FrameIndex, MVT::i32);
803 }
804
805 /// This transforms the control flow intrinsics to get the branch destination as
806 /// last parameter, also switches branch target with BR if the need arise
807 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
808                                       SelectionDAG &DAG) const {
809
810   SDLoc DL(BRCOND);
811
812   SDNode *Intr = BRCOND.getOperand(1).getNode();
813   SDValue Target = BRCOND.getOperand(2);
814   SDNode *BR = nullptr;
815
816   if (Intr->getOpcode() == ISD::SETCC) {
817     // As long as we negate the condition everything is fine
818     SDNode *SetCC = Intr;
819     assert(SetCC->getConstantOperandVal(1) == 1);
820     assert(cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
821            ISD::SETNE);
822     Intr = SetCC->getOperand(0).getNode();
823
824   } else {
825     // Get the target from BR if we don't negate the condition
826     BR = findUser(BRCOND, ISD::BR);
827     Target = BR->getOperand(1);
828   }
829
830   assert(Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN);
831
832   // Build the result and
833   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
834
835   // operands of the new intrinsic call
836   SmallVector<SDValue, 4> Ops;
837   Ops.push_back(BRCOND.getOperand(0));
838   Ops.append(Intr->op_begin() + 1, Intr->op_end());
839   Ops.push_back(Target);
840
841   // build the new intrinsic call
842   SDNode *Result = DAG.getNode(
843     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
844     DAG.getVTList(Res), Ops).getNode();
845
846   if (BR) {
847     // Give the branch instruction our target
848     SDValue Ops[] = {
849       BR->getOperand(0),
850       BRCOND.getOperand(2)
851     };
852     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
853     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
854     BR = NewBR.getNode();
855   }
856
857   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
858
859   // Copy the intrinsic results to registers
860   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
861     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
862     if (!CopyToReg)
863       continue;
864
865     Chain = DAG.getCopyToReg(
866       Chain, DL,
867       CopyToReg->getOperand(1),
868       SDValue(Result, i - 1),
869       SDValue());
870
871     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
872   }
873
874   // Remove the old intrinsic from the chain
875   DAG.ReplaceAllUsesOfValueWith(
876     SDValue(Intr, Intr->getNumValues() - 1),
877     Intr->getOperand(0));
878
879   return Chain;
880 }
881
882 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
883                                              SDValue Op,
884                                              SelectionDAG &DAG) const {
885   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
886
887   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS)
888     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
889
890   SDLoc DL(GSD);
891   const GlobalValue *GV = GSD->getGlobal();
892   MVT PtrVT = getPointerTy(DAG.getDataLayout(), GSD->getAddressSpace());
893
894   SDValue Ptr = DAG.getNode(AMDGPUISD::CONST_DATA_PTR, DL, PtrVT);
895   SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32);
896
897   SDValue PtrLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
898                               DAG.getConstant(0, DL, MVT::i32));
899   SDValue PtrHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Ptr,
900                               DAG.getConstant(1, DL, MVT::i32));
901
902   SDValue Lo = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i32, MVT::Glue),
903                            PtrLo, GA);
904   SDValue Hi = DAG.getNode(ISD::ADDE, DL, DAG.getVTList(MVT::i32, MVT::Glue),
905                            PtrHi, DAG.getConstant(0, DL, MVT::i32),
906                            SDValue(Lo.getNode(), 1));
907   return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Lo, Hi);
908 }
909
910 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, SDLoc DL,
911                                    SDValue V) const {
912   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
913   // so we will end up with redundant moves to m0.
914   //
915   // We can't use S_MOV_B32, because there is no way to specify m0 as the
916   // destination register.
917   //
918   // We have to use them both.  Machine cse will combine all the S_MOV_B32
919   // instructions and the register coalescer eliminate the extra copies.
920   SDNode *M0 = DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, V.getValueType(), V);
921   return DAG.getCopyToReg(Chain, DL, DAG.getRegister(AMDGPU::M0, MVT::i32),
922                           SDValue(M0, 0), SDValue()); // Glue
923                                                       // A Null SDValue creates
924                                                       // a glue result.
925 }
926
927 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
928                                                   SelectionDAG &DAG) const {
929   MachineFunction &MF = DAG.getMachineFunction();
930   const SIRegisterInfo *TRI =
931       static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
932
933   EVT VT = Op.getValueType();
934   SDLoc DL(Op);
935   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
936
937   switch (IntrinsicID) {
938   case Intrinsic::r600_read_ngroups_x:
939     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
940                           SI::KernelInputOffsets::NGROUPS_X, false);
941   case Intrinsic::r600_read_ngroups_y:
942     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
943                           SI::KernelInputOffsets::NGROUPS_Y, false);
944   case Intrinsic::r600_read_ngroups_z:
945     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
946                           SI::KernelInputOffsets::NGROUPS_Z, false);
947   case Intrinsic::r600_read_global_size_x:
948     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
949                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
950   case Intrinsic::r600_read_global_size_y:
951     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
952                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
953   case Intrinsic::r600_read_global_size_z:
954     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
955                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
956   case Intrinsic::r600_read_local_size_x:
957     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
958                           SI::KernelInputOffsets::LOCAL_SIZE_X, false);
959   case Intrinsic::r600_read_local_size_y:
960     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
961                           SI::KernelInputOffsets::LOCAL_SIZE_Y, false);
962   case Intrinsic::r600_read_local_size_z:
963     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
964                           SI::KernelInputOffsets::LOCAL_SIZE_Z, false);
965
966   case Intrinsic::AMDGPU_read_workdim:
967     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
968                           MF.getInfo<SIMachineFunctionInfo>()->ABIArgOffset,
969                           false);
970
971   case Intrinsic::r600_read_tgid_x:
972     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
973       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_X), VT);
974   case Intrinsic::r600_read_tgid_y:
975     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
976       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Y), VT);
977   case Intrinsic::r600_read_tgid_z:
978     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32RegClass,
979       TRI->getPreloadedValue(MF, SIRegisterInfo::TGID_Z), VT);
980   case Intrinsic::r600_read_tidig_x:
981     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
982       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_X), VT);
983   case Intrinsic::r600_read_tidig_y:
984     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
985       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Y), VT);
986   case Intrinsic::r600_read_tidig_z:
987     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
988       TRI->getPreloadedValue(MF, SIRegisterInfo::TIDIG_Z), VT);
989   case AMDGPUIntrinsic::SI_load_const: {
990     SDValue Ops[] = {
991       Op.getOperand(1),
992       Op.getOperand(2)
993     };
994
995     MachineMemOperand *MMO = MF.getMachineMemOperand(
996       MachinePointerInfo(),
997       MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant,
998       VT.getStoreSize(), 4);
999     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
1000                                    Op->getVTList(), Ops, VT, MMO);
1001   }
1002   case AMDGPUIntrinsic::SI_sample:
1003     return LowerSampleIntrinsic(AMDGPUISD::SAMPLE, Op, DAG);
1004   case AMDGPUIntrinsic::SI_sampleb:
1005     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEB, Op, DAG);
1006   case AMDGPUIntrinsic::SI_sampled:
1007     return LowerSampleIntrinsic(AMDGPUISD::SAMPLED, Op, DAG);
1008   case AMDGPUIntrinsic::SI_samplel:
1009     return LowerSampleIntrinsic(AMDGPUISD::SAMPLEL, Op, DAG);
1010   case AMDGPUIntrinsic::SI_vs_load_input:
1011     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
1012                        Op.getOperand(1),
1013                        Op.getOperand(2),
1014                        Op.getOperand(3));
1015
1016   case AMDGPUIntrinsic::AMDGPU_fract:
1017   case AMDGPUIntrinsic::AMDIL_fraction: // Legacy name.
1018     return DAG.getNode(ISD::FSUB, DL, VT, Op.getOperand(1),
1019                        DAG.getNode(ISD::FFLOOR, DL, VT, Op.getOperand(1)));
1020   case AMDGPUIntrinsic::SI_fs_constant: {
1021     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1022     SDValue Glue = M0.getValue(1);
1023     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
1024                        DAG.getConstant(2, DL, MVT::i32), // P0
1025                        Op.getOperand(1), Op.getOperand(2), Glue);
1026   }
1027   case AMDGPUIntrinsic::SI_fs_interp: {
1028     SDValue IJ = Op.getOperand(4);
1029     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1030                             DAG.getConstant(0, DL, MVT::i32));
1031     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
1032                             DAG.getConstant(1, DL, MVT::i32));
1033     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
1034     SDValue Glue = M0.getValue(1);
1035     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
1036                              DAG.getVTList(MVT::f32, MVT::Glue),
1037                              I, Op.getOperand(1), Op.getOperand(2), Glue);
1038     Glue = SDValue(P1.getNode(), 1);
1039     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
1040                              Op.getOperand(1), Op.getOperand(2), Glue);
1041   }
1042   default:
1043     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1044   }
1045 }
1046
1047 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
1048                                               SelectionDAG &DAG) const {
1049   MachineFunction &MF = DAG.getMachineFunction();
1050   SDLoc DL(Op);
1051   SDValue Chain = Op.getOperand(0);
1052   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1053
1054   switch (IntrinsicID) {
1055   case AMDGPUIntrinsic::SI_sendmsg: {
1056     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
1057     SDValue Glue = Chain.getValue(1);
1058     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
1059                        Op.getOperand(2), Glue);
1060   }
1061   case AMDGPUIntrinsic::SI_tbuffer_store: {
1062     SDValue Ops[] = {
1063       Chain,
1064       Op.getOperand(2),
1065       Op.getOperand(3),
1066       Op.getOperand(4),
1067       Op.getOperand(5),
1068       Op.getOperand(6),
1069       Op.getOperand(7),
1070       Op.getOperand(8),
1071       Op.getOperand(9),
1072       Op.getOperand(10),
1073       Op.getOperand(11),
1074       Op.getOperand(12),
1075       Op.getOperand(13),
1076       Op.getOperand(14)
1077     };
1078
1079     EVT VT = Op.getOperand(3).getValueType();
1080
1081     MachineMemOperand *MMO = MF.getMachineMemOperand(
1082       MachinePointerInfo(),
1083       MachineMemOperand::MOStore,
1084       VT.getStoreSize(), 4);
1085     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
1086                                    Op->getVTList(), Ops, VT, MMO);
1087   }
1088   default:
1089     return SDValue();
1090   }
1091 }
1092
1093 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1094   SDLoc DL(Op);
1095   LoadSDNode *Load = cast<LoadSDNode>(Op);
1096
1097   if (Op.getValueType().isVector()) {
1098     assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
1099            "Custom lowering for non-i32 vectors hasn't been implemented.");
1100     unsigned NumElements = Op.getValueType().getVectorNumElements();
1101     assert(NumElements != 2 && "v2 loads are supported for all address spaces.");
1102     switch (Load->getAddressSpace()) {
1103       default: break;
1104       case AMDGPUAS::GLOBAL_ADDRESS:
1105       case AMDGPUAS::PRIVATE_ADDRESS:
1106         // v4 loads are supported for private and global memory.
1107         if (NumElements <= 4)
1108           break;
1109         // fall-through
1110       case AMDGPUAS::LOCAL_ADDRESS:
1111         return ScalarizeVectorLoad(Op, DAG);
1112     }
1113   }
1114
1115   return AMDGPUTargetLowering::LowerLOAD(Op, DAG);
1116 }
1117
1118 SDValue SITargetLowering::LowerSampleIntrinsic(unsigned Opcode,
1119                                                const SDValue &Op,
1120                                                SelectionDAG &DAG) const {
1121   return DAG.getNode(Opcode, SDLoc(Op), Op.getValueType(), Op.getOperand(1),
1122                      Op.getOperand(2),
1123                      Op.getOperand(3),
1124                      Op.getOperand(4));
1125 }
1126
1127 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
1128   if (Op.getValueType() != MVT::i64)
1129     return SDValue();
1130
1131   SDLoc DL(Op);
1132   SDValue Cond = Op.getOperand(0);
1133
1134   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
1135   SDValue One = DAG.getConstant(1, DL, MVT::i32);
1136
1137   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
1138   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
1139
1140   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
1141   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
1142
1143   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
1144
1145   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
1146   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
1147
1148   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
1149
1150   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2i32, Lo, Hi);
1151   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
1152 }
1153
1154 // Catch division cases where we can use shortcuts with rcp and rsq
1155 // instructions.
1156 SDValue SITargetLowering::LowerFastFDIV(SDValue Op, SelectionDAG &DAG) const {
1157   SDLoc SL(Op);
1158   SDValue LHS = Op.getOperand(0);
1159   SDValue RHS = Op.getOperand(1);
1160   EVT VT = Op.getValueType();
1161   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
1162
1163   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
1164     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals())) &&
1165         CLHS->isExactlyValue(1.0)) {
1166       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
1167       // the CI documentation has a worst case error of 1 ulp.
1168       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
1169       // use it as long as we aren't trying to use denormals.
1170
1171       // 1.0 / sqrt(x) -> rsq(x)
1172       //
1173       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
1174       // error seems really high at 2^29 ULP.
1175       if (RHS.getOpcode() == ISD::FSQRT)
1176         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
1177
1178       // 1.0 / x -> rcp(x)
1179       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1180     }
1181   }
1182
1183   if (Unsafe) {
1184     // Turn into multiply by the reciprocal.
1185     // x / y -> x * (1.0 / y)
1186     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
1187     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip);
1188   }
1189
1190   return SDValue();
1191 }
1192
1193 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
1194   SDValue FastLowered = LowerFastFDIV(Op, DAG);
1195   if (FastLowered.getNode())
1196     return FastLowered;
1197
1198   // This uses v_rcp_f32 which does not handle denormals. Let this hit a
1199   // selection error for now rather than do something incorrect.
1200   if (Subtarget->hasFP32Denormals())
1201     return SDValue();
1202
1203   SDLoc SL(Op);
1204   SDValue LHS = Op.getOperand(0);
1205   SDValue RHS = Op.getOperand(1);
1206
1207   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
1208
1209   const APFloat K0Val(BitsToFloat(0x6f800000));
1210   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
1211
1212   const APFloat K1Val(BitsToFloat(0x2f800000));
1213   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
1214
1215   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
1216
1217   EVT SetCCVT =
1218       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
1219
1220   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
1221
1222   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
1223
1224   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
1225
1226   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
1227
1228   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
1229
1230   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
1231 }
1232
1233 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
1234   if (DAG.getTarget().Options.UnsafeFPMath)
1235     return LowerFastFDIV(Op, DAG);
1236
1237   SDLoc SL(Op);
1238   SDValue X = Op.getOperand(0);
1239   SDValue Y = Op.getOperand(1);
1240
1241   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
1242
1243   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
1244
1245   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
1246
1247   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
1248
1249   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
1250
1251   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
1252
1253   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
1254
1255   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
1256
1257   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
1258
1259   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
1260   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
1261
1262   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
1263                              NegDivScale0, Mul, DivScale1);
1264
1265   SDValue Scale;
1266
1267   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1268     // Workaround a hardware bug on SI where the condition output from div_scale
1269     // is not usable.
1270
1271     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
1272
1273     // Figure out if the scale to use for div_fmas.
1274     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
1275     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
1276     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
1277     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
1278
1279     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
1280     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
1281
1282     SDValue Scale0Hi
1283       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
1284     SDValue Scale1Hi
1285       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
1286
1287     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
1288     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
1289     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
1290   } else {
1291     Scale = DivScale1.getValue(1);
1292   }
1293
1294   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
1295                              Fma4, Fma3, Mul, Scale);
1296
1297   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
1298 }
1299
1300 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
1301   EVT VT = Op.getValueType();
1302
1303   if (VT == MVT::f32)
1304     return LowerFDIV32(Op, DAG);
1305
1306   if (VT == MVT::f64)
1307     return LowerFDIV64(Op, DAG);
1308
1309   llvm_unreachable("Unexpected type for fdiv");
1310 }
1311
1312 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
1313   SDLoc DL(Op);
1314   StoreSDNode *Store = cast<StoreSDNode>(Op);
1315   EVT VT = Store->getMemoryVT();
1316
1317   // These stores are legal.
1318   if (Store->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
1319     if (VT.isVector() && VT.getVectorNumElements() > 4)
1320       return ScalarizeVectorStore(Op, DAG);
1321     return SDValue();
1322   }
1323
1324   SDValue Ret = AMDGPUTargetLowering::LowerSTORE(Op, DAG);
1325   if (Ret.getNode())
1326     return Ret;
1327
1328   if (VT.isVector() && VT.getVectorNumElements() >= 8)
1329       return ScalarizeVectorStore(Op, DAG);
1330
1331   if (VT == MVT::i1)
1332     return DAG.getTruncStore(Store->getChain(), DL,
1333                         DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
1334                         Store->getBasePtr(), MVT::i1, Store->getMemOperand());
1335
1336   return SDValue();
1337 }
1338
1339 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
1340   SDLoc DL(Op);
1341   EVT VT = Op.getValueType();
1342   SDValue Arg = Op.getOperand(0);
1343   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
1344                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
1345                                               DAG.getConstantFP(0.5/M_PI, DL,
1346                                                                 VT)));
1347
1348   switch (Op.getOpcode()) {
1349   case ISD::FCOS:
1350     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
1351   case ISD::FSIN:
1352     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
1353   default:
1354     llvm_unreachable("Wrong trig opcode");
1355   }
1356 }
1357
1358 //===----------------------------------------------------------------------===//
1359 // Custom DAG optimizations
1360 //===----------------------------------------------------------------------===//
1361
1362 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
1363                                                      DAGCombinerInfo &DCI) const {
1364   EVT VT = N->getValueType(0);
1365   EVT ScalarVT = VT.getScalarType();
1366   if (ScalarVT != MVT::f32)
1367     return SDValue();
1368
1369   SelectionDAG &DAG = DCI.DAG;
1370   SDLoc DL(N);
1371
1372   SDValue Src = N->getOperand(0);
1373   EVT SrcVT = Src.getValueType();
1374
1375   // TODO: We could try to match extracting the higher bytes, which would be
1376   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
1377   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
1378   // about in practice.
1379   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
1380     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
1381       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
1382       DCI.AddToWorklist(Cvt.getNode());
1383       return Cvt;
1384     }
1385   }
1386
1387   // We are primarily trying to catch operations on illegal vector types
1388   // before they are expanded.
1389   // For scalars, we can use the more flexible method of checking masked bits
1390   // after legalization.
1391   if (!DCI.isBeforeLegalize() ||
1392       !SrcVT.isVector() ||
1393       SrcVT.getVectorElementType() != MVT::i8) {
1394     return SDValue();
1395   }
1396
1397   assert(DCI.isBeforeLegalize() && "Unexpected legal type");
1398
1399   // Weird sized vectors are a pain to handle, but we know 3 is really the same
1400   // size as 4.
1401   unsigned NElts = SrcVT.getVectorNumElements();
1402   if (!SrcVT.isSimple() && NElts != 3)
1403     return SDValue();
1404
1405   // Handle v4i8 -> v4f32 extload. Replace the v4i8 with a legal i32 load to
1406   // prevent a mess from expanding to v4i32 and repacking.
1407   if (ISD::isNormalLoad(Src.getNode()) && Src.hasOneUse()) {
1408     EVT LoadVT = getEquivalentMemType(*DAG.getContext(), SrcVT);
1409     EVT RegVT = getEquivalentLoadRegType(*DAG.getContext(), SrcVT);
1410     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f32, NElts);
1411     LoadSDNode *Load = cast<LoadSDNode>(Src);
1412
1413     unsigned AS = Load->getAddressSpace();
1414     unsigned Align = Load->getAlignment();
1415     Type *Ty = LoadVT.getTypeForEVT(*DAG.getContext());
1416     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
1417
1418     // Don't try to replace the load if we have to expand it due to alignment
1419     // problems. Otherwise we will end up scalarizing the load, and trying to
1420     // repack into the vector for no real reason.
1421     if (Align < ABIAlignment &&
1422         !allowsMisalignedMemoryAccesses(LoadVT, AS, Align, nullptr)) {
1423       return SDValue();
1424     }
1425
1426     SDValue NewLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegVT,
1427                                      Load->getChain(),
1428                                      Load->getBasePtr(),
1429                                      LoadVT,
1430                                      Load->getMemOperand());
1431
1432     // Make sure successors of the original load stay after it by updating
1433     // them to use the new Chain.
1434     DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), NewLoad.getValue(1));
1435
1436     SmallVector<SDValue, 4> Elts;
1437     if (RegVT.isVector())
1438       DAG.ExtractVectorElements(NewLoad, Elts);
1439     else
1440       Elts.push_back(NewLoad);
1441
1442     SmallVector<SDValue, 4> Ops;
1443
1444     unsigned EltIdx = 0;
1445     for (SDValue Elt : Elts) {
1446       unsigned ComponentsInElt = std::min(4u, NElts - 4 * EltIdx);
1447       for (unsigned I = 0; I < ComponentsInElt; ++I) {
1448         unsigned Opc = AMDGPUISD::CVT_F32_UBYTE0 + I;
1449         SDValue Cvt = DAG.getNode(Opc, DL, MVT::f32, Elt);
1450         DCI.AddToWorklist(Cvt.getNode());
1451         Ops.push_back(Cvt);
1452       }
1453
1454       ++EltIdx;
1455     }
1456
1457     assert(Ops.size() == NElts);
1458
1459     return DAG.getNode(ISD::BUILD_VECTOR, DL, FloatVT, Ops);
1460   }
1461
1462   return SDValue();
1463 }
1464
1465 /// \brief Return true if the given offset Size in bytes can be folded into
1466 /// the immediate offsets of a memory instruction for the given address space.
1467 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
1468                           const AMDGPUSubtarget &STI) {
1469   switch (AS) {
1470   case AMDGPUAS::GLOBAL_ADDRESS: {
1471     // MUBUF instructions a 12-bit offset in bytes.
1472     return isUInt<12>(OffsetSize);
1473   }
1474   case AMDGPUAS::CONSTANT_ADDRESS: {
1475     // SMRD instructions have an 8-bit offset in dwords on SI and
1476     // a 20-bit offset in bytes on VI.
1477     if (STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
1478       return isUInt<20>(OffsetSize);
1479     else
1480       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
1481   }
1482   case AMDGPUAS::LOCAL_ADDRESS:
1483   case AMDGPUAS::REGION_ADDRESS: {
1484     // The single offset versions have a 16-bit offset in bytes.
1485     return isUInt<16>(OffsetSize);
1486   }
1487   case AMDGPUAS::PRIVATE_ADDRESS:
1488   // Indirect register addressing does not use any offsets.
1489   default:
1490     return 0;
1491   }
1492 }
1493
1494 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
1495
1496 // This is a variant of
1497 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
1498 //
1499 // The normal DAG combiner will do this, but only if the add has one use since
1500 // that would increase the number of instructions.
1501 //
1502 // This prevents us from seeing a constant offset that can be folded into a
1503 // memory instruction's addressing mode. If we know the resulting add offset of
1504 // a pointer can be folded into an addressing offset, we can replace the pointer
1505 // operand with the add of new constant offset. This eliminates one of the uses,
1506 // and may allow the remaining use to also be simplified.
1507 //
1508 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
1509                                                unsigned AddrSpace,
1510                                                DAGCombinerInfo &DCI) const {
1511   SDValue N0 = N->getOperand(0);
1512   SDValue N1 = N->getOperand(1);
1513
1514   if (N0.getOpcode() != ISD::ADD)
1515     return SDValue();
1516
1517   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
1518   if (!CN1)
1519     return SDValue();
1520
1521   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
1522   if (!CAdd)
1523     return SDValue();
1524
1525   // If the resulting offset is too large, we can't fold it into the addressing
1526   // mode offset.
1527   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
1528   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *Subtarget))
1529     return SDValue();
1530
1531   SelectionDAG &DAG = DCI.DAG;
1532   SDLoc SL(N);
1533   EVT VT = N->getValueType(0);
1534
1535   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
1536   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
1537
1538   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
1539 }
1540
1541 SDValue SITargetLowering::performAndCombine(SDNode *N,
1542                                             DAGCombinerInfo &DCI) const {
1543   if (DCI.isBeforeLegalize())
1544     return SDValue();
1545
1546   SelectionDAG &DAG = DCI.DAG;
1547
1548   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
1549   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
1550   SDValue LHS = N->getOperand(0);
1551   SDValue RHS = N->getOperand(1);
1552
1553   if (LHS.getOpcode() == ISD::SETCC &&
1554       RHS.getOpcode() == ISD::SETCC) {
1555     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
1556     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
1557
1558     SDValue X = LHS.getOperand(0);
1559     SDValue Y = RHS.getOperand(0);
1560     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
1561       return SDValue();
1562
1563     if (LCC == ISD::SETO) {
1564       if (X != LHS.getOperand(1))
1565         return SDValue();
1566
1567       if (RCC == ISD::SETUNE) {
1568         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
1569         if (!C1 || !C1->isInfinity() || C1->isNegative())
1570           return SDValue();
1571
1572         const uint32_t Mask = SIInstrFlags::N_NORMAL |
1573                               SIInstrFlags::N_SUBNORMAL |
1574                               SIInstrFlags::N_ZERO |
1575                               SIInstrFlags::P_ZERO |
1576                               SIInstrFlags::P_SUBNORMAL |
1577                               SIInstrFlags::P_NORMAL;
1578
1579         static_assert(((~(SIInstrFlags::S_NAN |
1580                           SIInstrFlags::Q_NAN |
1581                           SIInstrFlags::N_INFINITY |
1582                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
1583                       "mask not equal");
1584
1585         SDLoc DL(N);
1586         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1587                            X, DAG.getConstant(Mask, DL, MVT::i32));
1588       }
1589     }
1590   }
1591
1592   return SDValue();
1593 }
1594
1595 SDValue SITargetLowering::performOrCombine(SDNode *N,
1596                                            DAGCombinerInfo &DCI) const {
1597   SelectionDAG &DAG = DCI.DAG;
1598   SDValue LHS = N->getOperand(0);
1599   SDValue RHS = N->getOperand(1);
1600
1601   // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
1602   if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
1603       RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
1604     SDValue Src = LHS.getOperand(0);
1605     if (Src != RHS.getOperand(0))
1606       return SDValue();
1607
1608     const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
1609     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
1610     if (!CLHS || !CRHS)
1611       return SDValue();
1612
1613     // Only 10 bits are used.
1614     static const uint32_t MaxMask = 0x3ff;
1615
1616     uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
1617     SDLoc DL(N);
1618     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
1619                        Src, DAG.getConstant(NewMask, DL, MVT::i32));
1620   }
1621
1622   return SDValue();
1623 }
1624
1625 SDValue SITargetLowering::performClassCombine(SDNode *N,
1626                                               DAGCombinerInfo &DCI) const {
1627   SelectionDAG &DAG = DCI.DAG;
1628   SDValue Mask = N->getOperand(1);
1629
1630   // fp_class x, 0 -> false
1631   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
1632     if (CMask->isNullValue())
1633       return DAG.getConstant(0, SDLoc(N), MVT::i1);
1634   }
1635
1636   return SDValue();
1637 }
1638
1639 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
1640   switch (Opc) {
1641   case ISD::FMAXNUM:
1642     return AMDGPUISD::FMAX3;
1643   case ISD::SMAX:
1644     return AMDGPUISD::SMAX3;
1645   case ISD::UMAX:
1646     return AMDGPUISD::UMAX3;
1647   case ISD::FMINNUM:
1648     return AMDGPUISD::FMIN3;
1649   case ISD::SMIN:
1650     return AMDGPUISD::SMIN3;
1651   case ISD::UMIN:
1652     return AMDGPUISD::UMIN3;
1653   default:
1654     llvm_unreachable("Not a min/max opcode");
1655   }
1656 }
1657
1658 SDValue SITargetLowering::performMin3Max3Combine(SDNode *N,
1659                                                  DAGCombinerInfo &DCI) const {
1660   SelectionDAG &DAG = DCI.DAG;
1661
1662   unsigned Opc = N->getOpcode();
1663   SDValue Op0 = N->getOperand(0);
1664   SDValue Op1 = N->getOperand(1);
1665
1666   // Only do this if the inner op has one use since this will just increases
1667   // register pressure for no benefit.
1668
1669   // max(max(a, b), c)
1670   if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
1671     SDLoc DL(N);
1672     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1673                        DL,
1674                        N->getValueType(0),
1675                        Op0.getOperand(0),
1676                        Op0.getOperand(1),
1677                        Op1);
1678   }
1679
1680   // max(a, max(b, c))
1681   if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
1682     SDLoc DL(N);
1683     return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
1684                        DL,
1685                        N->getValueType(0),
1686                        Op0,
1687                        Op1.getOperand(0),
1688                        Op1.getOperand(1));
1689   }
1690
1691   return SDValue();
1692 }
1693
1694 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
1695                                               DAGCombinerInfo &DCI) const {
1696   SelectionDAG &DAG = DCI.DAG;
1697   SDLoc SL(N);
1698
1699   SDValue LHS = N->getOperand(0);
1700   SDValue RHS = N->getOperand(1);
1701   EVT VT = LHS.getValueType();
1702
1703   if (VT != MVT::f32 && VT != MVT::f64)
1704     return SDValue();
1705
1706   // Match isinf pattern
1707   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
1708   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1709   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
1710     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
1711     if (!CRHS)
1712       return SDValue();
1713
1714     const APFloat &APF = CRHS->getValueAPF();
1715     if (APF.isInfinity() && !APF.isNegative()) {
1716       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
1717       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
1718                          DAG.getConstant(Mask, SL, MVT::i32));
1719     }
1720   }
1721
1722   return SDValue();
1723 }
1724
1725 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
1726                                             DAGCombinerInfo &DCI) const {
1727   SelectionDAG &DAG = DCI.DAG;
1728   SDLoc DL(N);
1729
1730   switch (N->getOpcode()) {
1731   default:
1732     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1733   case ISD::SETCC:
1734     return performSetCCCombine(N, DCI);
1735   case ISD::FMAXNUM: // TODO: What about fmax_legacy?
1736   case ISD::FMINNUM:
1737   case ISD::SMAX:
1738   case ISD::SMIN:
1739   case ISD::UMAX:
1740   case ISD::UMIN: {
1741     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
1742         N->getValueType(0) != MVT::f64 &&
1743         getTargetMachine().getOptLevel() > CodeGenOpt::None)
1744       return performMin3Max3Combine(N, DCI);
1745     break;
1746   }
1747
1748   case AMDGPUISD::CVT_F32_UBYTE0:
1749   case AMDGPUISD::CVT_F32_UBYTE1:
1750   case AMDGPUISD::CVT_F32_UBYTE2:
1751   case AMDGPUISD::CVT_F32_UBYTE3: {
1752     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
1753
1754     SDValue Src = N->getOperand(0);
1755     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
1756
1757     APInt KnownZero, KnownOne;
1758     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1759                                           !DCI.isBeforeLegalizeOps());
1760     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1761     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
1762         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
1763       DCI.CommitTargetLoweringOpt(TLO);
1764     }
1765
1766     break;
1767   }
1768
1769   case ISD::UINT_TO_FP: {
1770     return performUCharToFloatCombine(N, DCI);
1771
1772   case ISD::FADD: {
1773     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1774       break;
1775
1776     EVT VT = N->getValueType(0);
1777     if (VT != MVT::f32)
1778       break;
1779
1780     // Only do this if we are not trying to support denormals. v_mad_f32 does
1781     // not support denormals ever.
1782     if (Subtarget->hasFP32Denormals())
1783       break;
1784
1785     SDValue LHS = N->getOperand(0);
1786     SDValue RHS = N->getOperand(1);
1787
1788     // These should really be instruction patterns, but writing patterns with
1789     // source modiifiers is a pain.
1790
1791     // fadd (fadd (a, a), b) -> mad 2.0, a, b
1792     if (LHS.getOpcode() == ISD::FADD) {
1793       SDValue A = LHS.getOperand(0);
1794       if (A == LHS.getOperand(1)) {
1795         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1796         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
1797       }
1798     }
1799
1800     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
1801     if (RHS.getOpcode() == ISD::FADD) {
1802       SDValue A = RHS.getOperand(0);
1803       if (A == RHS.getOperand(1)) {
1804         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1805         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
1806       }
1807     }
1808
1809     return SDValue();
1810   }
1811   case ISD::FSUB: {
1812     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
1813       break;
1814
1815     EVT VT = N->getValueType(0);
1816
1817     // Try to get the fneg to fold into the source modifier. This undoes generic
1818     // DAG combines and folds them into the mad.
1819     //
1820     // Only do this if we are not trying to support denormals. v_mad_f32 does
1821     // not support denormals ever.
1822     if (VT == MVT::f32 &&
1823         !Subtarget->hasFP32Denormals()) {
1824       SDValue LHS = N->getOperand(0);
1825       SDValue RHS = N->getOperand(1);
1826       if (LHS.getOpcode() == ISD::FADD) {
1827         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
1828
1829         SDValue A = LHS.getOperand(0);
1830         if (A == LHS.getOperand(1)) {
1831           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
1832           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
1833
1834           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
1835         }
1836       }
1837
1838       if (RHS.getOpcode() == ISD::FADD) {
1839         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
1840
1841         SDValue A = RHS.getOperand(0);
1842         if (A == RHS.getOperand(1)) {
1843           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
1844           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
1845         }
1846       }
1847
1848       return SDValue();
1849     }
1850
1851     break;
1852   }
1853   }
1854   case ISD::LOAD:
1855   case ISD::STORE:
1856   case ISD::ATOMIC_LOAD:
1857   case ISD::ATOMIC_STORE:
1858   case ISD::ATOMIC_CMP_SWAP:
1859   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1860   case ISD::ATOMIC_SWAP:
1861   case ISD::ATOMIC_LOAD_ADD:
1862   case ISD::ATOMIC_LOAD_SUB:
1863   case ISD::ATOMIC_LOAD_AND:
1864   case ISD::ATOMIC_LOAD_OR:
1865   case ISD::ATOMIC_LOAD_XOR:
1866   case ISD::ATOMIC_LOAD_NAND:
1867   case ISD::ATOMIC_LOAD_MIN:
1868   case ISD::ATOMIC_LOAD_MAX:
1869   case ISD::ATOMIC_LOAD_UMIN:
1870   case ISD::ATOMIC_LOAD_UMAX: { // TODO: Target mem intrinsics.
1871     if (DCI.isBeforeLegalize())
1872       break;
1873
1874     MemSDNode *MemNode = cast<MemSDNode>(N);
1875     SDValue Ptr = MemNode->getBasePtr();
1876
1877     // TODO: We could also do this for multiplies.
1878     unsigned AS = MemNode->getAddressSpace();
1879     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
1880       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
1881       if (NewPtr) {
1882         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
1883
1884         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
1885         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
1886       }
1887     }
1888     break;
1889   }
1890   case ISD::AND:
1891     return performAndCombine(N, DCI);
1892   case ISD::OR:
1893     return performOrCombine(N, DCI);
1894   case AMDGPUISD::FP_CLASS:
1895     return performClassCombine(N, DCI);
1896   }
1897   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
1898 }
1899
1900 /// \brief Analyze the possible immediate value Op
1901 ///
1902 /// Returns -1 if it isn't an immediate, 0 if it's and inline immediate
1903 /// and the immediate value if it's a literal immediate
1904 int32_t SITargetLowering::analyzeImmediate(const SDNode *N) const {
1905
1906   const SIInstrInfo *TII =
1907       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
1908
1909   if (const ConstantSDNode *Node = dyn_cast<ConstantSDNode>(N)) {
1910     if (TII->isInlineConstant(Node->getAPIntValue()))
1911       return 0;
1912
1913     uint64_t Val = Node->getZExtValue();
1914     return isUInt<32>(Val) ? Val : -1;
1915   }
1916
1917   if (const ConstantFPSDNode *Node = dyn_cast<ConstantFPSDNode>(N)) {
1918     if (TII->isInlineConstant(Node->getValueAPF().bitcastToAPInt()))
1919       return 0;
1920
1921     if (Node->getValueType(0) == MVT::f32)
1922       return FloatToBits(Node->getValueAPF().convertToFloat());
1923
1924     return -1;
1925   }
1926
1927   return -1;
1928 }
1929
1930 /// \brief Helper function for adjustWritemask
1931 static unsigned SubIdx2Lane(unsigned Idx) {
1932   switch (Idx) {
1933   default: return 0;
1934   case AMDGPU::sub0: return 0;
1935   case AMDGPU::sub1: return 1;
1936   case AMDGPU::sub2: return 2;
1937   case AMDGPU::sub3: return 3;
1938   }
1939 }
1940
1941 /// \brief Adjust the writemask of MIMG instructions
1942 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
1943                                        SelectionDAG &DAG) const {
1944   SDNode *Users[4] = { };
1945   unsigned Lane = 0;
1946   unsigned OldDmask = Node->getConstantOperandVal(0);
1947   unsigned NewDmask = 0;
1948
1949   // Try to figure out the used register components
1950   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
1951        I != E; ++I) {
1952
1953     // Abort if we can't understand the usage
1954     if (!I->isMachineOpcode() ||
1955         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
1956       return;
1957
1958     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
1959     // Note that subregs are packed, i.e. Lane==0 is the first bit set
1960     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
1961     // set, etc.
1962     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
1963
1964     // Set which texture component corresponds to the lane.
1965     unsigned Comp;
1966     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
1967       assert(Dmask);
1968       Comp = countTrailingZeros(Dmask);
1969       Dmask &= ~(1 << Comp);
1970     }
1971
1972     // Abort if we have more than one user per component
1973     if (Users[Lane])
1974       return;
1975
1976     Users[Lane] = *I;
1977     NewDmask |= 1 << Comp;
1978   }
1979
1980   // Abort if there's no change
1981   if (NewDmask == OldDmask)
1982     return;
1983
1984   // Adjust the writemask in the node
1985   std::vector<SDValue> Ops;
1986   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
1987   Ops.insert(Ops.end(), Node->op_begin() + 1, Node->op_end());
1988   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
1989
1990   // If we only got one lane, replace it with a copy
1991   // (if NewDmask has only one bit set...)
1992   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
1993     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
1994                                        MVT::i32);
1995     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
1996                                       SDLoc(), Users[Lane]->getValueType(0),
1997                                       SDValue(Node, 0), RC);
1998     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
1999     return;
2000   }
2001
2002   // Update the users of the node with the new indices
2003   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
2004
2005     SDNode *User = Users[i];
2006     if (!User)
2007       continue;
2008
2009     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
2010     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
2011
2012     switch (Idx) {
2013     default: break;
2014     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
2015     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
2016     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
2017     }
2018   }
2019 }
2020
2021 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
2022 /// with frame index operands.
2023 /// LLVM assumes that inputs are to these instructions are registers.
2024 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
2025                                                      SelectionDAG &DAG) const {
2026
2027   SmallVector<SDValue, 8> Ops;
2028   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
2029     if (!isa<FrameIndexSDNode>(Node->getOperand(i))) {
2030       Ops.push_back(Node->getOperand(i));
2031       continue;
2032     }
2033
2034     SDLoc DL(Node);
2035     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
2036                                      Node->getOperand(i).getValueType(),
2037                                      Node->getOperand(i)), 0));
2038   }
2039
2040   DAG.UpdateNodeOperands(Node, Ops);
2041 }
2042
2043 /// \brief Fold the instructions after selecting them.
2044 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
2045                                           SelectionDAG &DAG) const {
2046   const SIInstrInfo *TII =
2047       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2048
2049   if (TII->isMIMG(Node->getMachineOpcode()))
2050     adjustWritemask(Node, DAG);
2051
2052   if (Node->getMachineOpcode() == AMDGPU::INSERT_SUBREG ||
2053       Node->getMachineOpcode() == AMDGPU::REG_SEQUENCE) {
2054     legalizeTargetIndependentNode(Node, DAG);
2055     return Node;
2056   }
2057   return Node;
2058 }
2059
2060 /// \brief Assign the register class depending on the number of
2061 /// bits set in the writemask
2062 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
2063                                                      SDNode *Node) const {
2064   const SIInstrInfo *TII =
2065       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2066
2067   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
2068   TII->legalizeOperands(MI);
2069
2070   if (TII->isMIMG(MI->getOpcode())) {
2071     unsigned VReg = MI->getOperand(0).getReg();
2072     unsigned Writemask = MI->getOperand(1).getImm();
2073     unsigned BitsSet = 0;
2074     for (unsigned i = 0; i < 4; ++i)
2075       BitsSet += Writemask & (1 << i) ? 1 : 0;
2076
2077     const TargetRegisterClass *RC;
2078     switch (BitsSet) {
2079     default: return;
2080     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
2081     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
2082     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
2083     }
2084
2085     unsigned NewOpcode = TII->getMaskedMIMGOp(MI->getOpcode(), BitsSet);
2086     MI->setDesc(TII->get(NewOpcode));
2087     MRI.setRegClass(VReg, RC);
2088     return;
2089   }
2090
2091   // Replace unused atomics with the no return version.
2092   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI->getOpcode());
2093   if (NoRetAtomicOp != -1) {
2094     if (!Node->hasAnyUseOfValue(0)) {
2095       MI->setDesc(TII->get(NoRetAtomicOp));
2096       MI->RemoveOperand(0);
2097     }
2098
2099     return;
2100   }
2101 }
2102
2103 static SDValue buildSMovImm32(SelectionDAG &DAG, SDLoc DL, uint64_t Val) {
2104   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
2105   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
2106 }
2107
2108 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
2109                                                 SDLoc DL,
2110                                                 SDValue Ptr) const {
2111   const SIInstrInfo *TII =
2112       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2113 #if 1
2114     // XXX - Workaround for moveToVALU not handling different register class
2115     // inserts for REG_SEQUENCE.
2116
2117     // Build the half of the subregister with the constants.
2118     const SDValue Ops0[] = {
2119       DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
2120       buildSMovImm32(DAG, DL, 0),
2121       DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2122       buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
2123       DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
2124     };
2125
2126     SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
2127                                                   MVT::v2i32, Ops0), 0);
2128
2129     // Combine the constants and the pointer.
2130     const SDValue Ops1[] = {
2131       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2132       Ptr,
2133       DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
2134       SubRegHi,
2135       DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
2136     };
2137
2138     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
2139 #else
2140     const SDValue Ops[] = {
2141       DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, MVT::i32),
2142       Ptr,
2143       DAG.getTargetConstant(AMDGPU::sub0_sub1, MVT::i32),
2144       buildSMovImm32(DAG, DL, 0),
2145       DAG.getTargetConstant(AMDGPU::sub2, MVT::i32),
2146       buildSMovImm32(DAG, DL, TII->getDefaultRsrcFormat() >> 32),
2147       DAG.getTargetConstant(AMDGPU::sub3, MVT::i32)
2148     };
2149
2150     return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2151
2152 #endif
2153 }
2154
2155 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
2156 ///        The TID (Thread ID) is multipled by the stride value (bits [61:48]
2157 ///        of the resource descriptor) to create an offset, which is added to the
2158 ///        resource ponter.
2159 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG,
2160                                            SDLoc DL,
2161                                            SDValue Ptr,
2162                                            uint32_t RsrcDword1,
2163                                            uint64_t RsrcDword2And3) const {
2164   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
2165   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
2166   if (RsrcDword1) {
2167     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
2168                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
2169                     0);
2170   }
2171
2172   SDValue DataLo = buildSMovImm32(DAG, DL,
2173                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
2174   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
2175
2176   const SDValue Ops[] = {
2177     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
2178     PtrLo,
2179     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
2180     PtrHi,
2181     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
2182     DataLo,
2183     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
2184     DataHi,
2185     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
2186   };
2187
2188   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
2189 }
2190
2191 MachineSDNode *SITargetLowering::buildScratchRSRC(SelectionDAG &DAG,
2192                                                   SDLoc DL,
2193                                                   SDValue Ptr) const {
2194   const SIInstrInfo *TII =
2195       static_cast<const SIInstrInfo *>(Subtarget->getInstrInfo());
2196   uint64_t Rsrc = TII->getDefaultRsrcDataFormat() | AMDGPU::RSRC_TID_ENABLE |
2197                   0xffffffff; // Size
2198
2199   return buildRSRC(DAG, DL, Ptr, 0, Rsrc);
2200 }
2201
2202 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
2203                                                const TargetRegisterClass *RC,
2204                                                unsigned Reg, EVT VT) const {
2205   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
2206
2207   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
2208                             cast<RegisterSDNode>(VReg)->getReg(), VT);
2209 }
2210
2211 //===----------------------------------------------------------------------===//
2212 //                         SI Inline Assembly Support
2213 //===----------------------------------------------------------------------===//
2214
2215 std::pair<unsigned, const TargetRegisterClass *>
2216 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
2217                                                StringRef Constraint,
2218                                                MVT VT) const {
2219   if (Constraint == "r") {
2220     switch(VT.SimpleTy) {
2221       default: llvm_unreachable("Unhandled type for 'r' inline asm constraint");
2222       case MVT::i64:
2223         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
2224       case MVT::i32:
2225         return std::make_pair(0U, &AMDGPU::SGPR_32RegClass);
2226     }
2227   }
2228
2229   if (Constraint.size() > 1) {
2230     const TargetRegisterClass *RC = nullptr;
2231     if (Constraint[1] == 'v') {
2232       RC = &AMDGPU::VGPR_32RegClass;
2233     } else if (Constraint[1] == 's') {
2234       RC = &AMDGPU::SGPR_32RegClass;
2235     }
2236
2237     if (RC) {
2238       uint32_t Idx;
2239       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
2240       if (!Failed && Idx < RC->getNumRegs())
2241         return std::make_pair(RC->getRegister(Idx), RC);
2242     }
2243   }
2244   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
2245 }