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