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