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 "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "SIDefines.h"
25 #include "SIISelLowering.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/Analysis.h"
36 #include "llvm/IR/DiagnosticInfo.h"
37 #include "llvm/IR/Function.h"
38 
39 using namespace llvm;
40 
41 static cl::opt<bool> EnableVGPRIndexMode(
42   "amdgpu-vgpr-index-mode",
43   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
44   cl::init(false));
45 
46 
47 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
48   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
49   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
50     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
51       return AMDGPU::SGPR0 + Reg;
52     }
53   }
54   llvm_unreachable("Cannot allocate sgpr");
55 }
56 
57 SITargetLowering::SITargetLowering(const TargetMachine &TM,
58                                    const SISubtarget &STI)
59     : AMDGPUTargetLowering(TM, STI) {
60   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
61   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
62 
63   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
64   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
65 
66   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
67   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
68   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
69 
70   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
71   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
72 
73   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
74   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
75 
76   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
77   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
78 
79   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
80   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
81 
82   if (Subtarget->has16BitInsts()) {
83     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
84     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
85   }
86 
87   computeRegisterProperties(STI.getRegisterInfo());
88 
89   // We need to custom lower vector stores from local memory
90   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
91   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
92   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
93   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
94   setOperationAction(ISD::LOAD, MVT::i1, Custom);
95 
96   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
97   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
98   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
99   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
100   setOperationAction(ISD::STORE, MVT::i1, Custom);
101 
102   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
103   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
104   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
105 
106   setOperationAction(ISD::SELECT, MVT::i1, Promote);
107   setOperationAction(ISD::SELECT, MVT::i64, Custom);
108   setOperationAction(ISD::SELECT, MVT::f64, Promote);
109   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
110 
111   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
112   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
113   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
114   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
115   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
116 
117   setOperationAction(ISD::SETCC, MVT::i1, Promote);
118   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
119   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
120 
121   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
122   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
123 
124   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
125   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
126   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
127   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
129   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
130   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
131 
132   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
133   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
134   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
135 
136   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
137   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
138   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
139   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
140   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
141   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
142 
143   // We only support LOAD/STORE and vector manipulation ops for vectors
144   // with > 4 elements.
145   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, MVT::v2i64, MVT::v2f64}) {
146     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
147       switch (Op) {
148       case ISD::LOAD:
149       case ISD::STORE:
150       case ISD::BUILD_VECTOR:
151       case ISD::BITCAST:
152       case ISD::EXTRACT_VECTOR_ELT:
153       case ISD::INSERT_VECTOR_ELT:
154       case ISD::INSERT_SUBVECTOR:
155       case ISD::EXTRACT_SUBVECTOR:
156       case ISD::SCALAR_TO_VECTOR:
157         break;
158       case ISD::CONCAT_VECTORS:
159         setOperationAction(Op, VT, Custom);
160         break;
161       default:
162         setOperationAction(Op, VT, Expand);
163         break;
164       }
165     }
166   }
167 
168   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
169   // is expanded to avoid having two separate loops in case the index is a VGPR.
170 
171   // Most operations are naturally 32-bit vector operations. We only support
172   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
173   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
174     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
175     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
176 
177     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
178     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
179 
180     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
181     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
182 
183     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
184     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
185   }
186 
187   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
188   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
189   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
190   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
191 
192   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
193   // and output demarshalling
194   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
195   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
196 
197   // We can't return success/failure, only the old value,
198   // let LLVM add the comparison
199   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
200   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
201 
202   if (getSubtarget()->hasFlatAddressSpace()) {
203     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
204     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
205   }
206 
207   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
208   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
209 
210   // On SI this is s_memtime and s_memrealtime on VI.
211   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
212   setOperationAction(ISD::TRAP, MVT::Other, Custom);
213 
214   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
215   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
216 
217   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
218     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
219     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
220     setOperationAction(ISD::FRINT, MVT::f64, Legal);
221   }
222 
223   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
224 
225   setOperationAction(ISD::FSIN, MVT::f32, Custom);
226   setOperationAction(ISD::FCOS, MVT::f32, Custom);
227   setOperationAction(ISD::FDIV, MVT::f32, Custom);
228   setOperationAction(ISD::FDIV, MVT::f64, Custom);
229 
230   if (Subtarget->has16BitInsts()) {
231     setOperationAction(ISD::Constant, MVT::i16, Legal);
232 
233     setOperationAction(ISD::SMIN, MVT::i16, Legal);
234     setOperationAction(ISD::SMAX, MVT::i16, Legal);
235 
236     setOperationAction(ISD::UMIN, MVT::i16, Legal);
237     setOperationAction(ISD::UMAX, MVT::i16, Legal);
238 
239     setOperationAction(ISD::SETCC, MVT::i16, Promote);
240     AddPromotedToType(ISD::SETCC, MVT::i16, MVT::i32);
241 
242     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
243     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
244 
245     setOperationAction(ISD::ROTR, MVT::i16, Promote);
246     setOperationAction(ISD::ROTL, MVT::i16, Promote);
247 
248     setOperationAction(ISD::SDIV, MVT::i16, Promote);
249     setOperationAction(ISD::UDIV, MVT::i16, Promote);
250     setOperationAction(ISD::SREM, MVT::i16, Promote);
251     setOperationAction(ISD::UREM, MVT::i16, Promote);
252 
253     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
254     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
255 
256     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
257     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
258     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
259     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
260 
261     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
262 
263     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
264 
265     setOperationAction(ISD::LOAD, MVT::i16, Custom);
266 
267     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
268 
269     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
270     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
271     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
272     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
273 
274     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
275     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
276     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
277     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
278 
279     // F16 - Constant Actions.
280     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
281 
282     // F16 - Load/Store Actions.
283     setOperationAction(ISD::LOAD, MVT::f16, Promote);
284     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
285     setOperationAction(ISD::STORE, MVT::f16, Promote);
286     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
287 
288     // F16 - VOP1 Actions.
289     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
290     setOperationAction(ISD::FCOS, MVT::f16, Promote);
291     setOperationAction(ISD::FSIN, MVT::f16, Promote);
292     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
293     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
294     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
295     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
296 
297     // F16 - VOP2 Actions.
298     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
299     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
300     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
301     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
302     setOperationAction(ISD::FDIV, MVT::f16, Promote);
303 
304     // F16 - VOP3 Actions.
305     setOperationAction(ISD::FMA, MVT::f16, Legal);
306     if (!Subtarget->hasFP16Denormals())
307       setOperationAction(ISD::FMAD, MVT::f16, Legal);
308   }
309 
310   setTargetDAGCombine(ISD::FADD);
311   setTargetDAGCombine(ISD::FSUB);
312   setTargetDAGCombine(ISD::FMINNUM);
313   setTargetDAGCombine(ISD::FMAXNUM);
314   setTargetDAGCombine(ISD::SMIN);
315   setTargetDAGCombine(ISD::SMAX);
316   setTargetDAGCombine(ISD::UMIN);
317   setTargetDAGCombine(ISD::UMAX);
318   setTargetDAGCombine(ISD::SETCC);
319   setTargetDAGCombine(ISD::AND);
320   setTargetDAGCombine(ISD::OR);
321   setTargetDAGCombine(ISD::XOR);
322   setTargetDAGCombine(ISD::SINT_TO_FP);
323   setTargetDAGCombine(ISD::UINT_TO_FP);
324   setTargetDAGCombine(ISD::FCANONICALIZE);
325 
326   // All memory operations. Some folding on the pointer operand is done to help
327   // matching the constant offsets in the addressing modes.
328   setTargetDAGCombine(ISD::LOAD);
329   setTargetDAGCombine(ISD::STORE);
330   setTargetDAGCombine(ISD::ATOMIC_LOAD);
331   setTargetDAGCombine(ISD::ATOMIC_STORE);
332   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
333   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
334   setTargetDAGCombine(ISD::ATOMIC_SWAP);
335   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
336   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
337   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
338   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
339   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
340   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
341   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
342   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
343   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
344   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
345 
346   setSchedulingPreference(Sched::RegPressure);
347 }
348 
349 const SISubtarget *SITargetLowering::getSubtarget() const {
350   return static_cast<const SISubtarget *>(Subtarget);
351 }
352 
353 //===----------------------------------------------------------------------===//
354 // TargetLowering queries
355 //===----------------------------------------------------------------------===//
356 
357 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
358                                           const CallInst &CI,
359                                           unsigned IntrID) const {
360   switch (IntrID) {
361   case Intrinsic::amdgcn_atomic_inc:
362   case Intrinsic::amdgcn_atomic_dec:
363     Info.opc = ISD::INTRINSIC_W_CHAIN;
364     Info.memVT = MVT::getVT(CI.getType());
365     Info.ptrVal = CI.getOperand(0);
366     Info.align = 0;
367     Info.vol = false;
368     Info.readMem = true;
369     Info.writeMem = true;
370     return true;
371   default:
372     return false;
373   }
374 }
375 
376 bool SITargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &,
377                                           EVT) const {
378   // SI has some legal vector types, but no legal vector operations. Say no
379   // shuffles are legal in order to prefer scalarizing some vector operations.
380   return false;
381 }
382 
383 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
384   // Flat instructions do not have offsets, and only have the register
385   // address.
386   return AM.BaseOffs == 0 && (AM.Scale == 0 || AM.Scale == 1);
387 }
388 
389 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
390   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
391   // additionally can do r + r + i with addr64. 32-bit has more addressing
392   // mode options. Depending on the resource constant, it can also do
393   // (i64 r0) + (i32 r1) * (i14 i).
394   //
395   // Private arrays end up using a scratch buffer most of the time, so also
396   // assume those use MUBUF instructions. Scratch loads / stores are currently
397   // implemented as mubuf instructions with offen bit set, so slightly
398   // different than the normal addr64.
399   if (!isUInt<12>(AM.BaseOffs))
400     return false;
401 
402   // FIXME: Since we can split immediate into soffset and immediate offset,
403   // would it make sense to allow any immediate?
404 
405   switch (AM.Scale) {
406   case 0: // r + i or just i, depending on HasBaseReg.
407     return true;
408   case 1:
409     return true; // We have r + r or r + i.
410   case 2:
411     if (AM.HasBaseReg) {
412       // Reject 2 * r + r.
413       return false;
414     }
415 
416     // Allow 2 * r as r + r
417     // Or  2 * r + i is allowed as r + r + i.
418     return true;
419   default: // Don't allow n * r
420     return false;
421   }
422 }
423 
424 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
425                                              const AddrMode &AM, Type *Ty,
426                                              unsigned AS) const {
427   // No global is ever allowed as a base.
428   if (AM.BaseGV)
429     return false;
430 
431   switch (AS) {
432   case AMDGPUAS::GLOBAL_ADDRESS: {
433     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
434       // Assume the we will use FLAT for all global memory accesses
435       // on VI.
436       // FIXME: This assumption is currently wrong.  On VI we still use
437       // MUBUF instructions for the r + i addressing mode.  As currently
438       // implemented, the MUBUF instructions only work on buffer < 4GB.
439       // It may be possible to support > 4GB buffers with MUBUF instructions,
440       // by setting the stride value in the resource descriptor which would
441       // increase the size limit to (stride * 4GB).  However, this is risky,
442       // because it has never been validated.
443       return isLegalFlatAddressingMode(AM);
444     }
445 
446     return isLegalMUBUFAddressingMode(AM);
447   }
448   case AMDGPUAS::CONSTANT_ADDRESS: {
449     // If the offset isn't a multiple of 4, it probably isn't going to be
450     // correctly aligned.
451     // FIXME: Can we get the real alignment here?
452     if (AM.BaseOffs % 4 != 0)
453       return isLegalMUBUFAddressingMode(AM);
454 
455     // There are no SMRD extloads, so if we have to do a small type access we
456     // will use a MUBUF load.
457     // FIXME?: We also need to do this if unaligned, but we don't know the
458     // alignment here.
459     if (DL.getTypeStoreSize(Ty) < 4)
460       return isLegalMUBUFAddressingMode(AM);
461 
462     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
463       // SMRD instructions have an 8-bit, dword offset on SI.
464       if (!isUInt<8>(AM.BaseOffs / 4))
465         return false;
466     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
467       // On CI+, this can also be a 32-bit literal constant offset. If it fits
468       // in 8-bits, it can use a smaller encoding.
469       if (!isUInt<32>(AM.BaseOffs / 4))
470         return false;
471     } else if (Subtarget->getGeneration() == SISubtarget::VOLCANIC_ISLANDS) {
472       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
473       if (!isUInt<20>(AM.BaseOffs))
474         return false;
475     } else
476       llvm_unreachable("unhandled generation");
477 
478     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
479       return true;
480 
481     if (AM.Scale == 1 && AM.HasBaseReg)
482       return true;
483 
484     return false;
485   }
486 
487   case AMDGPUAS::PRIVATE_ADDRESS:
488     return isLegalMUBUFAddressingMode(AM);
489 
490   case AMDGPUAS::LOCAL_ADDRESS:
491   case AMDGPUAS::REGION_ADDRESS: {
492     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
493     // field.
494     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
495     // an 8-bit dword offset but we don't know the alignment here.
496     if (!isUInt<16>(AM.BaseOffs))
497       return false;
498 
499     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
500       return true;
501 
502     if (AM.Scale == 1 && AM.HasBaseReg)
503       return true;
504 
505     return false;
506   }
507   case AMDGPUAS::FLAT_ADDRESS:
508   case AMDGPUAS::UNKNOWN_ADDRESS_SPACE:
509     // For an unknown address space, this usually means that this is for some
510     // reason being used for pure arithmetic, and not based on some addressing
511     // computation. We don't have instructions that compute pointers with any
512     // addressing modes, so treat them as having no offset like flat
513     // instructions.
514     return isLegalFlatAddressingMode(AM);
515 
516   default:
517     llvm_unreachable("unhandled address space");
518   }
519 }
520 
521 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
522                                                       unsigned AddrSpace,
523                                                       unsigned Align,
524                                                       bool *IsFast) const {
525   if (IsFast)
526     *IsFast = false;
527 
528   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
529   // which isn't a simple VT.
530   // Until MVT is extended to handle this, simply check for the size and
531   // rely on the condition below: allow accesses if the size is a multiple of 4.
532   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
533                            VT.getStoreSize() > 16)) {
534     return false;
535   }
536 
537   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
538       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
539     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
540     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
541     // with adjacent offsets.
542     bool AlignedBy4 = (Align % 4 == 0);
543     if (IsFast)
544       *IsFast = AlignedBy4;
545 
546     return AlignedBy4;
547   }
548 
549   // FIXME: We have to be conservative here and assume that flat operations
550   // will access scratch.  If we had access to the IR function, then we
551   // could determine if any private memory was used in the function.
552   if (!Subtarget->hasUnalignedScratchAccess() &&
553       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
554        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
555     return false;
556   }
557 
558   if (Subtarget->hasUnalignedBufferAccess()) {
559     // If we have an uniform constant load, it still requires using a slow
560     // buffer instruction if unaligned.
561     if (IsFast) {
562       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS) ?
563         (Align % 4 == 0) : true;
564     }
565 
566     return true;
567   }
568 
569   // Smaller than dword value must be aligned.
570   if (VT.bitsLT(MVT::i32))
571     return false;
572 
573   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
574   // byte-address are ignored, thus forcing Dword alignment.
575   // This applies to private, global, and constant memory.
576   if (IsFast)
577     *IsFast = true;
578 
579   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
580 }
581 
582 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
583                                           unsigned SrcAlign, bool IsMemset,
584                                           bool ZeroMemset,
585                                           bool MemcpyStrSrc,
586                                           MachineFunction &MF) const {
587   // FIXME: Should account for address space here.
588 
589   // The default fallback uses the private pointer size as a guess for a type to
590   // use. Make sure we switch these to 64-bit accesses.
591 
592   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
593     return MVT::v4i32;
594 
595   if (Size >= 8 && DstAlign >= 4)
596     return MVT::v2i32;
597 
598   // Use the default.
599   return MVT::Other;
600 }
601 
602 static bool isFlatGlobalAddrSpace(unsigned AS) {
603   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
604          AS == AMDGPUAS::FLAT_ADDRESS ||
605          AS == AMDGPUAS::CONSTANT_ADDRESS;
606 }
607 
608 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
609                                            unsigned DestAS) const {
610   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
611 }
612 
613 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
614   const MemSDNode *MemNode = cast<MemSDNode>(N);
615   const Value *Ptr = MemNode->getMemOperand()->getValue();
616   const Instruction *I = dyn_cast<Instruction>(Ptr);
617   return I && I->getMetadata("amdgpu.noclobber");
618 }
619 
620 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
621                                             unsigned DestAS) const {
622   // Flat -> private/local is a simple truncate.
623   // Flat -> global is no-op
624   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
625     return true;
626 
627   return isNoopAddrSpaceCast(SrcAS, DestAS);
628 }
629 
630 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
631   const MemSDNode *MemNode = cast<MemSDNode>(N);
632   const Value *Ptr = MemNode->getMemOperand()->getValue();
633 
634   // UndefValue means this is a load of a kernel input.  These are uniform.
635   // Sometimes LDS instructions have constant pointers.
636   // If Ptr is null, then that means this mem operand contains a
637   // PseudoSourceValue like GOT.
638   if (!Ptr || isa<UndefValue>(Ptr) || isa<Argument>(Ptr) ||
639       isa<Constant>(Ptr) || isa<GlobalValue>(Ptr))
640     return true;
641 
642   const Instruction *I = dyn_cast<Instruction>(Ptr);
643   return I && I->getMetadata("amdgpu.uniform");
644 }
645 
646 TargetLoweringBase::LegalizeTypeAction
647 SITargetLowering::getPreferredVectorAction(EVT VT) const {
648   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
649     return TypeSplitVector;
650 
651   return TargetLoweringBase::getPreferredVectorAction(VT);
652 }
653 
654 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
655                                                          Type *Ty) const {
656   // FIXME: Could be smarter if called for vector constants.
657   return true;
658 }
659 
660 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
661   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
662     switch (Op) {
663     case ISD::LOAD:
664     case ISD::STORE:
665 
666     // These operations are done with 32-bit instructions anyway.
667     case ISD::AND:
668     case ISD::OR:
669     case ISD::XOR:
670     case ISD::SELECT:
671       // TODO: Extensions?
672       return true;
673     default:
674       return false;
675     }
676   }
677 
678   // SimplifySetCC uses this function to determine whether or not it should
679   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
680   if (VT == MVT::i1 && Op == ISD::SETCC)
681     return false;
682 
683   return TargetLowering::isTypeDesirableForOp(Op, VT);
684 }
685 
686 SDValue SITargetLowering::LowerParameterPtr(SelectionDAG &DAG,
687                                             const SDLoc &SL, SDValue Chain,
688                                             unsigned Offset) const {
689   const DataLayout &DL = DAG.getDataLayout();
690   MachineFunction &MF = DAG.getMachineFunction();
691   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
692   unsigned InputPtrReg = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
693 
694   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
695   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
696   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
697                                        MRI.getLiveInVirtReg(InputPtrReg), PtrVT);
698   return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
699                      DAG.getConstant(Offset, SL, PtrVT));
700 }
701 
702 SDValue SITargetLowering::LowerParameter(SelectionDAG &DAG, EVT VT, EVT MemVT,
703                                          const SDLoc &SL, SDValue Chain,
704                                          unsigned Offset, bool Signed) const {
705   const DataLayout &DL = DAG.getDataLayout();
706   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
707   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
708   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
709 
710   unsigned Align = DL.getABITypeAlignment(Ty);
711 
712   SDValue Ptr = LowerParameterPtr(DAG, SL, Chain, Offset);
713   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
714                              MachineMemOperand::MONonTemporal |
715                              MachineMemOperand::MODereferenceable |
716                              MachineMemOperand::MOInvariant);
717 
718   SDValue Val;
719   if (MemVT.isFloatingPoint())
720     Val = getFPExtOrFPTrunc(DAG, Load, SL, VT);
721   else if (Signed)
722     Val = DAG.getSExtOrTrunc(Load, SL, VT);
723   else
724     Val = DAG.getZExtOrTrunc(Load, SL, VT);
725 
726   SDValue Ops[] = {
727     Val,
728     Load.getValue(1)
729   };
730 
731   return DAG.getMergeValues(Ops, SL);
732 }
733 
734 SDValue SITargetLowering::LowerFormalArguments(
735     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
736     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
737     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
738   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
739 
740   MachineFunction &MF = DAG.getMachineFunction();
741   FunctionType *FType = MF.getFunction()->getFunctionType();
742   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
743   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
744 
745   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
746     const Function *Fn = MF.getFunction();
747     DiagnosticInfoUnsupported NoGraphicsHSA(
748         *Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
749     DAG.getContext()->diagnose(NoGraphicsHSA);
750     return DAG.getEntryNode();
751   }
752 
753   // Create stack objects that are used for emitting debugger prologue if
754   // "amdgpu-debugger-emit-prologue" attribute was specified.
755   if (ST.debuggerEmitPrologue())
756     createDebuggerPrologueStackObjects(MF);
757 
758   SmallVector<ISD::InputArg, 16> Splits;
759   BitVector Skipped(Ins.size());
760 
761   for (unsigned i = 0, e = Ins.size(), PSInputNum = 0; i != e; ++i) {
762     const ISD::InputArg &Arg = Ins[i];
763 
764     // First check if it's a PS input addr
765     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
766         !Arg.Flags.isByVal() && PSInputNum <= 15) {
767 
768       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
769         // We can safely skip PS inputs
770         Skipped.set(i);
771         ++PSInputNum;
772         continue;
773       }
774 
775       Info->markPSInputAllocated(PSInputNum);
776       if (Arg.Used)
777         Info->PSInputEna |= 1 << PSInputNum;
778 
779       ++PSInputNum;
780     }
781 
782     if (AMDGPU::isShader(CallConv)) {
783       // Second split vertices into their elements
784       if (Arg.VT.isVector()) {
785         ISD::InputArg NewArg = Arg;
786         NewArg.Flags.setSplit();
787         NewArg.VT = Arg.VT.getVectorElementType();
788 
789         // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
790         // three or five element vertex only needs three or five registers,
791         // NOT four or eight.
792         Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
793         unsigned NumElements = ParamType->getVectorNumElements();
794 
795         for (unsigned j = 0; j != NumElements; ++j) {
796           Splits.push_back(NewArg);
797           NewArg.PartOffset += NewArg.VT.getStoreSize();
798         }
799       } else {
800         Splits.push_back(Arg);
801       }
802     }
803   }
804 
805   SmallVector<CCValAssign, 16> ArgLocs;
806   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
807                  *DAG.getContext());
808 
809   // At least one interpolation mode must be enabled or else the GPU will hang.
810   //
811   // Check PSInputAddr instead of PSInputEna. The idea is that if the user set
812   // PSInputAddr, the user wants to enable some bits after the compilation
813   // based on run-time states. Since we can't know what the final PSInputEna
814   // will look like, so we shouldn't do anything here and the user should take
815   // responsibility for the correct programming.
816   //
817   // Otherwise, the following restrictions apply:
818   // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
819   // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
820   //   enabled too.
821   if (CallConv == CallingConv::AMDGPU_PS &&
822       ((Info->getPSInputAddr() & 0x7F) == 0 ||
823        ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11)))) {
824     CCInfo.AllocateReg(AMDGPU::VGPR0);
825     CCInfo.AllocateReg(AMDGPU::VGPR1);
826     Info->markPSInputAllocated(0);
827     Info->PSInputEna |= 1;
828   }
829 
830   if (!AMDGPU::isShader(CallConv)) {
831     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
832   } else {
833     assert(!Info->hasPrivateSegmentBuffer() && !Info->hasDispatchPtr() &&
834            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
835            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
836            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
837            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
838            !Info->hasWorkItemIDZ());
839   }
840 
841   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
842   if (Info->hasPrivateSegmentBuffer()) {
843     unsigned PrivateSegmentBufferReg = Info->addPrivateSegmentBuffer(*TRI);
844     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SReg_128RegClass);
845     CCInfo.AllocateReg(PrivateSegmentBufferReg);
846   }
847 
848   if (Info->hasDispatchPtr()) {
849     unsigned DispatchPtrReg = Info->addDispatchPtr(*TRI);
850     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
851     CCInfo.AllocateReg(DispatchPtrReg);
852   }
853 
854   if (Info->hasQueuePtr()) {
855     unsigned QueuePtrReg = Info->addQueuePtr(*TRI);
856     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
857     CCInfo.AllocateReg(QueuePtrReg);
858   }
859 
860   if (Info->hasKernargSegmentPtr()) {
861     unsigned InputPtrReg = Info->addKernargSegmentPtr(*TRI);
862     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
863     CCInfo.AllocateReg(InputPtrReg);
864   }
865 
866   if (Info->hasDispatchID()) {
867     unsigned DispatchIDReg = Info->addDispatchID(*TRI);
868     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
869     CCInfo.AllocateReg(DispatchIDReg);
870   }
871 
872   if (Info->hasFlatScratchInit()) {
873     unsigned FlatScratchInitReg = Info->addFlatScratchInit(*TRI);
874     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
875     CCInfo.AllocateReg(FlatScratchInitReg);
876   }
877 
878   if (!AMDGPU::isShader(CallConv))
879     analyzeFormalArgumentsCompute(CCInfo, Ins);
880   else
881     AnalyzeFormalArguments(CCInfo, Splits);
882 
883   SmallVector<SDValue, 16> Chains;
884 
885   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
886 
887     const ISD::InputArg &Arg = Ins[i];
888     if (Skipped[i]) {
889       InVals.push_back(DAG.getUNDEF(Arg.VT));
890       continue;
891     }
892 
893     CCValAssign &VA = ArgLocs[ArgIdx++];
894     MVT VT = VA.getLocVT();
895 
896     if (VA.isMemLoc()) {
897       VT = Ins[i].VT;
898       EVT MemVT = VA.getLocVT();
899       const unsigned Offset = Subtarget->getExplicitKernelArgOffset() +
900                               VA.getLocMemOffset();
901       // The first 36 bytes of the input buffer contains information about
902       // thread group and global sizes.
903       SDValue Arg = LowerParameter(DAG, VT, MemVT,  DL, Chain,
904                                    Offset, Ins[i].Flags.isSExt());
905       Chains.push_back(Arg.getValue(1));
906 
907       auto *ParamTy =
908         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
909       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
910           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
911         // On SI local pointers are just offsets into LDS, so they are always
912         // less than 16-bits.  On CI and newer they could potentially be
913         // real pointers, so we can't guarantee their size.
914         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
915                           DAG.getValueType(MVT::i16));
916       }
917 
918       InVals.push_back(Arg);
919       Info->setABIArgOffset(Offset + MemVT.getStoreSize());
920       continue;
921     }
922     assert(VA.isRegLoc() && "Parameter must be in a register!");
923 
924     unsigned Reg = VA.getLocReg();
925 
926     if (VT == MVT::i64) {
927       // For now assume it is a pointer
928       Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0,
929                                      &AMDGPU::SGPR_64RegClass);
930       Reg = MF.addLiveIn(Reg, &AMDGPU::SGPR_64RegClass);
931       SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
932       InVals.push_back(Copy);
933       continue;
934     }
935 
936     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
937 
938     Reg = MF.addLiveIn(Reg, RC);
939     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
940 
941     if (Arg.VT.isVector()) {
942 
943       // Build a vector from the registers
944       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
945       unsigned NumElements = ParamType->getVectorNumElements();
946 
947       SmallVector<SDValue, 4> Regs;
948       Regs.push_back(Val);
949       for (unsigned j = 1; j != NumElements; ++j) {
950         Reg = ArgLocs[ArgIdx++].getLocReg();
951         Reg = MF.addLiveIn(Reg, RC);
952 
953         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
954         Regs.push_back(Copy);
955       }
956 
957       // Fill up the missing vector elements
958       NumElements = Arg.VT.getVectorNumElements() - NumElements;
959       Regs.append(NumElements, DAG.getUNDEF(VT));
960 
961       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
962       continue;
963     }
964 
965     InVals.push_back(Val);
966   }
967 
968   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
969   // these from the dispatch pointer.
970 
971   // Start adding system SGPRs.
972   if (Info->hasWorkGroupIDX()) {
973     unsigned Reg = Info->addWorkGroupIDX();
974     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
975     CCInfo.AllocateReg(Reg);
976   }
977 
978   if (Info->hasWorkGroupIDY()) {
979     unsigned Reg = Info->addWorkGroupIDY();
980     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
981     CCInfo.AllocateReg(Reg);
982   }
983 
984   if (Info->hasWorkGroupIDZ()) {
985     unsigned Reg = Info->addWorkGroupIDZ();
986     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
987     CCInfo.AllocateReg(Reg);
988   }
989 
990   if (Info->hasWorkGroupInfo()) {
991     unsigned Reg = Info->addWorkGroupInfo();
992     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
993     CCInfo.AllocateReg(Reg);
994   }
995 
996   if (Info->hasPrivateSegmentWaveByteOffset()) {
997     // Scratch wave offset passed in system SGPR.
998     unsigned PrivateSegmentWaveByteOffsetReg;
999 
1000     if (AMDGPU::isShader(CallConv)) {
1001       PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1002       Info->setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1003     } else
1004       PrivateSegmentWaveByteOffsetReg = Info->addPrivateSegmentWaveByteOffset();
1005 
1006     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1007     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1008   }
1009 
1010   // Now that we've figured out where the scratch register inputs are, see if
1011   // should reserve the arguments and use them directly.
1012   bool HasStackObjects = MF.getFrameInfo().hasStackObjects();
1013   // Record that we know we have non-spill stack objects so we don't need to
1014   // check all stack objects later.
1015   if (HasStackObjects)
1016     Info->setHasNonSpillStackObjects(true);
1017 
1018   // Everything live out of a block is spilled with fast regalloc, so it's
1019   // almost certain that spilling will be required.
1020   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
1021     HasStackObjects = true;
1022 
1023   if (ST.isAmdCodeObjectV2()) {
1024     if (HasStackObjects) {
1025       // If we have stack objects, we unquestionably need the private buffer
1026       // resource. For the Code Object V2 ABI, this will be the first 4 user
1027       // SGPR inputs. We can reserve those and use them directly.
1028 
1029       unsigned PrivateSegmentBufferReg = TRI->getPreloadedValue(
1030         MF, SIRegisterInfo::PRIVATE_SEGMENT_BUFFER);
1031       Info->setScratchRSrcReg(PrivateSegmentBufferReg);
1032 
1033       unsigned PrivateSegmentWaveByteOffsetReg = TRI->getPreloadedValue(
1034         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1035       Info->setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1036     } else {
1037       unsigned ReservedBufferReg
1038         = TRI->reservedPrivateSegmentBufferReg(MF);
1039       unsigned ReservedOffsetReg
1040         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1041 
1042       // We tentatively reserve the last registers (skipping the last two
1043       // which may contain VCC). After register allocation, we'll replace
1044       // these with the ones immediately after those which were really
1045       // allocated. In the prologue copies will be inserted from the argument
1046       // to these reserved registers.
1047       Info->setScratchRSrcReg(ReservedBufferReg);
1048       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1049     }
1050   } else {
1051     unsigned ReservedBufferReg = TRI->reservedPrivateSegmentBufferReg(MF);
1052 
1053     // Without HSA, relocations are used for the scratch pointer and the
1054     // buffer resource setup is always inserted in the prologue. Scratch wave
1055     // offset is still in an input SGPR.
1056     Info->setScratchRSrcReg(ReservedBufferReg);
1057 
1058     if (HasStackObjects) {
1059       unsigned ScratchWaveOffsetReg = TRI->getPreloadedValue(
1060         MF, SIRegisterInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1061       Info->setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1062     } else {
1063       unsigned ReservedOffsetReg
1064         = TRI->reservedPrivateSegmentWaveByteOffsetReg(MF);
1065       Info->setScratchWaveOffsetReg(ReservedOffsetReg);
1066     }
1067   }
1068 
1069   if (Info->hasWorkItemIDX()) {
1070     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X);
1071     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1072     CCInfo.AllocateReg(Reg);
1073   }
1074 
1075   if (Info->hasWorkItemIDY()) {
1076     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y);
1077     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1078     CCInfo.AllocateReg(Reg);
1079   }
1080 
1081   if (Info->hasWorkItemIDZ()) {
1082     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z);
1083     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1084     CCInfo.AllocateReg(Reg);
1085   }
1086 
1087   if (Chains.empty())
1088     return Chain;
1089 
1090   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1091 }
1092 
1093 SDValue
1094 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1095                               bool isVarArg,
1096                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1097                               const SmallVectorImpl<SDValue> &OutVals,
1098                               const SDLoc &DL, SelectionDAG &DAG) const {
1099   MachineFunction &MF = DAG.getMachineFunction();
1100   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1101 
1102   if (!AMDGPU::isShader(CallConv))
1103     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1104                                              OutVals, DL, DAG);
1105 
1106   Info->setIfReturnsVoid(Outs.size() == 0);
1107 
1108   SmallVector<ISD::OutputArg, 48> Splits;
1109   SmallVector<SDValue, 48> SplitVals;
1110 
1111   // Split vectors into their elements.
1112   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1113     const ISD::OutputArg &Out = Outs[i];
1114 
1115     if (Out.VT.isVector()) {
1116       MVT VT = Out.VT.getVectorElementType();
1117       ISD::OutputArg NewOut = Out;
1118       NewOut.Flags.setSplit();
1119       NewOut.VT = VT;
1120 
1121       // We want the original number of vector elements here, e.g.
1122       // three or five, not four or eight.
1123       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1124 
1125       for (unsigned j = 0; j != NumElements; ++j) {
1126         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1127                                    DAG.getConstant(j, DL, MVT::i32));
1128         SplitVals.push_back(Elem);
1129         Splits.push_back(NewOut);
1130         NewOut.PartOffset += NewOut.VT.getStoreSize();
1131       }
1132     } else {
1133       SplitVals.push_back(OutVals[i]);
1134       Splits.push_back(Out);
1135     }
1136   }
1137 
1138   // CCValAssign - represent the assignment of the return value to a location.
1139   SmallVector<CCValAssign, 48> RVLocs;
1140 
1141   // CCState - Info about the registers and stack slots.
1142   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1143                  *DAG.getContext());
1144 
1145   // Analyze outgoing return values.
1146   AnalyzeReturn(CCInfo, Splits);
1147 
1148   SDValue Flag;
1149   SmallVector<SDValue, 48> RetOps;
1150   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1151 
1152   // Copy the result values into the output registers.
1153   for (unsigned i = 0, realRVLocIdx = 0;
1154        i != RVLocs.size();
1155        ++i, ++realRVLocIdx) {
1156     CCValAssign &VA = RVLocs[i];
1157     assert(VA.isRegLoc() && "Can only return in registers!");
1158 
1159     SDValue Arg = SplitVals[realRVLocIdx];
1160 
1161     // Copied from other backends.
1162     switch (VA.getLocInfo()) {
1163     default: llvm_unreachable("Unknown loc info!");
1164     case CCValAssign::Full:
1165       break;
1166     case CCValAssign::BCvt:
1167       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1168       break;
1169     }
1170 
1171     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
1172     Flag = Chain.getValue(1);
1173     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1174   }
1175 
1176   // Update chain and glue.
1177   RetOps[0] = Chain;
1178   if (Flag.getNode())
1179     RetOps.push_back(Flag);
1180 
1181   unsigned Opc = Info->returnsVoid() ? AMDGPUISD::ENDPGM : AMDGPUISD::RETURN;
1182   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
1183 }
1184 
1185 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
1186                                              SelectionDAG &DAG) const {
1187   unsigned Reg = StringSwitch<unsigned>(RegName)
1188     .Case("m0", AMDGPU::M0)
1189     .Case("exec", AMDGPU::EXEC)
1190     .Case("exec_lo", AMDGPU::EXEC_LO)
1191     .Case("exec_hi", AMDGPU::EXEC_HI)
1192     .Case("flat_scratch", AMDGPU::FLAT_SCR)
1193     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
1194     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
1195     .Default(AMDGPU::NoRegister);
1196 
1197   if (Reg == AMDGPU::NoRegister) {
1198     report_fatal_error(Twine("invalid register name \""
1199                              + StringRef(RegName)  + "\"."));
1200 
1201   }
1202 
1203   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1204       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
1205     report_fatal_error(Twine("invalid register \""
1206                              + StringRef(RegName)  + "\" for subtarget."));
1207   }
1208 
1209   switch (Reg) {
1210   case AMDGPU::M0:
1211   case AMDGPU::EXEC_LO:
1212   case AMDGPU::EXEC_HI:
1213   case AMDGPU::FLAT_SCR_LO:
1214   case AMDGPU::FLAT_SCR_HI:
1215     if (VT.getSizeInBits() == 32)
1216       return Reg;
1217     break;
1218   case AMDGPU::EXEC:
1219   case AMDGPU::FLAT_SCR:
1220     if (VT.getSizeInBits() == 64)
1221       return Reg;
1222     break;
1223   default:
1224     llvm_unreachable("missing register type checking");
1225   }
1226 
1227   report_fatal_error(Twine("invalid type for register \""
1228                            + StringRef(RegName) + "\"."));
1229 }
1230 
1231 // If kill is not the last instruction, split the block so kill is always a
1232 // proper terminator.
1233 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
1234                                                     MachineBasicBlock *BB) const {
1235   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1236 
1237   MachineBasicBlock::iterator SplitPoint(&MI);
1238   ++SplitPoint;
1239 
1240   if (SplitPoint == BB->end()) {
1241     // Don't bother with a new block.
1242     MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1243     return BB;
1244   }
1245 
1246   MachineFunction *MF = BB->getParent();
1247   MachineBasicBlock *SplitBB
1248     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
1249 
1250   MF->insert(++MachineFunction::iterator(BB), SplitBB);
1251   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
1252 
1253   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
1254   BB->addSuccessor(SplitBB);
1255 
1256   MI.setDesc(TII->get(AMDGPU::SI_KILL_TERMINATOR));
1257   return SplitBB;
1258 }
1259 
1260 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
1261 // wavefront. If the value is uniform and just happens to be in a VGPR, this
1262 // will only do one iteration. In the worst case, this will loop 64 times.
1263 //
1264 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
1265 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
1266   const SIInstrInfo *TII,
1267   MachineRegisterInfo &MRI,
1268   MachineBasicBlock &OrigBB,
1269   MachineBasicBlock &LoopBB,
1270   const DebugLoc &DL,
1271   const MachineOperand &IdxReg,
1272   unsigned InitReg,
1273   unsigned ResultReg,
1274   unsigned PhiReg,
1275   unsigned InitSaveExecReg,
1276   int Offset,
1277   bool UseGPRIdxMode) {
1278   MachineBasicBlock::iterator I = LoopBB.begin();
1279 
1280   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1281   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1282   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1283   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1284 
1285   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
1286     .addReg(InitReg)
1287     .addMBB(&OrigBB)
1288     .addReg(ResultReg)
1289     .addMBB(&LoopBB);
1290 
1291   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
1292     .addReg(InitSaveExecReg)
1293     .addMBB(&OrigBB)
1294     .addReg(NewExec)
1295     .addMBB(&LoopBB);
1296 
1297   // Read the next variant <- also loop target.
1298   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
1299     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
1300 
1301   // Compare the just read M0 value to all possible Idx values.
1302   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
1303     .addReg(CurrentIdxReg)
1304     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
1305 
1306   if (UseGPRIdxMode) {
1307     unsigned IdxReg;
1308     if (Offset == 0) {
1309       IdxReg = CurrentIdxReg;
1310     } else {
1311       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
1312       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
1313         .addReg(CurrentIdxReg, RegState::Kill)
1314         .addImm(Offset);
1315     }
1316 
1317     MachineInstr *SetIdx =
1318       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
1319       .addReg(IdxReg, RegState::Kill);
1320     SetIdx->getOperand(2).setIsUndef();
1321   } else {
1322     // Move index from VCC into M0
1323     if (Offset == 0) {
1324       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1325         .addReg(CurrentIdxReg, RegState::Kill);
1326     } else {
1327       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1328         .addReg(CurrentIdxReg, RegState::Kill)
1329         .addImm(Offset);
1330     }
1331   }
1332 
1333   // Update EXEC, save the original EXEC value to VCC.
1334   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
1335     .addReg(CondReg, RegState::Kill);
1336 
1337   MRI.setSimpleHint(NewExec, CondReg);
1338 
1339   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
1340   MachineInstr *InsertPt =
1341     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
1342     .addReg(AMDGPU::EXEC)
1343     .addReg(NewExec);
1344 
1345   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
1346   // s_cbranch_scc0?
1347 
1348   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
1349   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
1350     .addMBB(&LoopBB);
1351 
1352   return InsertPt->getIterator();
1353 }
1354 
1355 // This has slightly sub-optimal regalloc when the source vector is killed by
1356 // the read. The register allocator does not understand that the kill is
1357 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
1358 // subregister from it, using 1 more VGPR than necessary. This was saved when
1359 // this was expanded after register allocation.
1360 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
1361                                                   MachineBasicBlock &MBB,
1362                                                   MachineInstr &MI,
1363                                                   unsigned InitResultReg,
1364                                                   unsigned PhiReg,
1365                                                   int Offset,
1366                                                   bool UseGPRIdxMode) {
1367   MachineFunction *MF = MBB.getParent();
1368   MachineRegisterInfo &MRI = MF->getRegInfo();
1369   const DebugLoc &DL = MI.getDebugLoc();
1370   MachineBasicBlock::iterator I(&MI);
1371 
1372   unsigned DstReg = MI.getOperand(0).getReg();
1373   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1374   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
1375 
1376   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
1377 
1378   // Save the EXEC mask
1379   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
1380     .addReg(AMDGPU::EXEC);
1381 
1382   // To insert the loop we need to split the block. Move everything after this
1383   // point to a new block, and insert a new empty block between the two.
1384   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
1385   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
1386   MachineFunction::iterator MBBI(MBB);
1387   ++MBBI;
1388 
1389   MF->insert(MBBI, LoopBB);
1390   MF->insert(MBBI, RemainderBB);
1391 
1392   LoopBB->addSuccessor(LoopBB);
1393   LoopBB->addSuccessor(RemainderBB);
1394 
1395   // Move the rest of the block into a new block.
1396   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
1397   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
1398 
1399   MBB.addSuccessor(LoopBB);
1400 
1401   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1402 
1403   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
1404                                       InitResultReg, DstReg, PhiReg, TmpExec,
1405                                       Offset, UseGPRIdxMode);
1406 
1407   MachineBasicBlock::iterator First = RemainderBB->begin();
1408   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
1409     .addReg(SaveExec);
1410 
1411   return InsPt;
1412 }
1413 
1414 // Returns subreg index, offset
1415 static std::pair<unsigned, int>
1416 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
1417                             const TargetRegisterClass *SuperRC,
1418                             unsigned VecReg,
1419                             int Offset) {
1420   int NumElts = SuperRC->getSize() / 4;
1421 
1422   // Skip out of bounds offsets, or else we would end up using an undefined
1423   // register.
1424   if (Offset >= NumElts || Offset < 0)
1425     return std::make_pair(AMDGPU::sub0, Offset);
1426 
1427   return std::make_pair(AMDGPU::sub0 + Offset, 0);
1428 }
1429 
1430 // Return true if the index is an SGPR and was set.
1431 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
1432                                  MachineRegisterInfo &MRI,
1433                                  MachineInstr &MI,
1434                                  int Offset,
1435                                  bool UseGPRIdxMode,
1436                                  bool IsIndirectSrc) {
1437   MachineBasicBlock *MBB = MI.getParent();
1438   const DebugLoc &DL = MI.getDebugLoc();
1439   MachineBasicBlock::iterator I(&MI);
1440 
1441   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1442   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
1443 
1444   assert(Idx->getReg() != AMDGPU::NoRegister);
1445 
1446   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
1447     return false;
1448 
1449   if (UseGPRIdxMode) {
1450     unsigned IdxMode = IsIndirectSrc ?
1451       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
1452     if (Offset == 0) {
1453       MachineInstr *SetOn =
1454         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1455         .addOperand(*Idx)
1456         .addImm(IdxMode);
1457 
1458       SetOn->getOperand(3).setIsUndef();
1459     } else {
1460       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
1461       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
1462         .addOperand(*Idx)
1463         .addImm(Offset);
1464       MachineInstr *SetOn =
1465         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1466         .addReg(Tmp, RegState::Kill)
1467         .addImm(IdxMode);
1468 
1469       SetOn->getOperand(3).setIsUndef();
1470     }
1471 
1472     return true;
1473   }
1474 
1475   if (Offset == 0) {
1476     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1477       .addOperand(*Idx);
1478   } else {
1479     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
1480       .addOperand(*Idx)
1481       .addImm(Offset);
1482   }
1483 
1484   return true;
1485 }
1486 
1487 // Control flow needs to be inserted if indexing with a VGPR.
1488 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
1489                                           MachineBasicBlock &MBB,
1490                                           const SISubtarget &ST) {
1491   const SIInstrInfo *TII = ST.getInstrInfo();
1492   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1493   MachineFunction *MF = MBB.getParent();
1494   MachineRegisterInfo &MRI = MF->getRegInfo();
1495 
1496   unsigned Dst = MI.getOperand(0).getReg();
1497   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
1498   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1499 
1500   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
1501 
1502   unsigned SubReg;
1503   std::tie(SubReg, Offset)
1504     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
1505 
1506   bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1507 
1508   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
1509     MachineBasicBlock::iterator I(&MI);
1510     const DebugLoc &DL = MI.getDebugLoc();
1511 
1512     if (UseGPRIdxMode) {
1513       // TODO: Look at the uses to avoid the copy. This may require rescheduling
1514       // to avoid interfering with other uses, so probably requires a new
1515       // optimization pass.
1516       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1517         .addReg(SrcReg, RegState::Undef, SubReg)
1518         .addReg(SrcReg, RegState::Implicit)
1519         .addReg(AMDGPU::M0, RegState::Implicit);
1520       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1521     } else {
1522       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1523         .addReg(SrcReg, RegState::Undef, SubReg)
1524         .addReg(SrcReg, RegState::Implicit);
1525     }
1526 
1527     MI.eraseFromParent();
1528 
1529     return &MBB;
1530   }
1531 
1532 
1533   const DebugLoc &DL = MI.getDebugLoc();
1534   MachineBasicBlock::iterator I(&MI);
1535 
1536   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1537   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1538 
1539   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
1540 
1541   if (UseGPRIdxMode) {
1542     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1543       .addImm(0) // Reset inside loop.
1544       .addImm(VGPRIndexMode::SRC0_ENABLE);
1545     SetOn->getOperand(3).setIsUndef();
1546 
1547     // Disable again after the loop.
1548     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1549   }
1550 
1551   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
1552   MachineBasicBlock *LoopBB = InsPt->getParent();
1553 
1554   if (UseGPRIdxMode) {
1555     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
1556       .addReg(SrcReg, RegState::Undef, SubReg)
1557       .addReg(SrcReg, RegState::Implicit)
1558       .addReg(AMDGPU::M0, RegState::Implicit);
1559   } else {
1560     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
1561       .addReg(SrcReg, RegState::Undef, SubReg)
1562       .addReg(SrcReg, RegState::Implicit);
1563   }
1564 
1565   MI.eraseFromParent();
1566 
1567   return LoopBB;
1568 }
1569 
1570 static unsigned getMOVRELDPseudo(const TargetRegisterClass *VecRC) {
1571   switch (VecRC->getSize()) {
1572   case 4:
1573     return AMDGPU::V_MOVRELD_B32_V1;
1574   case 8:
1575     return AMDGPU::V_MOVRELD_B32_V2;
1576   case 16:
1577     return AMDGPU::V_MOVRELD_B32_V4;
1578   case 32:
1579     return AMDGPU::V_MOVRELD_B32_V8;
1580   case 64:
1581     return AMDGPU::V_MOVRELD_B32_V16;
1582   default:
1583     llvm_unreachable("unsupported size for MOVRELD pseudos");
1584   }
1585 }
1586 
1587 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
1588                                           MachineBasicBlock &MBB,
1589                                           const SISubtarget &ST) {
1590   const SIInstrInfo *TII = ST.getInstrInfo();
1591   const SIRegisterInfo &TRI = TII->getRegisterInfo();
1592   MachineFunction *MF = MBB.getParent();
1593   MachineRegisterInfo &MRI = MF->getRegInfo();
1594 
1595   unsigned Dst = MI.getOperand(0).getReg();
1596   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
1597   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
1598   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
1599   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
1600   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
1601 
1602   // This can be an immediate, but will be folded later.
1603   assert(Val->getReg());
1604 
1605   unsigned SubReg;
1606   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
1607                                                          SrcVec->getReg(),
1608                                                          Offset);
1609   bool UseGPRIdxMode = ST.hasVGPRIndexMode() && EnableVGPRIndexMode;
1610 
1611   if (Idx->getReg() == AMDGPU::NoRegister) {
1612     MachineBasicBlock::iterator I(&MI);
1613     const DebugLoc &DL = MI.getDebugLoc();
1614 
1615     assert(Offset == 0);
1616 
1617     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
1618       .addOperand(*SrcVec)
1619       .addOperand(*Val)
1620       .addImm(SubReg);
1621 
1622     MI.eraseFromParent();
1623     return &MBB;
1624   }
1625 
1626   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
1627     MachineBasicBlock::iterator I(&MI);
1628     const DebugLoc &DL = MI.getDebugLoc();
1629 
1630     if (UseGPRIdxMode) {
1631       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1632         .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
1633         .addOperand(*Val)
1634         .addReg(Dst, RegState::ImplicitDefine)
1635         .addReg(SrcVec->getReg(), RegState::Implicit)
1636         .addReg(AMDGPU::M0, RegState::Implicit);
1637 
1638       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1639     } else {
1640       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1641 
1642       BuildMI(MBB, I, DL, MovRelDesc)
1643           .addReg(Dst, RegState::Define)
1644           .addReg(SrcVec->getReg())
1645           .addOperand(*Val)
1646           .addImm(SubReg - AMDGPU::sub0);
1647     }
1648 
1649     MI.eraseFromParent();
1650     return &MBB;
1651   }
1652 
1653   if (Val->isReg())
1654     MRI.clearKillFlags(Val->getReg());
1655 
1656   const DebugLoc &DL = MI.getDebugLoc();
1657 
1658   if (UseGPRIdxMode) {
1659     MachineBasicBlock::iterator I(&MI);
1660 
1661     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
1662       .addImm(0) // Reset inside loop.
1663       .addImm(VGPRIndexMode::DST_ENABLE);
1664     SetOn->getOperand(3).setIsUndef();
1665 
1666     // Disable again after the loop.
1667     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
1668   }
1669 
1670   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
1671 
1672   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
1673                               Offset, UseGPRIdxMode);
1674   MachineBasicBlock *LoopBB = InsPt->getParent();
1675 
1676   if (UseGPRIdxMode) {
1677     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
1678       .addReg(PhiReg, RegState::Undef, SubReg) // vdst
1679       .addOperand(*Val) // src0
1680       .addReg(Dst, RegState::ImplicitDefine)
1681       .addReg(PhiReg, RegState::Implicit)
1682       .addReg(AMDGPU::M0, RegState::Implicit);
1683   } else {
1684     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(VecRC));
1685 
1686     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
1687         .addReg(Dst, RegState::Define)
1688         .addReg(PhiReg)
1689         .addOperand(*Val)
1690         .addImm(SubReg - AMDGPU::sub0);
1691   }
1692 
1693   MI.eraseFromParent();
1694 
1695   return LoopBB;
1696 }
1697 
1698 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
1699   MachineInstr &MI, MachineBasicBlock *BB) const {
1700   switch (MI.getOpcode()) {
1701   case AMDGPU::SI_INIT_M0: {
1702     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1703     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
1704             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1705       .addOperand(MI.getOperand(0));
1706     MI.eraseFromParent();
1707     return BB;
1708   }
1709   case AMDGPU::GET_GROUPSTATICSIZE: {
1710     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1711 
1712     MachineFunction *MF = BB->getParent();
1713     SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1714     DebugLoc DL = MI.getDebugLoc();
1715     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
1716       .addOperand(MI.getOperand(0))
1717       .addImm(MFI->getLDSSize());
1718     MI.eraseFromParent();
1719     return BB;
1720   }
1721   case AMDGPU::SI_INDIRECT_SRC_V1:
1722   case AMDGPU::SI_INDIRECT_SRC_V2:
1723   case AMDGPU::SI_INDIRECT_SRC_V4:
1724   case AMDGPU::SI_INDIRECT_SRC_V8:
1725   case AMDGPU::SI_INDIRECT_SRC_V16:
1726     return emitIndirectSrc(MI, *BB, *getSubtarget());
1727   case AMDGPU::SI_INDIRECT_DST_V1:
1728   case AMDGPU::SI_INDIRECT_DST_V2:
1729   case AMDGPU::SI_INDIRECT_DST_V4:
1730   case AMDGPU::SI_INDIRECT_DST_V8:
1731   case AMDGPU::SI_INDIRECT_DST_V16:
1732     return emitIndirectDst(MI, *BB, *getSubtarget());
1733   case AMDGPU::SI_KILL:
1734     return splitKillBlock(MI, BB);
1735   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
1736     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
1737     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
1738 
1739     unsigned Dst = MI.getOperand(0).getReg();
1740     unsigned Src0 = MI.getOperand(1).getReg();
1741     unsigned Src1 = MI.getOperand(2).getReg();
1742     const DebugLoc &DL = MI.getDebugLoc();
1743     unsigned SrcCond = MI.getOperand(3).getReg();
1744 
1745     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1746     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1747 
1748     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
1749       .addReg(Src0, 0, AMDGPU::sub0)
1750       .addReg(Src1, 0, AMDGPU::sub0)
1751       .addReg(SrcCond);
1752     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
1753       .addReg(Src0, 0, AMDGPU::sub1)
1754       .addReg(Src1, 0, AMDGPU::sub1)
1755       .addReg(SrcCond);
1756 
1757     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
1758       .addReg(DstLo)
1759       .addImm(AMDGPU::sub0)
1760       .addReg(DstHi)
1761       .addImm(AMDGPU::sub1);
1762     MI.eraseFromParent();
1763     return BB;
1764   }
1765   default:
1766     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
1767   }
1768 }
1769 
1770 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1771   // This currently forces unfolding various combinations of fsub into fma with
1772   // free fneg'd operands. As long as we have fast FMA (controlled by
1773   // isFMAFasterThanFMulAndFAdd), we should perform these.
1774 
1775   // When fma is quarter rate, for f64 where add / sub are at best half rate,
1776   // most of these combines appear to be cycle neutral but save on instruction
1777   // count / code size.
1778   return true;
1779 }
1780 
1781 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
1782                                          EVT VT) const {
1783   if (!VT.isVector()) {
1784     return MVT::i1;
1785   }
1786   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
1787 }
1788 
1789 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT) const {
1790   return MVT::i32;
1791 }
1792 
1793 // Answering this is somewhat tricky and depends on the specific device which
1794 // have different rates for fma or all f64 operations.
1795 //
1796 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
1797 // regardless of which device (although the number of cycles differs between
1798 // devices), so it is always profitable for f64.
1799 //
1800 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
1801 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
1802 // which we can always do even without fused FP ops since it returns the same
1803 // result as the separate operations and since it is always full
1804 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
1805 // however does not support denormals, so we do report fma as faster if we have
1806 // a fast fma device and require denormals.
1807 //
1808 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
1809   VT = VT.getScalarType();
1810 
1811   if (!VT.isSimple())
1812     return false;
1813 
1814   switch (VT.getSimpleVT().SimpleTy) {
1815   case MVT::f32:
1816     // This is as fast on some subtargets. However, we always have full rate f32
1817     // mad available which returns the same result as the separate operations
1818     // which we should prefer over fma. We can't use this if we want to support
1819     // denormals, so only report this in these cases.
1820     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
1821   case MVT::f64:
1822     return true;
1823   default:
1824     break;
1825   }
1826 
1827   return false;
1828 }
1829 
1830 //===----------------------------------------------------------------------===//
1831 // Custom DAG Lowering Operations
1832 //===----------------------------------------------------------------------===//
1833 
1834 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1835   switch (Op.getOpcode()) {
1836   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
1837   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1838   case ISD::LOAD: {
1839     SDValue Result = LowerLOAD(Op, DAG);
1840     assert((!Result.getNode() ||
1841             Result.getNode()->getNumValues() == 2) &&
1842            "Load should return a value and a chain");
1843     return Result;
1844   }
1845 
1846   case ISD::FSIN:
1847   case ISD::FCOS:
1848     return LowerTrig(Op, DAG);
1849   case ISD::SELECT: return LowerSELECT(Op, DAG);
1850   case ISD::FDIV: return LowerFDIV(Op, DAG);
1851   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
1852   case ISD::STORE: return LowerSTORE(Op, DAG);
1853   case ISD::GlobalAddress: {
1854     MachineFunction &MF = DAG.getMachineFunction();
1855     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1856     return LowerGlobalAddress(MFI, Op, DAG);
1857   }
1858   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1859   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1860   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
1861   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
1862   case ISD::TRAP: return lowerTRAP(Op, DAG);
1863   case ISD::FP_ROUND:
1864     return lowerFP_ROUND(Op, DAG);
1865   }
1866   return SDValue();
1867 }
1868 
1869 /// \brief Helper function for LowerBRCOND
1870 static SDNode *findUser(SDValue Value, unsigned Opcode) {
1871 
1872   SDNode *Parent = Value.getNode();
1873   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
1874        I != E; ++I) {
1875 
1876     if (I.getUse().get() != Value)
1877       continue;
1878 
1879     if (I->getOpcode() == Opcode)
1880       return *I;
1881   }
1882   return nullptr;
1883 }
1884 
1885 bool SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
1886   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
1887     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
1888     case AMDGPUIntrinsic::amdgcn_if:
1889     case AMDGPUIntrinsic::amdgcn_else:
1890     case AMDGPUIntrinsic::amdgcn_end_cf:
1891     case AMDGPUIntrinsic::amdgcn_loop:
1892       return true;
1893     default:
1894       return false;
1895     }
1896   }
1897 
1898   if (Intr->getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
1899     switch (cast<ConstantSDNode>(Intr->getOperand(0))->getZExtValue()) {
1900     case AMDGPUIntrinsic::amdgcn_break:
1901     case AMDGPUIntrinsic::amdgcn_if_break:
1902     case AMDGPUIntrinsic::amdgcn_else_break:
1903       return true;
1904     default:
1905       return false;
1906     }
1907   }
1908 
1909   return false;
1910 }
1911 
1912 void SITargetLowering::createDebuggerPrologueStackObjects(
1913     MachineFunction &MF) const {
1914   // Create stack objects that are used for emitting debugger prologue.
1915   //
1916   // Debugger prologue writes work group IDs and work item IDs to scratch memory
1917   // at fixed location in the following format:
1918   //   offset 0:  work group ID x
1919   //   offset 4:  work group ID y
1920   //   offset 8:  work group ID z
1921   //   offset 16: work item ID x
1922   //   offset 20: work item ID y
1923   //   offset 24: work item ID z
1924   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1925   int ObjectIdx = 0;
1926 
1927   // For each dimension:
1928   for (unsigned i = 0; i < 3; ++i) {
1929     // Create fixed stack object for work group ID.
1930     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
1931     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
1932     // Create fixed stack object for work item ID.
1933     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
1934     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
1935   }
1936 }
1937 
1938 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
1939   const Triple &TT = getTargetMachine().getTargetTriple();
1940   return GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS &&
1941          AMDGPU::shouldEmitConstantsToTextSection(TT);
1942 }
1943 
1944 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
1945   return (GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
1946               GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
1947          !shouldEmitFixup(GV) &&
1948          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
1949 }
1950 
1951 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
1952   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
1953 }
1954 
1955 /// This transforms the control flow intrinsics to get the branch destination as
1956 /// last parameter, also switches branch target with BR if the need arise
1957 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
1958                                       SelectionDAG &DAG) const {
1959 
1960   SDLoc DL(BRCOND);
1961 
1962   SDNode *Intr = BRCOND.getOperand(1).getNode();
1963   SDValue Target = BRCOND.getOperand(2);
1964   SDNode *BR = nullptr;
1965   SDNode *SetCC = nullptr;
1966 
1967   if (Intr->getOpcode() == ISD::SETCC) {
1968     // As long as we negate the condition everything is fine
1969     SetCC = Intr;
1970     Intr = SetCC->getOperand(0).getNode();
1971 
1972   } else {
1973     // Get the target from BR if we don't negate the condition
1974     BR = findUser(BRCOND, ISD::BR);
1975     Target = BR->getOperand(1);
1976   }
1977 
1978   // FIXME: This changes the types of the intrinsics instead of introducing new
1979   // nodes with the correct types.
1980   // e.g. llvm.amdgcn.loop
1981 
1982   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
1983   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
1984 
1985   if (!isCFIntrinsic(Intr)) {
1986     // This is a uniform branch so we don't need to legalize.
1987     return BRCOND;
1988   }
1989 
1990   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
1991                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
1992 
1993   assert(!SetCC ||
1994         (SetCC->getConstantOperandVal(1) == 1 &&
1995          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
1996                                                              ISD::SETNE));
1997 
1998   // operands of the new intrinsic call
1999   SmallVector<SDValue, 4> Ops;
2000   if (HaveChain)
2001     Ops.push_back(BRCOND.getOperand(0));
2002 
2003   Ops.append(Intr->op_begin() + (HaveChain ?  1 : 0), Intr->op_end());
2004   Ops.push_back(Target);
2005 
2006   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
2007 
2008   // build the new intrinsic call
2009   SDNode *Result = DAG.getNode(
2010     Res.size() > 1 ? ISD::INTRINSIC_W_CHAIN : ISD::INTRINSIC_VOID, DL,
2011     DAG.getVTList(Res), Ops).getNode();
2012 
2013   if (!HaveChain) {
2014     SDValue Ops[] =  {
2015       SDValue(Result, 0),
2016       BRCOND.getOperand(0)
2017     };
2018 
2019     Result = DAG.getMergeValues(Ops, DL).getNode();
2020   }
2021 
2022   if (BR) {
2023     // Give the branch instruction our target
2024     SDValue Ops[] = {
2025       BR->getOperand(0),
2026       BRCOND.getOperand(2)
2027     };
2028     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
2029     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
2030     BR = NewBR.getNode();
2031   }
2032 
2033   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
2034 
2035   // Copy the intrinsic results to registers
2036   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
2037     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
2038     if (!CopyToReg)
2039       continue;
2040 
2041     Chain = DAG.getCopyToReg(
2042       Chain, DL,
2043       CopyToReg->getOperand(1),
2044       SDValue(Result, i - 1),
2045       SDValue());
2046 
2047     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
2048   }
2049 
2050   // Remove the old intrinsic from the chain
2051   DAG.ReplaceAllUsesOfValueWith(
2052     SDValue(Intr, Intr->getNumValues() - 1),
2053     Intr->getOperand(0));
2054 
2055   return Chain;
2056 }
2057 
2058 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
2059                                             SDValue Op,
2060                                             const SDLoc &DL,
2061                                             EVT VT) const {
2062   return Op.getValueType().bitsLE(VT) ?
2063       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
2064       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
2065 }
2066 
2067 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
2068   assert(Op.getValueType() == MVT::f16 &&
2069          "Do not know how to custom lower FP_ROUND for non-f16 type");
2070 
2071   SDValue Src = Op.getOperand(0);
2072   EVT SrcVT = Src.getValueType();
2073   if (SrcVT != MVT::f64)
2074     return Op;
2075 
2076   SDLoc DL(Op);
2077 
2078   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
2079   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
2080   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);;
2081 }
2082 
2083 SDValue SITargetLowering::getSegmentAperture(unsigned AS,
2084                                              SelectionDAG &DAG) const {
2085   SDLoc SL;
2086   MachineFunction &MF = DAG.getMachineFunction();
2087   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2088   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
2089   assert(UserSGPR != AMDGPU::NoRegister);
2090 
2091   SDValue QueuePtr = CreateLiveInRegister(
2092     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
2093 
2094   // Offset into amd_queue_t for group_segment_aperture_base_hi /
2095   // private_segment_aperture_base_hi.
2096   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
2097 
2098   SDValue Ptr = DAG.getNode(ISD::ADD, SL, MVT::i64, QueuePtr,
2099                             DAG.getConstant(StructOffset, SL, MVT::i64));
2100 
2101   // TODO: Use custom target PseudoSourceValue.
2102   // TODO: We should use the value from the IR intrinsic call, but it might not
2103   // be available and how do we get it?
2104   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
2105                                               AMDGPUAS::CONSTANT_ADDRESS));
2106 
2107   MachinePointerInfo PtrInfo(V, StructOffset);
2108   return DAG.getLoad(MVT::i32, SL, QueuePtr.getValue(1), Ptr, PtrInfo,
2109                      MinAlign(64, StructOffset),
2110                      MachineMemOperand::MODereferenceable |
2111                          MachineMemOperand::MOInvariant);
2112 }
2113 
2114 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
2115                                              SelectionDAG &DAG) const {
2116   SDLoc SL(Op);
2117   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
2118 
2119   SDValue Src = ASC->getOperand(0);
2120 
2121   // FIXME: Really support non-0 null pointers.
2122   SDValue SegmentNullPtr = DAG.getConstant(-1, SL, MVT::i32);
2123   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
2124 
2125   // flat -> local/private
2126   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2127     if (ASC->getDestAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2128         ASC->getDestAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2129       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
2130       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
2131 
2132       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
2133                          NonNull, Ptr, SegmentNullPtr);
2134     }
2135   }
2136 
2137   // local/private -> flat
2138   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
2139     if (ASC->getSrcAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2140         ASC->getSrcAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
2141       SDValue NonNull
2142         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
2143 
2144       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), DAG);
2145       SDValue CvtPtr
2146         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
2147 
2148       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
2149                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
2150                          FlatNullPtr);
2151     }
2152   }
2153 
2154   // global <-> flat are no-ops and never emitted.
2155 
2156   const MachineFunction &MF = DAG.getMachineFunction();
2157   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
2158     *MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
2159   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
2160 
2161   return DAG.getUNDEF(ASC->getValueType(0));
2162 }
2163 
2164 bool
2165 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2166   // We can fold offsets for anything that doesn't require a GOT relocation.
2167   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
2168               GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS) &&
2169          !shouldEmitGOTReloc(GA->getGlobal());
2170 }
2171 
2172 static SDValue buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
2173                                       SDLoc DL, unsigned Offset, EVT PtrVT,
2174                                       unsigned GAFlags = SIInstrInfo::MO_NONE) {
2175   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
2176   // lowered to the following code sequence:
2177   //
2178   // For constant address space:
2179   //   s_getpc_b64 s[0:1]
2180   //   s_add_u32 s0, s0, $symbol
2181   //   s_addc_u32 s1, s1, 0
2182   //
2183   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2184   //   a fixup or relocation is emitted to replace $symbol with a literal
2185   //   constant, which is a pc-relative offset from the encoding of the $symbol
2186   //   operand to the global variable.
2187   //
2188   // For global address space:
2189   //   s_getpc_b64 s[0:1]
2190   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
2191   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
2192   //
2193   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
2194   //   fixups or relocations are emitted to replace $symbol@*@lo and
2195   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
2196   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
2197   //   operand to the global variable.
2198   //
2199   // What we want here is an offset from the value returned by s_getpc
2200   // (which is the address of the s_add_u32 instruction) to the global
2201   // variable, but since the encoding of $symbol starts 4 bytes after the start
2202   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
2203   // small. This requires us to add 4 to the global variable offset in order to
2204   // compute the correct address.
2205   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2206                                              GAFlags);
2207   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
2208                                              GAFlags == SIInstrInfo::MO_NONE ?
2209                                              GAFlags : GAFlags + 1);
2210   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
2211 }
2212 
2213 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
2214                                              SDValue Op,
2215                                              SelectionDAG &DAG) const {
2216   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
2217 
2218   if (GSD->getAddressSpace() != AMDGPUAS::CONSTANT_ADDRESS &&
2219       GSD->getAddressSpace() != AMDGPUAS::GLOBAL_ADDRESS)
2220     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
2221 
2222   SDLoc DL(GSD);
2223   const GlobalValue *GV = GSD->getGlobal();
2224   EVT PtrVT = Op.getValueType();
2225 
2226   if (shouldEmitFixup(GV))
2227     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
2228   else if (shouldEmitPCReloc(GV))
2229     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
2230                                    SIInstrInfo::MO_REL32);
2231 
2232   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
2233                                             SIInstrInfo::MO_GOTPCREL32);
2234 
2235   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
2236   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
2237   const DataLayout &DataLayout = DAG.getDataLayout();
2238   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
2239   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
2240   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
2241 
2242   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
2243                      MachineMemOperand::MODereferenceable |
2244                          MachineMemOperand::MOInvariant);
2245 }
2246 
2247 SDValue SITargetLowering::lowerTRAP(SDValue Op,
2248                                     SelectionDAG &DAG) const {
2249   const MachineFunction &MF = DAG.getMachineFunction();
2250   DiagnosticInfoUnsupported NoTrap(*MF.getFunction(),
2251                                    "trap handler not supported",
2252                                    Op.getDebugLoc(),
2253                                    DS_Warning);
2254   DAG.getContext()->diagnose(NoTrap);
2255 
2256   // Emit s_endpgm.
2257 
2258   // FIXME: This should really be selected to s_trap, but that requires
2259   // setting up the trap handler for it o do anything.
2260   return DAG.getNode(AMDGPUISD::ENDPGM, SDLoc(Op), MVT::Other,
2261                      Op.getOperand(0));
2262 }
2263 
2264 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
2265                                    const SDLoc &DL, SDValue V) const {
2266   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
2267   // the destination register.
2268   //
2269   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
2270   // so we will end up with redundant moves to m0.
2271   //
2272   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
2273 
2274   // A Null SDValue creates a glue result.
2275   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
2276                                   V, Chain);
2277   return SDValue(M0, 0);
2278 }
2279 
2280 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
2281                                                  SDValue Op,
2282                                                  MVT VT,
2283                                                  unsigned Offset) const {
2284   SDLoc SL(Op);
2285   SDValue Param = LowerParameter(DAG, MVT::i32, MVT::i32, SL,
2286                                  DAG.getEntryNode(), Offset, false);
2287   // The local size values will have the hi 16-bits as zero.
2288   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
2289                      DAG.getValueType(VT));
2290 }
2291 
2292 static SDValue emitNonHSAIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2293   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2294                                       "non-hsa intrinsic with hsa target",
2295                                       DL.getDebugLoc());
2296   DAG.getContext()->diagnose(BadIntrin);
2297   return DAG.getUNDEF(VT);
2298 }
2299 
2300 static SDValue emitRemovedIntrinsicError(SelectionDAG& DAG, SDLoc DL, EVT VT) {
2301   DiagnosticInfoUnsupported BadIntrin(*DAG.getMachineFunction().getFunction(),
2302                                       "intrinsic not supported on subtarget",
2303                                       DL.getDebugLoc());
2304   DAG.getContext()->diagnose(BadIntrin);
2305   return DAG.getUNDEF(VT);
2306 }
2307 
2308 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2309                                                   SelectionDAG &DAG) const {
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
2312   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2313 
2314   EVT VT = Op.getValueType();
2315   SDLoc DL(Op);
2316   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2317 
2318   // TODO: Should this propagate fast-math-flags?
2319 
2320   switch (IntrinsicID) {
2321   case Intrinsic::amdgcn_dispatch_ptr:
2322   case Intrinsic::amdgcn_queue_ptr: {
2323     if (!Subtarget->isAmdCodeObjectV2()) {
2324       DiagnosticInfoUnsupported BadIntrin(
2325           *MF.getFunction(), "unsupported hsa intrinsic without hsa target",
2326           DL.getDebugLoc());
2327       DAG.getContext()->diagnose(BadIntrin);
2328       return DAG.getUNDEF(VT);
2329     }
2330 
2331     auto Reg = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
2332       SIRegisterInfo::DISPATCH_PTR : SIRegisterInfo::QUEUE_PTR;
2333     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass,
2334                                 TRI->getPreloadedValue(MF, Reg), VT);
2335   }
2336   case Intrinsic::amdgcn_implicitarg_ptr: {
2337     unsigned offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
2338     return LowerParameterPtr(DAG, DL, DAG.getEntryNode(), offset);
2339   }
2340   case Intrinsic::amdgcn_kernarg_segment_ptr: {
2341     unsigned Reg
2342       = TRI->getPreloadedValue(MF, SIRegisterInfo::KERNARG_SEGMENT_PTR);
2343     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2344   }
2345   case Intrinsic::amdgcn_dispatch_id: {
2346     unsigned Reg = TRI->getPreloadedValue(MF, SIRegisterInfo::DISPATCH_ID);
2347     return CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, Reg, VT);
2348   }
2349   case Intrinsic::amdgcn_rcp:
2350     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
2351   case Intrinsic::amdgcn_rsq:
2352   case AMDGPUIntrinsic::AMDGPU_rsq: // Legacy name
2353     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2354   case Intrinsic::amdgcn_rsq_legacy: {
2355     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2356       return emitRemovedIntrinsicError(DAG, DL, VT);
2357 
2358     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
2359   }
2360   case Intrinsic::amdgcn_rcp_legacy: {
2361     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
2362       return emitRemovedIntrinsicError(DAG, DL, VT);
2363     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
2364   }
2365   case Intrinsic::amdgcn_rsq_clamp: {
2366     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2367       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
2368 
2369     Type *Type = VT.getTypeForEVT(*DAG.getContext());
2370     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
2371     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
2372 
2373     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
2374     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
2375                               DAG.getConstantFP(Max, DL, VT));
2376     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
2377                        DAG.getConstantFP(Min, DL, VT));
2378   }
2379   case Intrinsic::r600_read_ngroups_x:
2380     if (Subtarget->isAmdHsaOS())
2381       return emitNonHSAIntrinsicError(DAG, DL, VT);
2382 
2383     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2384                           SI::KernelInputOffsets::NGROUPS_X, false);
2385   case Intrinsic::r600_read_ngroups_y:
2386     if (Subtarget->isAmdHsaOS())
2387       return emitNonHSAIntrinsicError(DAG, DL, VT);
2388 
2389     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2390                           SI::KernelInputOffsets::NGROUPS_Y, false);
2391   case Intrinsic::r600_read_ngroups_z:
2392     if (Subtarget->isAmdHsaOS())
2393       return emitNonHSAIntrinsicError(DAG, DL, VT);
2394 
2395     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2396                           SI::KernelInputOffsets::NGROUPS_Z, false);
2397   case Intrinsic::r600_read_global_size_x:
2398     if (Subtarget->isAmdHsaOS())
2399       return emitNonHSAIntrinsicError(DAG, DL, VT);
2400 
2401     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2402                           SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
2403   case Intrinsic::r600_read_global_size_y:
2404     if (Subtarget->isAmdHsaOS())
2405       return emitNonHSAIntrinsicError(DAG, DL, VT);
2406 
2407     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2408                           SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
2409   case Intrinsic::r600_read_global_size_z:
2410     if (Subtarget->isAmdHsaOS())
2411       return emitNonHSAIntrinsicError(DAG, DL, VT);
2412 
2413     return LowerParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
2414                           SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
2415   case Intrinsic::r600_read_local_size_x:
2416     if (Subtarget->isAmdHsaOS())
2417       return emitNonHSAIntrinsicError(DAG, DL, VT);
2418 
2419     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2420                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
2421   case Intrinsic::r600_read_local_size_y:
2422     if (Subtarget->isAmdHsaOS())
2423       return emitNonHSAIntrinsicError(DAG, DL, VT);
2424 
2425     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2426                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
2427   case Intrinsic::r600_read_local_size_z:
2428     if (Subtarget->isAmdHsaOS())
2429       return emitNonHSAIntrinsicError(DAG, DL, VT);
2430 
2431     return lowerImplicitZextParam(DAG, Op, MVT::i16,
2432                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
2433   case Intrinsic::amdgcn_workgroup_id_x:
2434   case Intrinsic::r600_read_tgid_x:
2435     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2436       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_X), VT);
2437   case Intrinsic::amdgcn_workgroup_id_y:
2438   case Intrinsic::r600_read_tgid_y:
2439     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2440       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Y), VT);
2441   case Intrinsic::amdgcn_workgroup_id_z:
2442   case Intrinsic::r600_read_tgid_z:
2443     return CreateLiveInRegister(DAG, &AMDGPU::SReg_32_XM0RegClass,
2444       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKGROUP_ID_Z), VT);
2445   case Intrinsic::amdgcn_workitem_id_x:
2446   case Intrinsic::r600_read_tidig_x:
2447     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2448       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_X), VT);
2449   case Intrinsic::amdgcn_workitem_id_y:
2450   case Intrinsic::r600_read_tidig_y:
2451     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2452       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Y), VT);
2453   case Intrinsic::amdgcn_workitem_id_z:
2454   case Intrinsic::r600_read_tidig_z:
2455     return CreateLiveInRegister(DAG, &AMDGPU::VGPR_32RegClass,
2456       TRI->getPreloadedValue(MF, SIRegisterInfo::WORKITEM_ID_Z), VT);
2457   case AMDGPUIntrinsic::SI_load_const: {
2458     SDValue Ops[] = {
2459       Op.getOperand(1),
2460       Op.getOperand(2)
2461     };
2462 
2463     MachineMemOperand *MMO = MF.getMachineMemOperand(
2464         MachinePointerInfo(),
2465         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
2466             MachineMemOperand::MOInvariant,
2467         VT.getStoreSize(), 4);
2468     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
2469                                    Op->getVTList(), Ops, VT, MMO);
2470   }
2471   case AMDGPUIntrinsic::amdgcn_fdiv_fast: {
2472     return lowerFDIV_FAST(Op, DAG);
2473   }
2474   case AMDGPUIntrinsic::SI_vs_load_input:
2475     return DAG.getNode(AMDGPUISD::LOAD_INPUT, DL, VT,
2476                        Op.getOperand(1),
2477                        Op.getOperand(2),
2478                        Op.getOperand(3));
2479 
2480   case AMDGPUIntrinsic::SI_fs_constant: {
2481     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2482     SDValue Glue = M0.getValue(1);
2483     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
2484                        DAG.getConstant(2, DL, MVT::i32), // P0
2485                        Op.getOperand(1), Op.getOperand(2), Glue);
2486   }
2487   case AMDGPUIntrinsic::SI_packf16:
2488     if (Op.getOperand(1).isUndef() && Op.getOperand(2).isUndef())
2489       return DAG.getUNDEF(MVT::i32);
2490     return Op;
2491   case AMDGPUIntrinsic::SI_fs_interp: {
2492     SDValue IJ = Op.getOperand(4);
2493     SDValue I = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2494                             DAG.getConstant(0, DL, MVT::i32));
2495     SDValue J = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, IJ,
2496                             DAG.getConstant(1, DL, MVT::i32));
2497     I = DAG.getNode(ISD::BITCAST, DL, MVT::f32, I);
2498     J = DAG.getNode(ISD::BITCAST, DL, MVT::f32, J);
2499     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(3));
2500     SDValue Glue = M0.getValue(1);
2501     SDValue P1 = DAG.getNode(AMDGPUISD::INTERP_P1, DL,
2502                              DAG.getVTList(MVT::f32, MVT::Glue),
2503                              I, Op.getOperand(1), Op.getOperand(2), Glue);
2504     Glue = SDValue(P1.getNode(), 1);
2505     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, P1, J,
2506                              Op.getOperand(1), Op.getOperand(2), Glue);
2507   }
2508   case Intrinsic::amdgcn_interp_mov: {
2509     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2510     SDValue Glue = M0.getValue(1);
2511     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
2512                        Op.getOperand(2), Op.getOperand(3), Glue);
2513   }
2514   case Intrinsic::amdgcn_interp_p1: {
2515     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
2516     SDValue Glue = M0.getValue(1);
2517     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
2518                        Op.getOperand(2), Op.getOperand(3), Glue);
2519   }
2520   case Intrinsic::amdgcn_interp_p2: {
2521     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
2522     SDValue Glue = SDValue(M0.getNode(), 1);
2523     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
2524                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
2525                        Glue);
2526   }
2527   case Intrinsic::amdgcn_sin:
2528     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
2529 
2530   case Intrinsic::amdgcn_cos:
2531     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
2532 
2533   case Intrinsic::amdgcn_log_clamp: {
2534     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
2535       return SDValue();
2536 
2537     DiagnosticInfoUnsupported BadIntrin(
2538       *MF.getFunction(), "intrinsic not supported on subtarget",
2539       DL.getDebugLoc());
2540       DAG.getContext()->diagnose(BadIntrin);
2541       return DAG.getUNDEF(VT);
2542   }
2543   case Intrinsic::amdgcn_ldexp:
2544     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
2545                        Op.getOperand(1), Op.getOperand(2));
2546 
2547   case Intrinsic::amdgcn_fract:
2548     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
2549 
2550   case Intrinsic::amdgcn_class:
2551     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
2552                        Op.getOperand(1), Op.getOperand(2));
2553   case Intrinsic::amdgcn_div_fmas:
2554     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
2555                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
2556                        Op.getOperand(4));
2557 
2558   case Intrinsic::amdgcn_div_fixup:
2559     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
2560                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
2561 
2562   case Intrinsic::amdgcn_trig_preop:
2563     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
2564                        Op.getOperand(1), Op.getOperand(2));
2565   case Intrinsic::amdgcn_div_scale: {
2566     // 3rd parameter required to be a constant.
2567     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2568     if (!Param)
2569       return DAG.getUNDEF(VT);
2570 
2571     // Translate to the operands expected by the machine instruction. The
2572     // first parameter must be the same as the first instruction.
2573     SDValue Numerator = Op.getOperand(1);
2574     SDValue Denominator = Op.getOperand(2);
2575 
2576     // Note this order is opposite of the machine instruction's operations,
2577     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
2578     // intrinsic has the numerator as the first operand to match a normal
2579     // division operation.
2580 
2581     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
2582 
2583     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
2584                        Denominator, Numerator);
2585   }
2586   case Intrinsic::amdgcn_icmp: {
2587     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2588     int CondCode = CD->getSExtValue();
2589 
2590     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
2591         CondCode >= ICmpInst::Predicate::BAD_ICMP_PREDICATE)
2592       return DAG.getUNDEF(VT);
2593 
2594     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
2595     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
2596     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2597                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2598   }
2599   case Intrinsic::amdgcn_fcmp: {
2600     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
2601     int CondCode = CD->getSExtValue();
2602 
2603     if (CondCode <= FCmpInst::Predicate::FCMP_FALSE ||
2604         CondCode >= FCmpInst::Predicate::FCMP_TRUE)
2605       return DAG.getUNDEF(VT);
2606 
2607     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
2608     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
2609     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
2610                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
2611   }
2612   case Intrinsic::amdgcn_fmul_legacy:
2613     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
2614                        Op.getOperand(1), Op.getOperand(2));
2615   case Intrinsic::amdgcn_sffbh:
2616   case AMDGPUIntrinsic::AMDGPU_flbit_i32: // Legacy name.
2617     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
2618   default:
2619     return AMDGPUTargetLowering::LowerOperation(Op, DAG);
2620   }
2621 }
2622 
2623 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2624                                                  SelectionDAG &DAG) const {
2625   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2626   switch (IntrID) {
2627   case Intrinsic::amdgcn_atomic_inc:
2628   case Intrinsic::amdgcn_atomic_dec: {
2629     MemSDNode *M = cast<MemSDNode>(Op);
2630     unsigned Opc = (IntrID == Intrinsic::amdgcn_atomic_inc) ?
2631       AMDGPUISD::ATOMIC_INC : AMDGPUISD::ATOMIC_DEC;
2632     SDValue Ops[] = {
2633       M->getOperand(0), // Chain
2634       M->getOperand(2), // Ptr
2635       M->getOperand(3)  // Value
2636     };
2637 
2638     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
2639                                    M->getMemoryVT(), M->getMemOperand());
2640   }
2641   default:
2642     return SDValue();
2643   }
2644 }
2645 
2646 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
2647                                               SelectionDAG &DAG) const {
2648   MachineFunction &MF = DAG.getMachineFunction();
2649   SDLoc DL(Op);
2650   SDValue Chain = Op.getOperand(0);
2651   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2652 
2653   switch (IntrinsicID) {
2654   case AMDGPUIntrinsic::SI_sendmsg: {
2655     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
2656     SDValue Glue = Chain.getValue(1);
2657     return DAG.getNode(AMDGPUISD::SENDMSG, DL, MVT::Other, Chain,
2658                        Op.getOperand(2), Glue);
2659   }
2660   case AMDGPUIntrinsic::SI_tbuffer_store: {
2661     SDValue Ops[] = {
2662       Chain,
2663       Op.getOperand(2),
2664       Op.getOperand(3),
2665       Op.getOperand(4),
2666       Op.getOperand(5),
2667       Op.getOperand(6),
2668       Op.getOperand(7),
2669       Op.getOperand(8),
2670       Op.getOperand(9),
2671       Op.getOperand(10),
2672       Op.getOperand(11),
2673       Op.getOperand(12),
2674       Op.getOperand(13),
2675       Op.getOperand(14)
2676     };
2677 
2678     EVT VT = Op.getOperand(3).getValueType();
2679 
2680     MachineMemOperand *MMO = MF.getMachineMemOperand(
2681       MachinePointerInfo(),
2682       MachineMemOperand::MOStore,
2683       VT.getStoreSize(), 4);
2684     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_STORE_FORMAT, DL,
2685                                    Op->getVTList(), Ops, VT, MMO);
2686   }
2687   case AMDGPUIntrinsic::AMDGPU_kill: {
2688     SDValue Src = Op.getOperand(2);
2689     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
2690       if (!K->isNegative())
2691         return Chain;
2692 
2693       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
2694       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
2695     }
2696 
2697     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
2698     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
2699   }
2700   case AMDGPUIntrinsic::SI_export: {
2701     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(2));
2702     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(3));
2703     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(4));
2704     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(5));
2705     const ConstantSDNode *Compr = cast<ConstantSDNode>(Op.getOperand(6));
2706 
2707     const SDValue Ops[] = {
2708       Chain,
2709       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),
2710       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1),
2711       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8),
2712       DAG.getTargetConstant(Compr->getZExtValue(), DL, MVT::i1),
2713       Op.getOperand(7), // src0
2714       Op.getOperand(8), // src1
2715       Op.getOperand(9), // src2
2716       Op.getOperand(10) // src3
2717     };
2718 
2719     unsigned Opc = Done->isNullValue() ?
2720       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
2721     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
2722   }
2723   default:
2724     return SDValue();
2725   }
2726 }
2727 
2728 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2729   SDLoc DL(Op);
2730   LoadSDNode *Load = cast<LoadSDNode>(Op);
2731   ISD::LoadExtType ExtType = Load->getExtensionType();
2732   EVT MemVT = Load->getMemoryVT();
2733 
2734   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
2735     // FIXME: Copied from PPC
2736     // First, load into 32 bits, then truncate to 1 bit.
2737 
2738     SDValue Chain = Load->getChain();
2739     SDValue BasePtr = Load->getBasePtr();
2740     MachineMemOperand *MMO = Load->getMemOperand();
2741 
2742     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
2743 
2744     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
2745                                    BasePtr, RealMemVT, MMO);
2746 
2747     SDValue Ops[] = {
2748       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
2749       NewLD.getValue(1)
2750     };
2751 
2752     return DAG.getMergeValues(Ops, DL);
2753   }
2754 
2755   if (!MemVT.isVector())
2756     return SDValue();
2757 
2758   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
2759          "Custom lowering for non-i32 vectors hasn't been implemented.");
2760 
2761   unsigned AS = Load->getAddressSpace();
2762   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
2763                           AS, Load->getAlignment())) {
2764     SDValue Ops[2];
2765     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
2766     return DAG.getMergeValues(Ops, DL);
2767   }
2768 
2769   MachineFunction &MF = DAG.getMachineFunction();
2770   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
2771   // If there is a possibilty that flat instruction access scratch memory
2772   // then we need to use the same legalization rules we use for private.
2773   if (AS == AMDGPUAS::FLAT_ADDRESS)
2774     AS = MFI->hasFlatScratchInit() ?
2775          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
2776 
2777   unsigned NumElements = MemVT.getVectorNumElements();
2778   switch (AS) {
2779   case AMDGPUAS::CONSTANT_ADDRESS:
2780     if (isMemOpUniform(Load))
2781       return SDValue();
2782     // Non-uniform loads will be selected to MUBUF instructions, so they
2783     // have the same legalization requirements as global and private
2784     // loads.
2785     //
2786     LLVM_FALLTHROUGH;
2787   case AMDGPUAS::GLOBAL_ADDRESS: {
2788     if (isMemOpUniform(Load) && isMemOpHasNoClobberedMemOperand(Load))
2789       return SDValue();
2790     // Non-uniform loads will be selected to MUBUF instructions, so they
2791     // have the same legalization requirements as global and private
2792     // loads.
2793     //
2794   }
2795     LLVM_FALLTHROUGH;
2796   case AMDGPUAS::FLAT_ADDRESS:
2797     if (NumElements > 4)
2798       return SplitVectorLoad(Op, DAG);
2799     // v4 loads are supported for private and global memory.
2800     return SDValue();
2801   case AMDGPUAS::PRIVATE_ADDRESS: {
2802     // Depending on the setting of the private_element_size field in the
2803     // resource descriptor, we can only make private accesses up to a certain
2804     // size.
2805     switch (Subtarget->getMaxPrivateElementSize()) {
2806     case 4:
2807       return scalarizeVectorLoad(Load, DAG);
2808     case 8:
2809       if (NumElements > 2)
2810         return SplitVectorLoad(Op, DAG);
2811       return SDValue();
2812     case 16:
2813       // Same as global/flat
2814       if (NumElements > 4)
2815         return SplitVectorLoad(Op, DAG);
2816       return SDValue();
2817     default:
2818       llvm_unreachable("unsupported private_element_size");
2819     }
2820   }
2821   case AMDGPUAS::LOCAL_ADDRESS: {
2822     if (NumElements > 2)
2823       return SplitVectorLoad(Op, DAG);
2824 
2825     if (NumElements == 2)
2826       return SDValue();
2827 
2828     // If properly aligned, if we split we might be able to use ds_read_b64.
2829     return SplitVectorLoad(Op, DAG);
2830   }
2831   default:
2832     return SDValue();
2833   }
2834 }
2835 
2836 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2837   if (Op.getValueType() != MVT::i64)
2838     return SDValue();
2839 
2840   SDLoc DL(Op);
2841   SDValue Cond = Op.getOperand(0);
2842 
2843   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2844   SDValue One = DAG.getConstant(1, DL, MVT::i32);
2845 
2846   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
2847   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
2848 
2849   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
2850   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
2851 
2852   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
2853 
2854   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
2855   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
2856 
2857   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
2858 
2859   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
2860   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
2861 }
2862 
2863 // Catch division cases where we can use shortcuts with rcp and rsq
2864 // instructions.
2865 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
2866                                               SelectionDAG &DAG) const {
2867   SDLoc SL(Op);
2868   SDValue LHS = Op.getOperand(0);
2869   SDValue RHS = Op.getOperand(1);
2870   EVT VT = Op.getValueType();
2871   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath;
2872 
2873   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
2874     if ((Unsafe || (VT == MVT::f32 && !Subtarget->hasFP32Denormals()))) {
2875 
2876       if (CLHS->isExactlyValue(1.0)) {
2877         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
2878         // the CI documentation has a worst case error of 1 ulp.
2879         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
2880         // use it as long as we aren't trying to use denormals.
2881 
2882         // 1.0 / sqrt(x) -> rsq(x)
2883         //
2884         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
2885         // error seems really high at 2^29 ULP.
2886         if (RHS.getOpcode() == ISD::FSQRT)
2887           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
2888 
2889         // 1.0 / x -> rcp(x)
2890         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2891       }
2892 
2893       // Same as for 1.0, but expand the sign out of the constant.
2894       if (CLHS->isExactlyValue(-1.0)) {
2895         // -1.0 / x -> rcp (fneg x)
2896         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
2897         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
2898       }
2899     }
2900   }
2901 
2902   const SDNodeFlags *Flags = Op->getFlags();
2903 
2904   if (Unsafe || Flags->hasAllowReciprocal()) {
2905     // Turn into multiply by the reciprocal.
2906     // x / y -> x * (1.0 / y)
2907     SDNodeFlags Flags;
2908     Flags.setUnsafeAlgebra(true);
2909     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
2910     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, &Flags);
2911   }
2912 
2913   return SDValue();
2914 }
2915 
2916 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
2917                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
2918   if (GlueChain->getNumValues() <= 1) {
2919     return DAG.getNode(Opcode, SL, VT, A, B);
2920   }
2921 
2922   assert(GlueChain->getNumValues() == 3);
2923 
2924   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
2925   switch (Opcode) {
2926   default: llvm_unreachable("no chain equivalent for opcode");
2927   case ISD::FMUL:
2928     Opcode = AMDGPUISD::FMUL_W_CHAIN;
2929     break;
2930   }
2931 
2932   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
2933                      GlueChain.getValue(2));
2934 }
2935 
2936 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
2937                            EVT VT, SDValue A, SDValue B, SDValue C,
2938                            SDValue GlueChain) {
2939   if (GlueChain->getNumValues() <= 1) {
2940     return DAG.getNode(Opcode, SL, VT, A, B, C);
2941   }
2942 
2943   assert(GlueChain->getNumValues() == 3);
2944 
2945   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
2946   switch (Opcode) {
2947   default: llvm_unreachable("no chain equivalent for opcode");
2948   case ISD::FMA:
2949     Opcode = AMDGPUISD::FMA_W_CHAIN;
2950     break;
2951   }
2952 
2953   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
2954                      GlueChain.getValue(2));
2955 }
2956 
2957 // Faster 2.5 ULP division that does not support denormals.
2958 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
2959   SDLoc SL(Op);
2960   SDValue LHS = Op.getOperand(1);
2961   SDValue RHS = Op.getOperand(2);
2962 
2963   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
2964 
2965   const APFloat K0Val(BitsToFloat(0x6f800000));
2966   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
2967 
2968   const APFloat K1Val(BitsToFloat(0x2f800000));
2969   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
2970 
2971   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
2972 
2973   EVT SetCCVT =
2974     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
2975 
2976   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
2977 
2978   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
2979 
2980   // TODO: Should this propagate fast-math-flags?
2981   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
2982 
2983   // rcp does not support denormals.
2984   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
2985 
2986   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
2987 
2988   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
2989 }
2990 
2991 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
2992   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
2993     return FastLowered;
2994 
2995   SDLoc SL(Op);
2996   SDValue LHS = Op.getOperand(0);
2997   SDValue RHS = Op.getOperand(1);
2998 
2999   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
3000 
3001   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
3002 
3003   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3004                                           RHS, RHS, LHS);
3005   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
3006                                         LHS, RHS, LHS);
3007 
3008   // Denominator is scaled to not be denormal, so using rcp is ok.
3009   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
3010                                   DenominatorScaled);
3011   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
3012                                      DenominatorScaled);
3013 
3014   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
3015                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
3016                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
3017 
3018   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
3019 
3020   if (!Subtarget->hasFP32Denormals()) {
3021     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
3022     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
3023                                                       SL, MVT::i32);
3024     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
3025                                        DAG.getEntryNode(),
3026                                        EnableDenormValue, BitField);
3027     SDValue Ops[3] = {
3028       NegDivScale0,
3029       EnableDenorm.getValue(0),
3030       EnableDenorm.getValue(1)
3031     };
3032 
3033     NegDivScale0 = DAG.getMergeValues(Ops, SL);
3034   }
3035 
3036   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
3037                              ApproxRcp, One, NegDivScale0);
3038 
3039   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
3040                              ApproxRcp, Fma0);
3041 
3042   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
3043                            Fma1, Fma1);
3044 
3045   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
3046                              NumeratorScaled, Mul);
3047 
3048   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
3049 
3050   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
3051                              NumeratorScaled, Fma3);
3052 
3053   if (!Subtarget->hasFP32Denormals()) {
3054     const SDValue DisableDenormValue =
3055         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
3056     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
3057                                         Fma4.getValue(1),
3058                                         DisableDenormValue,
3059                                         BitField,
3060                                         Fma4.getValue(2));
3061 
3062     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
3063                                       DisableDenorm, DAG.getRoot());
3064     DAG.setRoot(OutputChain);
3065   }
3066 
3067   SDValue Scale = NumeratorScaled.getValue(1);
3068   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
3069                              Fma4, Fma1, Fma3, Scale);
3070 
3071   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
3072 }
3073 
3074 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
3075   if (DAG.getTarget().Options.UnsafeFPMath)
3076     return lowerFastUnsafeFDIV(Op, DAG);
3077 
3078   SDLoc SL(Op);
3079   SDValue X = Op.getOperand(0);
3080   SDValue Y = Op.getOperand(1);
3081 
3082   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
3083 
3084   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
3085 
3086   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
3087 
3088   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
3089 
3090   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
3091 
3092   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
3093 
3094   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
3095 
3096   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
3097 
3098   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
3099 
3100   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
3101   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
3102 
3103   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
3104                              NegDivScale0, Mul, DivScale1);
3105 
3106   SDValue Scale;
3107 
3108   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
3109     // Workaround a hardware bug on SI where the condition output from div_scale
3110     // is not usable.
3111 
3112     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
3113 
3114     // Figure out if the scale to use for div_fmas.
3115     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
3116     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
3117     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
3118     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
3119 
3120     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
3121     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
3122 
3123     SDValue Scale0Hi
3124       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
3125     SDValue Scale1Hi
3126       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
3127 
3128     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
3129     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
3130     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
3131   } else {
3132     Scale = DivScale1.getValue(1);
3133   }
3134 
3135   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
3136                              Fma4, Fma3, Mul, Scale);
3137 
3138   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
3139 }
3140 
3141 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
3142   EVT VT = Op.getValueType();
3143 
3144   if (VT == MVT::f32)
3145     return LowerFDIV32(Op, DAG);
3146 
3147   if (VT == MVT::f64)
3148     return LowerFDIV64(Op, DAG);
3149 
3150   llvm_unreachable("Unexpected type for fdiv");
3151 }
3152 
3153 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
3154   SDLoc DL(Op);
3155   StoreSDNode *Store = cast<StoreSDNode>(Op);
3156   EVT VT = Store->getMemoryVT();
3157 
3158   if (VT == MVT::i1) {
3159     return DAG.getTruncStore(Store->getChain(), DL,
3160        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
3161        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
3162   }
3163 
3164   assert(VT.isVector() &&
3165          Store->getValue().getValueType().getScalarType() == MVT::i32);
3166 
3167   unsigned AS = Store->getAddressSpace();
3168   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
3169                           AS, Store->getAlignment())) {
3170     return expandUnalignedStore(Store, DAG);
3171   }
3172 
3173   MachineFunction &MF = DAG.getMachineFunction();
3174   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3175   // If there is a possibilty that flat instruction access scratch memory
3176   // then we need to use the same legalization rules we use for private.
3177   if (AS == AMDGPUAS::FLAT_ADDRESS)
3178     AS = MFI->hasFlatScratchInit() ?
3179          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
3180 
3181   unsigned NumElements = VT.getVectorNumElements();
3182   switch (AS) {
3183   case AMDGPUAS::GLOBAL_ADDRESS:
3184   case AMDGPUAS::FLAT_ADDRESS:
3185     if (NumElements > 4)
3186       return SplitVectorStore(Op, DAG);
3187     return SDValue();
3188   case AMDGPUAS::PRIVATE_ADDRESS: {
3189     switch (Subtarget->getMaxPrivateElementSize()) {
3190     case 4:
3191       return scalarizeVectorStore(Store, DAG);
3192     case 8:
3193       if (NumElements > 2)
3194         return SplitVectorStore(Op, DAG);
3195       return SDValue();
3196     case 16:
3197       if (NumElements > 4)
3198         return SplitVectorStore(Op, DAG);
3199       return SDValue();
3200     default:
3201       llvm_unreachable("unsupported private_element_size");
3202     }
3203   }
3204   case AMDGPUAS::LOCAL_ADDRESS: {
3205     if (NumElements > 2)
3206       return SplitVectorStore(Op, DAG);
3207 
3208     if (NumElements == 2)
3209       return Op;
3210 
3211     // If properly aligned, if we split we might be able to use ds_write_b64.
3212     return SplitVectorStore(Op, DAG);
3213   }
3214   default:
3215     llvm_unreachable("unhandled address space");
3216   }
3217 }
3218 
3219 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
3220   SDLoc DL(Op);
3221   EVT VT = Op.getValueType();
3222   SDValue Arg = Op.getOperand(0);
3223   // TODO: Should this propagate fast-math-flags?
3224   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
3225                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
3226                                               DAG.getConstantFP(0.5/M_PI, DL,
3227                                                                 VT)));
3228 
3229   switch (Op.getOpcode()) {
3230   case ISD::FCOS:
3231     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
3232   case ISD::FSIN:
3233     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
3234   default:
3235     llvm_unreachable("Wrong trig opcode");
3236   }
3237 }
3238 
3239 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
3240   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
3241   assert(AtomicNode->isCompareAndSwap());
3242   unsigned AS = AtomicNode->getAddressSpace();
3243 
3244   // No custom lowering required for local address space
3245   if (!isFlatGlobalAddrSpace(AS))
3246     return Op;
3247 
3248   // Non-local address space requires custom lowering for atomic compare
3249   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
3250   SDLoc DL(Op);
3251   SDValue ChainIn = Op.getOperand(0);
3252   SDValue Addr = Op.getOperand(1);
3253   SDValue Old = Op.getOperand(2);
3254   SDValue New = Op.getOperand(3);
3255   EVT VT = Op.getValueType();
3256   MVT SimpleVT = VT.getSimpleVT();
3257   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
3258 
3259   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
3260   SDValue Ops[] = { ChainIn, Addr, NewOld };
3261 
3262   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
3263                                  Ops, VT, AtomicNode->getMemOperand());
3264 }
3265 
3266 //===----------------------------------------------------------------------===//
3267 // Custom DAG optimizations
3268 //===----------------------------------------------------------------------===//
3269 
3270 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
3271                                                      DAGCombinerInfo &DCI) const {
3272   EVT VT = N->getValueType(0);
3273   EVT ScalarVT = VT.getScalarType();
3274   if (ScalarVT != MVT::f32)
3275     return SDValue();
3276 
3277   SelectionDAG &DAG = DCI.DAG;
3278   SDLoc DL(N);
3279 
3280   SDValue Src = N->getOperand(0);
3281   EVT SrcVT = Src.getValueType();
3282 
3283   // TODO: We could try to match extracting the higher bytes, which would be
3284   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
3285   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
3286   // about in practice.
3287   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
3288     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
3289       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
3290       DCI.AddToWorklist(Cvt.getNode());
3291       return Cvt;
3292     }
3293   }
3294 
3295   return SDValue();
3296 }
3297 
3298 /// \brief Return true if the given offset Size in bytes can be folded into
3299 /// the immediate offsets of a memory instruction for the given address space.
3300 static bool canFoldOffset(unsigned OffsetSize, unsigned AS,
3301                           const SISubtarget &STI) {
3302   switch (AS) {
3303   case AMDGPUAS::GLOBAL_ADDRESS: {
3304     // MUBUF instructions a 12-bit offset in bytes.
3305     return isUInt<12>(OffsetSize);
3306   }
3307   case AMDGPUAS::CONSTANT_ADDRESS: {
3308     // SMRD instructions have an 8-bit offset in dwords on SI and
3309     // a 20-bit offset in bytes on VI.
3310     if (STI.getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
3311       return isUInt<20>(OffsetSize);
3312     else
3313       return (OffsetSize % 4 == 0) && isUInt<8>(OffsetSize / 4);
3314   }
3315   case AMDGPUAS::LOCAL_ADDRESS:
3316   case AMDGPUAS::REGION_ADDRESS: {
3317     // The single offset versions have a 16-bit offset in bytes.
3318     return isUInt<16>(OffsetSize);
3319   }
3320   case AMDGPUAS::PRIVATE_ADDRESS:
3321   // Indirect register addressing does not use any offsets.
3322   default:
3323     return 0;
3324   }
3325 }
3326 
3327 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
3328 
3329 // This is a variant of
3330 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
3331 //
3332 // The normal DAG combiner will do this, but only if the add has one use since
3333 // that would increase the number of instructions.
3334 //
3335 // This prevents us from seeing a constant offset that can be folded into a
3336 // memory instruction's addressing mode. If we know the resulting add offset of
3337 // a pointer can be folded into an addressing offset, we can replace the pointer
3338 // operand with the add of new constant offset. This eliminates one of the uses,
3339 // and may allow the remaining use to also be simplified.
3340 //
3341 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
3342                                                unsigned AddrSpace,
3343                                                DAGCombinerInfo &DCI) const {
3344   SDValue N0 = N->getOperand(0);
3345   SDValue N1 = N->getOperand(1);
3346 
3347   if (N0.getOpcode() != ISD::ADD)
3348     return SDValue();
3349 
3350   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
3351   if (!CN1)
3352     return SDValue();
3353 
3354   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3355   if (!CAdd)
3356     return SDValue();
3357 
3358   // If the resulting offset is too large, we can't fold it into the addressing
3359   // mode offset.
3360   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
3361   if (!canFoldOffset(Offset.getZExtValue(), AddrSpace, *getSubtarget()))
3362     return SDValue();
3363 
3364   SelectionDAG &DAG = DCI.DAG;
3365   SDLoc SL(N);
3366   EVT VT = N->getValueType(0);
3367 
3368   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
3369   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
3370 
3371   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset);
3372 }
3373 
3374 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
3375   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
3376          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
3377          (Opc == ISD::XOR && Val == 0);
3378 }
3379 
3380 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
3381 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
3382 // integer combine opportunities since most 64-bit operations are decomposed
3383 // this way.  TODO: We won't want this for SALU especially if it is an inline
3384 // immediate.
3385 SDValue SITargetLowering::splitBinaryBitConstantOp(
3386   DAGCombinerInfo &DCI,
3387   const SDLoc &SL,
3388   unsigned Opc, SDValue LHS,
3389   const ConstantSDNode *CRHS) const {
3390   uint64_t Val = CRHS->getZExtValue();
3391   uint32_t ValLo = Lo_32(Val);
3392   uint32_t ValHi = Hi_32(Val);
3393   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3394 
3395     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
3396          bitOpWithConstantIsReducible(Opc, ValHi)) ||
3397         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
3398     // If we need to materialize a 64-bit immediate, it will be split up later
3399     // anyway. Avoid creating the harder to understand 64-bit immediate
3400     // materialization.
3401     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
3402   }
3403 
3404   return SDValue();
3405 }
3406 
3407 SDValue SITargetLowering::performAndCombine(SDNode *N,
3408                                             DAGCombinerInfo &DCI) const {
3409   if (DCI.isBeforeLegalize())
3410     return SDValue();
3411 
3412   SelectionDAG &DAG = DCI.DAG;
3413   EVT VT = N->getValueType(0);
3414   SDValue LHS = N->getOperand(0);
3415   SDValue RHS = N->getOperand(1);
3416 
3417 
3418   if (VT == MVT::i64) {
3419     const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3420     if (CRHS) {
3421       if (SDValue Split
3422           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
3423         return Split;
3424     }
3425   }
3426 
3427   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
3428   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
3429   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
3430     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
3431     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
3432 
3433     SDValue X = LHS.getOperand(0);
3434     SDValue Y = RHS.getOperand(0);
3435     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
3436       return SDValue();
3437 
3438     if (LCC == ISD::SETO) {
3439       if (X != LHS.getOperand(1))
3440         return SDValue();
3441 
3442       if (RCC == ISD::SETUNE) {
3443         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
3444         if (!C1 || !C1->isInfinity() || C1->isNegative())
3445           return SDValue();
3446 
3447         const uint32_t Mask = SIInstrFlags::N_NORMAL |
3448                               SIInstrFlags::N_SUBNORMAL |
3449                               SIInstrFlags::N_ZERO |
3450                               SIInstrFlags::P_ZERO |
3451                               SIInstrFlags::P_SUBNORMAL |
3452                               SIInstrFlags::P_NORMAL;
3453 
3454         static_assert(((~(SIInstrFlags::S_NAN |
3455                           SIInstrFlags::Q_NAN |
3456                           SIInstrFlags::N_INFINITY |
3457                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
3458                       "mask not equal");
3459 
3460         SDLoc DL(N);
3461         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3462                            X, DAG.getConstant(Mask, DL, MVT::i32));
3463       }
3464     }
3465   }
3466 
3467   return SDValue();
3468 }
3469 
3470 SDValue SITargetLowering::performOrCombine(SDNode *N,
3471                                            DAGCombinerInfo &DCI) const {
3472   SelectionDAG &DAG = DCI.DAG;
3473   SDValue LHS = N->getOperand(0);
3474   SDValue RHS = N->getOperand(1);
3475 
3476   EVT VT = N->getValueType(0);
3477   if (VT == MVT::i1) {
3478     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
3479     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
3480         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
3481       SDValue Src = LHS.getOperand(0);
3482       if (Src != RHS.getOperand(0))
3483         return SDValue();
3484 
3485       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
3486       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
3487       if (!CLHS || !CRHS)
3488         return SDValue();
3489 
3490       // Only 10 bits are used.
3491       static const uint32_t MaxMask = 0x3ff;
3492 
3493       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
3494       SDLoc DL(N);
3495       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
3496                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
3497     }
3498 
3499     return SDValue();
3500   }
3501 
3502   if (VT != MVT::i64)
3503     return SDValue();
3504 
3505   // TODO: This could be a generic combine with a predicate for extracting the
3506   // high half of an integer being free.
3507 
3508   // (or i64:x, (zero_extend i32:y)) ->
3509   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
3510   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
3511       RHS.getOpcode() != ISD::ZERO_EXTEND)
3512     std::swap(LHS, RHS);
3513 
3514   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
3515     SDValue ExtSrc = RHS.getOperand(0);
3516     EVT SrcVT = ExtSrc.getValueType();
3517     if (SrcVT == MVT::i32) {
3518       SDLoc SL(N);
3519       SDValue LowLHS, HiBits;
3520       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
3521       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
3522 
3523       DCI.AddToWorklist(LowOr.getNode());
3524       DCI.AddToWorklist(HiBits.getNode());
3525 
3526       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
3527                                 LowOr, HiBits);
3528       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3529     }
3530   }
3531 
3532   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3533   if (CRHS) {
3534     if (SDValue Split
3535           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
3536       return Split;
3537   }
3538 
3539   return SDValue();
3540 }
3541 
3542 SDValue SITargetLowering::performXorCombine(SDNode *N,
3543                                             DAGCombinerInfo &DCI) const {
3544   EVT VT = N->getValueType(0);
3545   if (VT != MVT::i64)
3546     return SDValue();
3547 
3548   SDValue LHS = N->getOperand(0);
3549   SDValue RHS = N->getOperand(1);
3550 
3551   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
3552   if (CRHS) {
3553     if (SDValue Split
3554           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
3555       return Split;
3556   }
3557 
3558   return SDValue();
3559 }
3560 
3561 SDValue SITargetLowering::performClassCombine(SDNode *N,
3562                                               DAGCombinerInfo &DCI) const {
3563   SelectionDAG &DAG = DCI.DAG;
3564   SDValue Mask = N->getOperand(1);
3565 
3566   // fp_class x, 0 -> false
3567   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
3568     if (CMask->isNullValue())
3569       return DAG.getConstant(0, SDLoc(N), MVT::i1);
3570   }
3571 
3572   if (N->getOperand(0).isUndef())
3573     return DAG.getUNDEF(MVT::i1);
3574 
3575   return SDValue();
3576 }
3577 
3578 // Constant fold canonicalize.
3579 SDValue SITargetLowering::performFCanonicalizeCombine(
3580   SDNode *N,
3581   DAGCombinerInfo &DCI) const {
3582   ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3583   if (!CFP)
3584     return SDValue();
3585 
3586   SelectionDAG &DAG = DCI.DAG;
3587   const APFloat &C = CFP->getValueAPF();
3588 
3589   // Flush denormals to 0 if not enabled.
3590   if (C.isDenormal()) {
3591     EVT VT = N->getValueType(0);
3592     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals())
3593       return DAG.getConstantFP(0.0, SDLoc(N), VT);
3594 
3595     if (VT == MVT::f64 && !Subtarget->hasFP64Denormals())
3596       return DAG.getConstantFP(0.0, SDLoc(N), VT);
3597   }
3598 
3599   if (C.isNaN()) {
3600     EVT VT = N->getValueType(0);
3601     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
3602     if (C.isSignaling()) {
3603       // Quiet a signaling NaN.
3604       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3605     }
3606 
3607     // Make sure it is the canonical NaN bitpattern.
3608     //
3609     // TODO: Can we use -1 as the canonical NaN value since it's an inline
3610     // immediate?
3611     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
3612       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
3613   }
3614 
3615   return SDValue(CFP, 0);
3616 }
3617 
3618 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
3619   switch (Opc) {
3620   case ISD::FMAXNUM:
3621     return AMDGPUISD::FMAX3;
3622   case ISD::SMAX:
3623     return AMDGPUISD::SMAX3;
3624   case ISD::UMAX:
3625     return AMDGPUISD::UMAX3;
3626   case ISD::FMINNUM:
3627     return AMDGPUISD::FMIN3;
3628   case ISD::SMIN:
3629     return AMDGPUISD::SMIN3;
3630   case ISD::UMIN:
3631     return AMDGPUISD::UMIN3;
3632   default:
3633     llvm_unreachable("Not a min/max opcode");
3634   }
3635 }
3636 
3637 static SDValue performIntMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3638                                         SDValue Op0, SDValue Op1, bool Signed) {
3639   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
3640   if (!K1)
3641     return SDValue();
3642 
3643   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
3644   if (!K0)
3645     return SDValue();
3646 
3647   if (Signed) {
3648     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
3649       return SDValue();
3650   } else {
3651     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
3652       return SDValue();
3653   }
3654 
3655   EVT VT = K0->getValueType(0);
3656 
3657   MVT NVT = MVT::i32;
3658   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3659 
3660   SDValue Tmp1, Tmp2, Tmp3;
3661   Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
3662   Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
3663   Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
3664 
3665   if (VT == MVT::i16) {
3666     Tmp1 = DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, NVT,
3667                        Tmp1, Tmp2, Tmp3);
3668 
3669     return DAG.getNode(ISD::TRUNCATE, SL, VT, Tmp1);
3670   } else
3671     return DAG.getNode(Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3, SL, VT,
3672                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
3673 }
3674 
3675 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
3676   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
3677     return true;
3678 
3679   return DAG.isKnownNeverNaN(Op);
3680 }
3681 
3682 static SDValue performFPMed3ImmCombine(SelectionDAG &DAG, const SDLoc &SL,
3683                                        SDValue Op0, SDValue Op1) {
3684   ConstantFPSDNode *K1 = dyn_cast<ConstantFPSDNode>(Op1);
3685   if (!K1)
3686     return SDValue();
3687 
3688   ConstantFPSDNode *K0 = dyn_cast<ConstantFPSDNode>(Op0.getOperand(1));
3689   if (!K0)
3690     return SDValue();
3691 
3692   // Ordered >= (although NaN inputs should have folded away by now).
3693   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
3694   if (Cmp == APFloat::cmpGreaterThan)
3695     return SDValue();
3696 
3697   // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
3698   // signaling NaN gives a quiet NaN. The quiet NaN input to the min would then
3699   // give the other result, which is different from med3 with a NaN input.
3700   SDValue Var = Op0.getOperand(0);
3701   if (!isKnownNeverSNan(DAG, Var))
3702     return SDValue();
3703 
3704   return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
3705                      Var, SDValue(K0, 0), SDValue(K1, 0));
3706 }
3707 
3708 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
3709                                                DAGCombinerInfo &DCI) const {
3710   SelectionDAG &DAG = DCI.DAG;
3711 
3712   unsigned Opc = N->getOpcode();
3713   SDValue Op0 = N->getOperand(0);
3714   SDValue Op1 = N->getOperand(1);
3715 
3716   // Only do this if the inner op has one use since this will just increases
3717   // register pressure for no benefit.
3718 
3719   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY) {
3720     // max(max(a, b), c) -> max3(a, b, c)
3721     // min(min(a, b), c) -> min3(a, b, c)
3722     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
3723       SDLoc DL(N);
3724       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3725                          DL,
3726                          N->getValueType(0),
3727                          Op0.getOperand(0),
3728                          Op0.getOperand(1),
3729                          Op1);
3730     }
3731 
3732     // Try commuted.
3733     // max(a, max(b, c)) -> max3(a, b, c)
3734     // min(a, min(b, c)) -> min3(a, b, c)
3735     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
3736       SDLoc DL(N);
3737       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
3738                          DL,
3739                          N->getValueType(0),
3740                          Op0,
3741                          Op1.getOperand(0),
3742                          Op1.getOperand(1));
3743     }
3744   }
3745 
3746   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
3747   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
3748     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
3749       return Med3;
3750   }
3751 
3752   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
3753     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
3754       return Med3;
3755   }
3756 
3757   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
3758   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
3759        (Opc == AMDGPUISD::FMIN_LEGACY &&
3760         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
3761       N->getValueType(0) == MVT::f32 && Op0.hasOneUse()) {
3762     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
3763       return Res;
3764   }
3765 
3766   return SDValue();
3767 }
3768 
3769 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
3770                                               DAGCombinerInfo &DCI) const {
3771   SelectionDAG &DAG = DCI.DAG;
3772   SDLoc SL(N);
3773 
3774   SDValue LHS = N->getOperand(0);
3775   SDValue RHS = N->getOperand(1);
3776   EVT VT = LHS.getValueType();
3777 
3778   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
3779                                            VT != MVT::f16))
3780     return SDValue();
3781 
3782   // Match isinf pattern
3783   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
3784   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
3785   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
3786     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
3787     if (!CRHS)
3788       return SDValue();
3789 
3790     const APFloat &APF = CRHS->getValueAPF();
3791     if (APF.isInfinity() && !APF.isNegative()) {
3792       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
3793       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
3794                          DAG.getConstant(Mask, SL, MVT::i32));
3795     }
3796   }
3797 
3798   return SDValue();
3799 }
3800 
3801 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
3802                                             DAGCombinerInfo &DCI) const {
3803   SelectionDAG &DAG = DCI.DAG;
3804   SDLoc DL(N);
3805 
3806   switch (N->getOpcode()) {
3807   default:
3808     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
3809   case ISD::SETCC:
3810     return performSetCCCombine(N, DCI);
3811   case ISD::FMAXNUM:
3812   case ISD::FMINNUM:
3813   case ISD::SMAX:
3814   case ISD::SMIN:
3815   case ISD::UMAX:
3816   case ISD::UMIN:
3817   case AMDGPUISD::FMIN_LEGACY:
3818   case AMDGPUISD::FMAX_LEGACY: {
3819     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
3820         N->getValueType(0) != MVT::f64 &&
3821         getTargetMachine().getOptLevel() > CodeGenOpt::None)
3822       return performMinMaxCombine(N, DCI);
3823     break;
3824   }
3825 
3826   case AMDGPUISD::CVT_F32_UBYTE0:
3827   case AMDGPUISD::CVT_F32_UBYTE1:
3828   case AMDGPUISD::CVT_F32_UBYTE2:
3829   case AMDGPUISD::CVT_F32_UBYTE3: {
3830     unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
3831 
3832     SDValue Src = N->getOperand(0);
3833     SDValue Srl = N->getOperand(0);
3834     if (Srl.getOpcode() == ISD::ZERO_EXTEND)
3835       Srl = Srl.getOperand(0);
3836 
3837     // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
3838     if (Srl.getOpcode() == ISD::SRL) {
3839       // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
3840       // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
3841       // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
3842 
3843       if (const ConstantSDNode *C =
3844               dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
3845         Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
3846                                  EVT(MVT::i32));
3847 
3848         unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
3849         if (SrcOffset < 32 && SrcOffset % 8 == 0) {
3850           return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, DL,
3851                              MVT::f32, Srl);
3852         }
3853       }
3854     }
3855 
3856     APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
3857 
3858     APInt KnownZero, KnownOne;
3859     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
3860                                           !DCI.isBeforeLegalizeOps());
3861     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3862     if (TLO.ShrinkDemandedConstant(Src, Demanded) ||
3863         TLI.SimplifyDemandedBits(Src, Demanded, KnownZero, KnownOne, TLO)) {
3864       DCI.CommitTargetLoweringOpt(TLO);
3865     }
3866 
3867     break;
3868   }
3869   case ISD::SINT_TO_FP:
3870   case ISD::UINT_TO_FP: {
3871     return performUCharToFloatCombine(N, DCI);
3872   }
3873   case ISD::FADD: {
3874     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3875       break;
3876 
3877     EVT VT = N->getValueType(0);
3878     if (VT != MVT::f32)
3879       break;
3880 
3881     // Only do this if we are not trying to support denormals. v_mad_f32 does
3882     // not support denormals ever.
3883     if (Subtarget->hasFP32Denormals())
3884       break;
3885 
3886     SDValue LHS = N->getOperand(0);
3887     SDValue RHS = N->getOperand(1);
3888 
3889     // These should really be instruction patterns, but writing patterns with
3890     // source modiifiers is a pain.
3891 
3892     // fadd (fadd (a, a), b) -> mad 2.0, a, b
3893     if (LHS.getOpcode() == ISD::FADD) {
3894       SDValue A = LHS.getOperand(0);
3895       if (A == LHS.getOperand(1)) {
3896         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3897         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, RHS);
3898       }
3899     }
3900 
3901     // fadd (b, fadd (a, a)) -> mad 2.0, a, b
3902     if (RHS.getOpcode() == ISD::FADD) {
3903       SDValue A = RHS.getOperand(0);
3904       if (A == RHS.getOperand(1)) {
3905         const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3906         return DAG.getNode(ISD::FMAD, DL, VT, Two, A, LHS);
3907       }
3908     }
3909 
3910     return SDValue();
3911   }
3912   case ISD::FSUB: {
3913     if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
3914       break;
3915 
3916     EVT VT = N->getValueType(0);
3917 
3918     // Try to get the fneg to fold into the source modifier. This undoes generic
3919     // DAG combines and folds them into the mad.
3920     //
3921     // Only do this if we are not trying to support denormals. v_mad_f32 does
3922     // not support denormals ever.
3923     if (VT == MVT::f32 && !Subtarget->hasFP32Denormals()) {
3924       SDValue LHS = N->getOperand(0);
3925       SDValue RHS = N->getOperand(1);
3926       if (LHS.getOpcode() == ISD::FADD) {
3927         // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
3928 
3929         SDValue A = LHS.getOperand(0);
3930         if (A == LHS.getOperand(1)) {
3931           const SDValue Two = DAG.getConstantFP(2.0, DL, MVT::f32);
3932           SDValue NegRHS = DAG.getNode(ISD::FNEG, DL, VT, RHS);
3933 
3934           return DAG.getNode(ISD::FMAD, DL, VT, Two, A, NegRHS);
3935         }
3936       }
3937 
3938       if (RHS.getOpcode() == ISD::FADD) {
3939         // (fsub c, (fadd a, a)) -> mad -2.0, a, c
3940 
3941         SDValue A = RHS.getOperand(0);
3942         if (A == RHS.getOperand(1)) {
3943           const SDValue NegTwo = DAG.getConstantFP(-2.0, DL, MVT::f32);
3944           return DAG.getNode(ISD::FMAD, DL, VT, NegTwo, A, LHS);
3945         }
3946       }
3947 
3948       return SDValue();
3949     }
3950 
3951     break;
3952   }
3953   case ISD::LOAD:
3954   case ISD::STORE:
3955   case ISD::ATOMIC_LOAD:
3956   case ISD::ATOMIC_STORE:
3957   case ISD::ATOMIC_CMP_SWAP:
3958   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3959   case ISD::ATOMIC_SWAP:
3960   case ISD::ATOMIC_LOAD_ADD:
3961   case ISD::ATOMIC_LOAD_SUB:
3962   case ISD::ATOMIC_LOAD_AND:
3963   case ISD::ATOMIC_LOAD_OR:
3964   case ISD::ATOMIC_LOAD_XOR:
3965   case ISD::ATOMIC_LOAD_NAND:
3966   case ISD::ATOMIC_LOAD_MIN:
3967   case ISD::ATOMIC_LOAD_MAX:
3968   case ISD::ATOMIC_LOAD_UMIN:
3969   case ISD::ATOMIC_LOAD_UMAX:
3970   case AMDGPUISD::ATOMIC_INC:
3971   case AMDGPUISD::ATOMIC_DEC: { // TODO: Target mem intrinsics.
3972     if (DCI.isBeforeLegalize())
3973       break;
3974 
3975     MemSDNode *MemNode = cast<MemSDNode>(N);
3976     SDValue Ptr = MemNode->getBasePtr();
3977 
3978     // TODO: We could also do this for multiplies.
3979     unsigned AS = MemNode->getAddressSpace();
3980     if (Ptr.getOpcode() == ISD::SHL && AS != AMDGPUAS::PRIVATE_ADDRESS) {
3981       SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), AS, DCI);
3982       if (NewPtr) {
3983         SmallVector<SDValue, 8> NewOps(MemNode->op_begin(), MemNode->op_end());
3984 
3985         NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
3986         return SDValue(DAG.UpdateNodeOperands(MemNode, NewOps), 0);
3987       }
3988     }
3989     break;
3990   }
3991   case ISD::AND:
3992     return performAndCombine(N, DCI);
3993   case ISD::OR:
3994     return performOrCombine(N, DCI);
3995   case ISD::XOR:
3996     return performXorCombine(N, DCI);
3997   case AMDGPUISD::FP_CLASS:
3998     return performClassCombine(N, DCI);
3999   case ISD::FCANONICALIZE:
4000     return performFCanonicalizeCombine(N, DCI);
4001   case AMDGPUISD::FRACT:
4002   case AMDGPUISD::RCP:
4003   case AMDGPUISD::RSQ:
4004   case AMDGPUISD::RCP_LEGACY:
4005   case AMDGPUISD::RSQ_LEGACY:
4006   case AMDGPUISD::RSQ_CLAMP:
4007   case AMDGPUISD::LDEXP: {
4008     SDValue Src = N->getOperand(0);
4009     if (Src.isUndef())
4010       return Src;
4011     break;
4012   }
4013   }
4014   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
4015 }
4016 
4017 /// \brief Helper function for adjustWritemask
4018 static unsigned SubIdx2Lane(unsigned Idx) {
4019   switch (Idx) {
4020   default: return 0;
4021   case AMDGPU::sub0: return 0;
4022   case AMDGPU::sub1: return 1;
4023   case AMDGPU::sub2: return 2;
4024   case AMDGPU::sub3: return 3;
4025   }
4026 }
4027 
4028 /// \brief Adjust the writemask of MIMG instructions
4029 void SITargetLowering::adjustWritemask(MachineSDNode *&Node,
4030                                        SelectionDAG &DAG) const {
4031   SDNode *Users[4] = { };
4032   unsigned Lane = 0;
4033   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
4034   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
4035   unsigned NewDmask = 0;
4036 
4037   // Try to figure out the used register components
4038   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
4039        I != E; ++I) {
4040 
4041     // Abort if we can't understand the usage
4042     if (!I->isMachineOpcode() ||
4043         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
4044       return;
4045 
4046     // Lane means which subreg of %VGPRa_VGPRb_VGPRc_VGPRd is used.
4047     // Note that subregs are packed, i.e. Lane==0 is the first bit set
4048     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
4049     // set, etc.
4050     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
4051 
4052     // Set which texture component corresponds to the lane.
4053     unsigned Comp;
4054     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
4055       assert(Dmask);
4056       Comp = countTrailingZeros(Dmask);
4057       Dmask &= ~(1 << Comp);
4058     }
4059 
4060     // Abort if we have more than one user per component
4061     if (Users[Lane])
4062       return;
4063 
4064     Users[Lane] = *I;
4065     NewDmask |= 1 << Comp;
4066   }
4067 
4068   // Abort if there's no change
4069   if (NewDmask == OldDmask)
4070     return;
4071 
4072   // Adjust the writemask in the node
4073   std::vector<SDValue> Ops;
4074   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
4075   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
4076   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
4077   Node = (MachineSDNode*)DAG.UpdateNodeOperands(Node, Ops);
4078 
4079   // If we only got one lane, replace it with a copy
4080   // (if NewDmask has only one bit set...)
4081   if (NewDmask && (NewDmask & (NewDmask-1)) == 0) {
4082     SDValue RC = DAG.getTargetConstant(AMDGPU::VGPR_32RegClassID, SDLoc(),
4083                                        MVT::i32);
4084     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4085                                       SDLoc(), Users[Lane]->getValueType(0),
4086                                       SDValue(Node, 0), RC);
4087     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
4088     return;
4089   }
4090 
4091   // Update the users of the node with the new indices
4092   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
4093 
4094     SDNode *User = Users[i];
4095     if (!User)
4096       continue;
4097 
4098     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
4099     DAG.UpdateNodeOperands(User, User->getOperand(0), Op);
4100 
4101     switch (Idx) {
4102     default: break;
4103     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
4104     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
4105     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
4106     }
4107   }
4108 }
4109 
4110 static bool isFrameIndexOp(SDValue Op) {
4111   if (Op.getOpcode() == ISD::AssertZext)
4112     Op = Op.getOperand(0);
4113 
4114   return isa<FrameIndexSDNode>(Op);
4115 }
4116 
4117 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
4118 /// with frame index operands.
4119 /// LLVM assumes that inputs are to these instructions are registers.
4120 void SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
4121                                                      SelectionDAG &DAG) const {
4122 
4123   SmallVector<SDValue, 8> Ops;
4124   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
4125     if (!isFrameIndexOp(Node->getOperand(i))) {
4126       Ops.push_back(Node->getOperand(i));
4127       continue;
4128     }
4129 
4130     SDLoc DL(Node);
4131     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
4132                                      Node->getOperand(i).getValueType(),
4133                                      Node->getOperand(i)), 0));
4134   }
4135 
4136   DAG.UpdateNodeOperands(Node, Ops);
4137 }
4138 
4139 /// \brief Fold the instructions after selecting them.
4140 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
4141                                           SelectionDAG &DAG) const {
4142   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4143   unsigned Opcode = Node->getMachineOpcode();
4144 
4145   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
4146       !TII->isGather4(Opcode))
4147     adjustWritemask(Node, DAG);
4148 
4149   if (Opcode == AMDGPU::INSERT_SUBREG ||
4150       Opcode == AMDGPU::REG_SEQUENCE) {
4151     legalizeTargetIndependentNode(Node, DAG);
4152     return Node;
4153   }
4154   return Node;
4155 }
4156 
4157 /// \brief Assign the register class depending on the number of
4158 /// bits set in the writemask
4159 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
4160                                                      SDNode *Node) const {
4161   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4162 
4163   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
4164 
4165   if (TII->isVOP3(MI.getOpcode())) {
4166     // Make sure constant bus requirements are respected.
4167     TII->legalizeOperandsVOP3(MRI, MI);
4168     return;
4169   }
4170 
4171   if (TII->isMIMG(MI)) {
4172     unsigned VReg = MI.getOperand(0).getReg();
4173     const TargetRegisterClass *RC = MRI.getRegClass(VReg);
4174     // TODO: Need mapping tables to handle other cases (register classes).
4175     if (RC != &AMDGPU::VReg_128RegClass)
4176       return;
4177 
4178     unsigned DmaskIdx = MI.getNumOperands() == 12 ? 3 : 4;
4179     unsigned Writemask = MI.getOperand(DmaskIdx).getImm();
4180     unsigned BitsSet = 0;
4181     for (unsigned i = 0; i < 4; ++i)
4182       BitsSet += Writemask & (1 << i) ? 1 : 0;
4183     switch (BitsSet) {
4184     default: return;
4185     case 1:  RC = &AMDGPU::VGPR_32RegClass; break;
4186     case 2:  RC = &AMDGPU::VReg_64RegClass; break;
4187     case 3:  RC = &AMDGPU::VReg_96RegClass; break;
4188     }
4189 
4190     unsigned NewOpcode = TII->getMaskedMIMGOp(MI.getOpcode(), BitsSet);
4191     MI.setDesc(TII->get(NewOpcode));
4192     MRI.setRegClass(VReg, RC);
4193     return;
4194   }
4195 
4196   // Replace unused atomics with the no return version.
4197   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
4198   if (NoRetAtomicOp != -1) {
4199     if (!Node->hasAnyUseOfValue(0)) {
4200       MI.setDesc(TII->get(NoRetAtomicOp));
4201       MI.RemoveOperand(0);
4202       return;
4203     }
4204 
4205     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
4206     // instruction, because the return type of these instructions is a vec2 of
4207     // the memory type, so it can be tied to the input operand.
4208     // This means these instructions always have a use, so we need to add a
4209     // special case to check if the atomic has only one extract_subreg use,
4210     // which itself has no uses.
4211     if ((Node->hasNUsesOfValue(1, 0) &&
4212          Node->use_begin()->isMachineOpcode() &&
4213          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
4214          !Node->use_begin()->hasAnyUseOfValue(0))) {
4215       unsigned Def = MI.getOperand(0).getReg();
4216 
4217       // Change this into a noret atomic.
4218       MI.setDesc(TII->get(NoRetAtomicOp));
4219       MI.RemoveOperand(0);
4220 
4221       // If we only remove the def operand from the atomic instruction, the
4222       // extract_subreg will be left with a use of a vreg without a def.
4223       // So we need to insert an implicit_def to avoid machine verifier
4224       // errors.
4225       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
4226               TII->get(AMDGPU::IMPLICIT_DEF), Def);
4227     }
4228     return;
4229   }
4230 }
4231 
4232 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
4233                               uint64_t Val) {
4234   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
4235   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
4236 }
4237 
4238 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
4239                                                 const SDLoc &DL,
4240                                                 SDValue Ptr) const {
4241   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4242 
4243   // Build the half of the subregister with the constants before building the
4244   // full 128-bit register. If we are building multiple resource descriptors,
4245   // this will allow CSEing of the 2-component register.
4246   const SDValue Ops0[] = {
4247     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
4248     buildSMovImm32(DAG, DL, 0),
4249     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4250     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
4251     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
4252   };
4253 
4254   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
4255                                                 MVT::v2i32, Ops0), 0);
4256 
4257   // Combine the constants and the pointer.
4258   const SDValue Ops1[] = {
4259     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4260     Ptr,
4261     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
4262     SubRegHi,
4263     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
4264   };
4265 
4266   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
4267 }
4268 
4269 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
4270 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
4271 ///        of the resource descriptor) to create an offset, which is added to
4272 ///        the resource pointer.
4273 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
4274                                            SDValue Ptr, uint32_t RsrcDword1,
4275                                            uint64_t RsrcDword2And3) const {
4276   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
4277   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
4278   if (RsrcDword1) {
4279     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
4280                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
4281                     0);
4282   }
4283 
4284   SDValue DataLo = buildSMovImm32(DAG, DL,
4285                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
4286   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
4287 
4288   const SDValue Ops[] = {
4289     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
4290     PtrLo,
4291     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
4292     PtrHi,
4293     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
4294     DataLo,
4295     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
4296     DataHi,
4297     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
4298   };
4299 
4300   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
4301 }
4302 
4303 SDValue SITargetLowering::CreateLiveInRegister(SelectionDAG &DAG,
4304                                                const TargetRegisterClass *RC,
4305                                                unsigned Reg, EVT VT) const {
4306   SDValue VReg = AMDGPUTargetLowering::CreateLiveInRegister(DAG, RC, Reg, VT);
4307 
4308   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(DAG.getEntryNode()),
4309                             cast<RegisterSDNode>(VReg)->getReg(), VT);
4310 }
4311 
4312 //===----------------------------------------------------------------------===//
4313 //                         SI Inline Assembly Support
4314 //===----------------------------------------------------------------------===//
4315 
4316 std::pair<unsigned, const TargetRegisterClass *>
4317 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4318                                                StringRef Constraint,
4319                                                MVT VT) const {
4320   if (!isTypeLegal(VT))
4321     return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4322 
4323   if (Constraint.size() == 1) {
4324     switch (Constraint[0]) {
4325     case 's':
4326     case 'r':
4327       switch (VT.getSizeInBits()) {
4328       default:
4329         return std::make_pair(0U, nullptr);
4330       case 32:
4331         return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
4332       case 64:
4333         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
4334       case 128:
4335         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
4336       case 256:
4337         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
4338       }
4339 
4340     case 'v':
4341       switch (VT.getSizeInBits()) {
4342       default:
4343         return std::make_pair(0U, nullptr);
4344       case 32:
4345         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
4346       case 64:
4347         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
4348       case 96:
4349         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
4350       case 128:
4351         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
4352       case 256:
4353         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
4354       case 512:
4355         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
4356       }
4357     }
4358   }
4359 
4360   if (Constraint.size() > 1) {
4361     const TargetRegisterClass *RC = nullptr;
4362     if (Constraint[1] == 'v') {
4363       RC = &AMDGPU::VGPR_32RegClass;
4364     } else if (Constraint[1] == 's') {
4365       RC = &AMDGPU::SGPR_32RegClass;
4366     }
4367 
4368     if (RC) {
4369       uint32_t Idx;
4370       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
4371       if (!Failed && Idx < RC->getNumRegs())
4372         return std::make_pair(RC->getRegister(Idx), RC);
4373     }
4374   }
4375   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4376 }
4377 
4378 SITargetLowering::ConstraintType
4379 SITargetLowering::getConstraintType(StringRef Constraint) const {
4380   if (Constraint.size() == 1) {
4381     switch (Constraint[0]) {
4382     default: break;
4383     case 's':
4384     case 'v':
4385       return C_RegisterClass;
4386     }
4387   }
4388   return TargetLowering::getConstraintType(Constraint);
4389 }
4390