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