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