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