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