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