1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// \brief Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #endif
19 
20 #include "SIISelLowering.h"
21 #include "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/ADT/APFloat.h"
31 #include "llvm/ADT/APInt.h"
32 #include "llvm/ADT/ArrayRef.h"
33 #include "llvm/ADT/BitVector.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/MachineValueType.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Target/TargetOptions.h"
78 #include <cassert>
79 #include <cmath>
80 #include <cstdint>
81 #include <iterator>
82 #include <tuple>
83 #include <utility>
84 #include <vector>
85 
86 using namespace llvm;
87 
88 #define DEBUG_TYPE "si-lower"
89 
90 STATISTIC(NumTailCalls, "Number of tail calls");
91 
92 static cl::opt<bool> EnableVGPRIndexMode(
93   "amdgpu-vgpr-index-mode",
94   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
95   cl::init(false));
96 
97 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
98   "amdgpu-frame-index-zero-bits",
99   cl::desc("High bits of frame index assumed to be zero"),
100   cl::init(5),
101   cl::ReallyHidden);
102 
103 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107       return AMDGPU::SGPR0 + Reg;
108     }
109   }
110   llvm_unreachable("Cannot allocate sgpr");
111 }
112 
113 SITargetLowering::SITargetLowering(const TargetMachine &TM,
114                                    const SISubtarget &STI)
115     : AMDGPUTargetLowering(TM, STI) {
116   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
117   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
118 
119   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
120   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
121 
122   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
123   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
124   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
125 
126   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
127   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
128 
129   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
130   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
131 
132   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
133   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
134 
135   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
136   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
137 
138   if (Subtarget->has16BitInsts()) {
139     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
140     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
141   }
142 
143   if (Subtarget->hasVOP3PInsts()) {
144     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
146   }
147 
148   computeRegisterProperties(STI.getRegisterInfo());
149 
150   // We need to custom lower vector stores from local memory
151   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
152   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
153   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
154   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::i1, Custom);
156 
157   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
158   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
159   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
160   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
161   setOperationAction(ISD::STORE, MVT::i1, Custom);
162 
163   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
164   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
173 
174   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
175   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176   setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand);
177 
178   setOperationAction(ISD::SELECT, MVT::i1, Promote);
179   setOperationAction(ISD::SELECT, MVT::i64, Custom);
180   setOperationAction(ISD::SELECT, MVT::f64, Promote);
181   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
182 
183   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
184   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
185   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
186   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
187   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
188 
189   setOperationAction(ISD::SETCC, MVT::i1, Promote);
190   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
191   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
192   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
193 
194   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
195   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
196 
197   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
198   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
199   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
200   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
201   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
202   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
203   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
204 
205   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
206   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
207   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
208   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
209   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
210 
211   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
212   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
213   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
214 
215   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
216   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
217   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
218   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
219 
220   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
221   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
222   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
224   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
225   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
226 
227   setOperationAction(ISD::UADDO, MVT::i32, Legal);
228   setOperationAction(ISD::USUBO, MVT::i32, Legal);
229 
230   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
231   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
232 
233 #if 0
234   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
235   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
236 #endif
237 
238   //setOperationAction(ISD::ADDC, MVT::i64, Expand);
239   //setOperationAction(ISD::SUBC, MVT::i64, Expand);
240 
241   // We only support LOAD/STORE and vector manipulation ops for vectors
242   // with > 4 elements.
243   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
244         MVT::v2i64, MVT::v2f64}) {
245     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
246       switch (Op) {
247       case ISD::LOAD:
248       case ISD::STORE:
249       case ISD::BUILD_VECTOR:
250       case ISD::BITCAST:
251       case ISD::EXTRACT_VECTOR_ELT:
252       case ISD::INSERT_VECTOR_ELT:
253       case ISD::INSERT_SUBVECTOR:
254       case ISD::EXTRACT_SUBVECTOR:
255       case ISD::SCALAR_TO_VECTOR:
256         break;
257       case ISD::CONCAT_VECTORS:
258         setOperationAction(Op, VT, Custom);
259         break;
260       default:
261         setOperationAction(Op, VT, Expand);
262         break;
263       }
264     }
265   }
266 
267   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
268   // is expanded to avoid having two separate loops in case the index is a VGPR.
269 
270   // Most operations are naturally 32-bit vector operations. We only support
271   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
272   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
273     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
274     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
275 
276     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
277     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
278 
279     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
280     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
281 
282     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
283     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
284   }
285 
286   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
287   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
288   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
289   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
290 
291   // Avoid stack access for these.
292   // TODO: Generalize to more vector types.
293   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
294   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
295   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
296   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
297 
298   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
299   // and output demarshalling
300   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
301   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
302 
303   // We can't return success/failure, only the old value,
304   // let LLVM add the comparison
305   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
306   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
307 
308   if (getSubtarget()->hasFlatAddressSpace()) {
309     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
310     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
311   }
312 
313   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
314   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
315 
316   // On SI this is s_memtime and s_memrealtime on VI.
317   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
318   setOperationAction(ISD::TRAP, MVT::Other, Custom);
319   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
320 
321   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
322   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
323 
324   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
325     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
326     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
327     setOperationAction(ISD::FRINT, MVT::f64, Legal);
328   }
329 
330   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
331 
332   setOperationAction(ISD::FSIN, MVT::f32, Custom);
333   setOperationAction(ISD::FCOS, MVT::f32, Custom);
334   setOperationAction(ISD::FDIV, MVT::f32, Custom);
335   setOperationAction(ISD::FDIV, MVT::f64, Custom);
336 
337   if (Subtarget->has16BitInsts()) {
338     setOperationAction(ISD::Constant, MVT::i16, Legal);
339 
340     setOperationAction(ISD::SMIN, MVT::i16, Legal);
341     setOperationAction(ISD::SMAX, MVT::i16, Legal);
342 
343     setOperationAction(ISD::UMIN, MVT::i16, Legal);
344     setOperationAction(ISD::UMAX, MVT::i16, Legal);
345 
346     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
347     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
348 
349     setOperationAction(ISD::ROTR, MVT::i16, Promote);
350     setOperationAction(ISD::ROTL, MVT::i16, Promote);
351 
352     setOperationAction(ISD::SDIV, MVT::i16, Promote);
353     setOperationAction(ISD::UDIV, MVT::i16, Promote);
354     setOperationAction(ISD::SREM, MVT::i16, Promote);
355     setOperationAction(ISD::UREM, MVT::i16, Promote);
356 
357     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
358     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
359 
360     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
361     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
362     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
363     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
364 
365     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
366 
367     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
368 
369     setOperationAction(ISD::LOAD, MVT::i16, Custom);
370 
371     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
372 
373     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
374     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
375     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
376     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
377 
378     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
382 
383     // F16 - Constant Actions.
384     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
385 
386     // F16 - Load/Store Actions.
387     setOperationAction(ISD::LOAD, MVT::f16, Promote);
388     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
389     setOperationAction(ISD::STORE, MVT::f16, Promote);
390     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
391 
392     // F16 - VOP1 Actions.
393     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
394     setOperationAction(ISD::FCOS, MVT::f16, Promote);
395     setOperationAction(ISD::FSIN, MVT::f16, Promote);
396     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
397     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
398     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
399     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
400     setOperationAction(ISD::FROUND, MVT::f16, Custom);
401 
402     // F16 - VOP2 Actions.
403     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
404     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
405     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
406     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
407     setOperationAction(ISD::FDIV, MVT::f16, Custom);
408 
409     // F16 - VOP3 Actions.
410     setOperationAction(ISD::FMA, MVT::f16, Legal);
411     if (!Subtarget->hasFP16Denormals())
412       setOperationAction(ISD::FMAD, MVT::f16, Legal);
413   }
414 
415   if (Subtarget->hasVOP3PInsts()) {
416     for (MVT VT : {MVT::v2i16, MVT::v2f16}) {
417       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
418         switch (Op) {
419         case ISD::LOAD:
420         case ISD::STORE:
421         case ISD::BUILD_VECTOR:
422         case ISD::BITCAST:
423         case ISD::EXTRACT_VECTOR_ELT:
424         case ISD::INSERT_VECTOR_ELT:
425         case ISD::INSERT_SUBVECTOR:
426         case ISD::EXTRACT_SUBVECTOR:
427         case ISD::SCALAR_TO_VECTOR:
428           break;
429         case ISD::CONCAT_VECTORS:
430           setOperationAction(Op, VT, Custom);
431           break;
432         default:
433           setOperationAction(Op, VT, Expand);
434           break;
435         }
436       }
437     }
438 
439     // XXX - Do these do anything? Vector constants turn into build_vector.
440     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
441     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
442 
443     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
444     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
445     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
446     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
447 
448     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
449     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
450     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
451     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
452 
453     setOperationAction(ISD::AND, MVT::v2i16, Promote);
454     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
455     setOperationAction(ISD::OR, MVT::v2i16, Promote);
456     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
457     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
458     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
459     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
460     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
461     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
462     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
463 
464     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
465     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
466     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
467     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
468     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
469     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
470     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
471     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
472     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
473     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
474 
475     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
476     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
477     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
478     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
479     setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
480     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
481 
482     // This isn't really legal, but this avoids the legalizer unrolling it (and
483     // allows matching fneg (fabs x) patterns)
484     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
485 
486     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
487     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
488 
489     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
490     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
491     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
492     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
493   } else {
494     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
495     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
496   }
497 
498   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
499     setOperationAction(ISD::SELECT, VT, Custom);
500   }
501 
502   setTargetDAGCombine(ISD::ADD);
503   setTargetDAGCombine(ISD::ADDCARRY);
504   setTargetDAGCombine(ISD::SUB);
505   setTargetDAGCombine(ISD::SUBCARRY);
506   setTargetDAGCombine(ISD::FADD);
507   setTargetDAGCombine(ISD::FSUB);
508   setTargetDAGCombine(ISD::FMINNUM);
509   setTargetDAGCombine(ISD::FMAXNUM);
510   setTargetDAGCombine(ISD::SMIN);
511   setTargetDAGCombine(ISD::SMAX);
512   setTargetDAGCombine(ISD::UMIN);
513   setTargetDAGCombine(ISD::UMAX);
514   setTargetDAGCombine(ISD::SETCC);
515   setTargetDAGCombine(ISD::AND);
516   setTargetDAGCombine(ISD::OR);
517   setTargetDAGCombine(ISD::XOR);
518   setTargetDAGCombine(ISD::SINT_TO_FP);
519   setTargetDAGCombine(ISD::UINT_TO_FP);
520   setTargetDAGCombine(ISD::FCANONICALIZE);
521   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
522   setTargetDAGCombine(ISD::ZERO_EXTEND);
523   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
524   setTargetDAGCombine(ISD::BUILD_VECTOR);
525 
526   // All memory operations. Some folding on the pointer operand is done to help
527   // matching the constant offsets in the addressing modes.
528   setTargetDAGCombine(ISD::LOAD);
529   setTargetDAGCombine(ISD::STORE);
530   setTargetDAGCombine(ISD::ATOMIC_LOAD);
531   setTargetDAGCombine(ISD::ATOMIC_STORE);
532   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
533   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
534   setTargetDAGCombine(ISD::ATOMIC_SWAP);
535   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
536   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
537   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
538   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
539   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
540   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
541   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
542   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
543   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
544   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
545 
546   setSchedulingPreference(Sched::RegPressure);
547 }
548 
549 const SISubtarget *SITargetLowering::getSubtarget() const {
550   return static_cast<const SISubtarget *>(Subtarget);
551 }
552 
553 //===----------------------------------------------------------------------===//
554 // TargetLowering queries
555 //===----------------------------------------------------------------------===//
556 
557 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
558   // SI has some legal vector types, but no legal vector operations. Say no
559   // shuffles are legal in order to prefer scalarizing some vector operations.
560   return false;
561 }
562 
563 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
564                                           const CallInst &CI,
565                                           MachineFunction &MF,
566                                           unsigned IntrID) const {
567   switch (IntrID) {
568   case Intrinsic::amdgcn_atomic_inc:
569   case Intrinsic::amdgcn_atomic_dec:
570   case Intrinsic::amdgcn_ds_fadd:
571   case Intrinsic::amdgcn_ds_fmin:
572   case Intrinsic::amdgcn_ds_fmax: {
573     Info.opc = ISD::INTRINSIC_W_CHAIN;
574     Info.memVT = MVT::getVT(CI.getType());
575     Info.ptrVal = CI.getOperand(0);
576     Info.align = 0;
577     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
578 
579     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
580     if (!Vol || !Vol->isZero())
581       Info.flags |= MachineMemOperand::MOVolatile;
582 
583     return true;
584   }
585 
586   // Image load.
587   case Intrinsic::amdgcn_image_load:
588   case Intrinsic::amdgcn_image_load_mip:
589 
590   // Sample.
591   case Intrinsic::amdgcn_image_sample:
592   case Intrinsic::amdgcn_image_sample_cl:
593   case Intrinsic::amdgcn_image_sample_d:
594   case Intrinsic::amdgcn_image_sample_d_cl:
595   case Intrinsic::amdgcn_image_sample_l:
596   case Intrinsic::amdgcn_image_sample_b:
597   case Intrinsic::amdgcn_image_sample_b_cl:
598   case Intrinsic::amdgcn_image_sample_lz:
599   case Intrinsic::amdgcn_image_sample_cd:
600   case Intrinsic::amdgcn_image_sample_cd_cl:
601 
602     // Sample with comparison.
603   case Intrinsic::amdgcn_image_sample_c:
604   case Intrinsic::amdgcn_image_sample_c_cl:
605   case Intrinsic::amdgcn_image_sample_c_d:
606   case Intrinsic::amdgcn_image_sample_c_d_cl:
607   case Intrinsic::amdgcn_image_sample_c_l:
608   case Intrinsic::amdgcn_image_sample_c_b:
609   case Intrinsic::amdgcn_image_sample_c_b_cl:
610   case Intrinsic::amdgcn_image_sample_c_lz:
611   case Intrinsic::amdgcn_image_sample_c_cd:
612   case Intrinsic::amdgcn_image_sample_c_cd_cl:
613 
614     // Sample with offsets.
615   case Intrinsic::amdgcn_image_sample_o:
616   case Intrinsic::amdgcn_image_sample_cl_o:
617   case Intrinsic::amdgcn_image_sample_d_o:
618   case Intrinsic::amdgcn_image_sample_d_cl_o:
619   case Intrinsic::amdgcn_image_sample_l_o:
620   case Intrinsic::amdgcn_image_sample_b_o:
621   case Intrinsic::amdgcn_image_sample_b_cl_o:
622   case Intrinsic::amdgcn_image_sample_lz_o:
623   case Intrinsic::amdgcn_image_sample_cd_o:
624   case Intrinsic::amdgcn_image_sample_cd_cl_o:
625 
626     // Sample with comparison and offsets.
627   case Intrinsic::amdgcn_image_sample_c_o:
628   case Intrinsic::amdgcn_image_sample_c_cl_o:
629   case Intrinsic::amdgcn_image_sample_c_d_o:
630   case Intrinsic::amdgcn_image_sample_c_d_cl_o:
631   case Intrinsic::amdgcn_image_sample_c_l_o:
632   case Intrinsic::amdgcn_image_sample_c_b_o:
633   case Intrinsic::amdgcn_image_sample_c_b_cl_o:
634   case Intrinsic::amdgcn_image_sample_c_lz_o:
635   case Intrinsic::amdgcn_image_sample_c_cd_o:
636   case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
637 
638     // Basic gather4
639   case Intrinsic::amdgcn_image_gather4:
640   case Intrinsic::amdgcn_image_gather4_cl:
641   case Intrinsic::amdgcn_image_gather4_l:
642   case Intrinsic::amdgcn_image_gather4_b:
643   case Intrinsic::amdgcn_image_gather4_b_cl:
644   case Intrinsic::amdgcn_image_gather4_lz:
645 
646     // Gather4 with comparison
647   case Intrinsic::amdgcn_image_gather4_c:
648   case Intrinsic::amdgcn_image_gather4_c_cl:
649   case Intrinsic::amdgcn_image_gather4_c_l:
650   case Intrinsic::amdgcn_image_gather4_c_b:
651   case Intrinsic::amdgcn_image_gather4_c_b_cl:
652   case Intrinsic::amdgcn_image_gather4_c_lz:
653 
654     // Gather4 with offsets
655   case Intrinsic::amdgcn_image_gather4_o:
656   case Intrinsic::amdgcn_image_gather4_cl_o:
657   case Intrinsic::amdgcn_image_gather4_l_o:
658   case Intrinsic::amdgcn_image_gather4_b_o:
659   case Intrinsic::amdgcn_image_gather4_b_cl_o:
660   case Intrinsic::amdgcn_image_gather4_lz_o:
661 
662     // Gather4 with comparison and offsets
663   case Intrinsic::amdgcn_image_gather4_c_o:
664   case Intrinsic::amdgcn_image_gather4_c_cl_o:
665   case Intrinsic::amdgcn_image_gather4_c_l_o:
666   case Intrinsic::amdgcn_image_gather4_c_b_o:
667   case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
668   case Intrinsic::amdgcn_image_gather4_c_lz_o: {
669     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
670     Info.opc = ISD::INTRINSIC_W_CHAIN;
671     Info.memVT = MVT::getVT(CI.getType());
672     Info.ptrVal = MFI->getImagePSV(
673       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
674       CI.getArgOperand(1));
675     Info.align = 0;
676     Info.flags = MachineMemOperand::MOLoad |
677                  MachineMemOperand::MODereferenceable;
678     return true;
679   }
680   case Intrinsic::amdgcn_image_store:
681   case Intrinsic::amdgcn_image_store_mip: {
682     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
683     Info.opc = ISD::INTRINSIC_VOID;
684     Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
685     Info.ptrVal = MFI->getImagePSV(
686       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
687       CI.getArgOperand(2));
688     Info.flags = MachineMemOperand::MOStore |
689                  MachineMemOperand::MODereferenceable;
690     Info.align = 0;
691     return true;
692   }
693   case Intrinsic::amdgcn_image_atomic_swap:
694   case Intrinsic::amdgcn_image_atomic_add:
695   case Intrinsic::amdgcn_image_atomic_sub:
696   case Intrinsic::amdgcn_image_atomic_smin:
697   case Intrinsic::amdgcn_image_atomic_umin:
698   case Intrinsic::amdgcn_image_atomic_smax:
699   case Intrinsic::amdgcn_image_atomic_umax:
700   case Intrinsic::amdgcn_image_atomic_and:
701   case Intrinsic::amdgcn_image_atomic_or:
702   case Intrinsic::amdgcn_image_atomic_xor:
703   case Intrinsic::amdgcn_image_atomic_inc:
704   case Intrinsic::amdgcn_image_atomic_dec: {
705     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
706     Info.opc = ISD::INTRINSIC_W_CHAIN;
707     Info.memVT = MVT::getVT(CI.getType());
708     Info.ptrVal = MFI->getImagePSV(
709       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
710       CI.getArgOperand(2));
711 
712     Info.flags = MachineMemOperand::MOLoad |
713                  MachineMemOperand::MOStore |
714                  MachineMemOperand::MODereferenceable;
715 
716     // XXX - Should this be volatile without known ordering?
717     Info.flags |= MachineMemOperand::MOVolatile;
718     return true;
719   }
720   case Intrinsic::amdgcn_image_atomic_cmpswap: {
721     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
722     Info.opc = ISD::INTRINSIC_W_CHAIN;
723     Info.memVT = MVT::getVT(CI.getType());
724     Info.ptrVal = MFI->getImagePSV(
725       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
726       CI.getArgOperand(3));
727 
728     Info.flags = MachineMemOperand::MOLoad |
729                  MachineMemOperand::MOStore |
730                  MachineMemOperand::MODereferenceable;
731 
732     // XXX - Should this be volatile without known ordering?
733     Info.flags |= MachineMemOperand::MOVolatile;
734     return true;
735   }
736   case Intrinsic::amdgcn_tbuffer_load:
737   case Intrinsic::amdgcn_buffer_load:
738   case Intrinsic::amdgcn_buffer_load_format: {
739     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
740     Info.opc = ISD::INTRINSIC_W_CHAIN;
741     Info.ptrVal = MFI->getBufferPSV(
742       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
743       CI.getArgOperand(0));
744     Info.memVT = MVT::getVT(CI.getType());
745     Info.flags = MachineMemOperand::MOLoad |
746                  MachineMemOperand::MODereferenceable;
747 
748     // There is a constant offset component, but there are additional register
749     // offsets which could break AA if we set the offset to anything non-0.
750     return true;
751   }
752   case Intrinsic::amdgcn_tbuffer_store:
753   case Intrinsic::amdgcn_buffer_store:
754   case Intrinsic::amdgcn_buffer_store_format: {
755     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
756     Info.opc = ISD::INTRINSIC_VOID;
757     Info.ptrVal = MFI->getBufferPSV(
758       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
759       CI.getArgOperand(1));
760     Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
761     Info.flags = MachineMemOperand::MOStore |
762                  MachineMemOperand::MODereferenceable;
763     return true;
764   }
765   case Intrinsic::amdgcn_buffer_atomic_swap:
766   case Intrinsic::amdgcn_buffer_atomic_add:
767   case Intrinsic::amdgcn_buffer_atomic_sub:
768   case Intrinsic::amdgcn_buffer_atomic_smin:
769   case Intrinsic::amdgcn_buffer_atomic_umin:
770   case Intrinsic::amdgcn_buffer_atomic_smax:
771   case Intrinsic::amdgcn_buffer_atomic_umax:
772   case Intrinsic::amdgcn_buffer_atomic_and:
773   case Intrinsic::amdgcn_buffer_atomic_or:
774   case Intrinsic::amdgcn_buffer_atomic_xor: {
775     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
776     Info.opc = ISD::INTRINSIC_W_CHAIN;
777     Info.ptrVal = MFI->getBufferPSV(
778       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
779       CI.getArgOperand(1));
780     Info.memVT = MVT::getVT(CI.getType());
781     Info.flags = MachineMemOperand::MOLoad |
782                  MachineMemOperand::MOStore |
783                  MachineMemOperand::MODereferenceable |
784                  MachineMemOperand::MOVolatile;
785     return true;
786   }
787   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
788     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
789     Info.opc = ISD::INTRINSIC_W_CHAIN;
790     Info.ptrVal = MFI->getBufferPSV(
791       *MF.getSubtarget<SISubtarget>().getInstrInfo(),
792       CI.getArgOperand(2));
793     Info.memVT = MVT::getVT(CI.getType());
794     Info.flags = MachineMemOperand::MOLoad |
795                  MachineMemOperand::MOStore |
796                  MachineMemOperand::MODereferenceable |
797                  MachineMemOperand::MOVolatile;
798     return true;
799   }
800   default:
801     return false;
802   }
803 }
804 
805 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
806                                             SmallVectorImpl<Value*> &Ops,
807                                             Type *&AccessTy) const {
808   switch (II->getIntrinsicID()) {
809   case Intrinsic::amdgcn_atomic_inc:
810   case Intrinsic::amdgcn_atomic_dec:
811   case Intrinsic::amdgcn_ds_fadd:
812   case Intrinsic::amdgcn_ds_fmin:
813   case Intrinsic::amdgcn_ds_fmax: {
814     Value *Ptr = II->getArgOperand(0);
815     AccessTy = II->getType();
816     Ops.push_back(Ptr);
817     return true;
818   }
819   default:
820     return false;
821   }
822 }
823 
824 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
825   if (!Subtarget->hasFlatInstOffsets()) {
826     // Flat instructions do not have offsets, and only have the register
827     // address.
828     return AM.BaseOffs == 0 && AM.Scale == 0;
829   }
830 
831   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
832   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
833 
834   // Just r + i
835   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
836 }
837 
838 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
839   if (Subtarget->hasFlatGlobalInsts())
840     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
841 
842   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
843       // Assume the we will use FLAT for all global memory accesses
844       // on VI.
845       // FIXME: This assumption is currently wrong.  On VI we still use
846       // MUBUF instructions for the r + i addressing mode.  As currently
847       // implemented, the MUBUF instructions only work on buffer < 4GB.
848       // It may be possible to support > 4GB buffers with MUBUF instructions,
849       // by setting the stride value in the resource descriptor which would
850       // increase the size limit to (stride * 4GB).  However, this is risky,
851       // because it has never been validated.
852     return isLegalFlatAddressingMode(AM);
853   }
854 
855   return isLegalMUBUFAddressingMode(AM);
856 }
857 
858 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
859   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
860   // additionally can do r + r + i with addr64. 32-bit has more addressing
861   // mode options. Depending on the resource constant, it can also do
862   // (i64 r0) + (i32 r1) * (i14 i).
863   //
864   // Private arrays end up using a scratch buffer most of the time, so also
865   // assume those use MUBUF instructions. Scratch loads / stores are currently
866   // implemented as mubuf instructions with offen bit set, so slightly
867   // different than the normal addr64.
868   if (!isUInt<12>(AM.BaseOffs))
869     return false;
870 
871   // FIXME: Since we can split immediate into soffset and immediate offset,
872   // would it make sense to allow any immediate?
873 
874   switch (AM.Scale) {
875   case 0: // r + i or just i, depending on HasBaseReg.
876     return true;
877   case 1:
878     return true; // We have r + r or r + i.
879   case 2:
880     if (AM.HasBaseReg) {
881       // Reject 2 * r + r.
882       return false;
883     }
884 
885     // Allow 2 * r as r + r
886     // Or  2 * r + i is allowed as r + r + i.
887     return true;
888   default: // Don't allow n * r
889     return false;
890   }
891 }
892 
893 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
894                                              const AddrMode &AM, Type *Ty,
895                                              unsigned AS, Instruction *I) const {
896   // No global is ever allowed as a base.
897   if (AM.BaseGV)
898     return false;
899 
900   if (AS == AMDGPUASI.GLOBAL_ADDRESS)
901     return isLegalGlobalAddressingMode(AM);
902 
903   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
904       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
905     // If the offset isn't a multiple of 4, it probably isn't going to be
906     // correctly aligned.
907     // FIXME: Can we get the real alignment here?
908     if (AM.BaseOffs % 4 != 0)
909       return isLegalMUBUFAddressingMode(AM);
910 
911     // There are no SMRD extloads, so if we have to do a small type access we
912     // will use a MUBUF load.
913     // FIXME?: We also need to do this if unaligned, but we don't know the
914     // alignment here.
915     if (DL.getTypeStoreSize(Ty) < 4)
916       return isLegalGlobalAddressingMode(AM);
917 
918     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
919       // SMRD instructions have an 8-bit, dword offset on SI.
920       if (!isUInt<8>(AM.BaseOffs / 4))
921         return false;
922     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
923       // On CI+, this can also be a 32-bit literal constant offset. If it fits
924       // in 8-bits, it can use a smaller encoding.
925       if (!isUInt<32>(AM.BaseOffs / 4))
926         return false;
927     } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
928       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
929       if (!isUInt<20>(AM.BaseOffs))
930         return false;
931     } else
932       llvm_unreachable("unhandled generation");
933 
934     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
935       return true;
936 
937     if (AM.Scale == 1 && AM.HasBaseReg)
938       return true;
939 
940     return false;
941 
942   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
943     return isLegalMUBUFAddressingMode(AM);
944   } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
945              AS == AMDGPUASI.REGION_ADDRESS) {
946     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
947     // field.
948     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
949     // an 8-bit dword offset but we don't know the alignment here.
950     if (!isUInt<16>(AM.BaseOffs))
951       return false;
952 
953     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
954       return true;
955 
956     if (AM.Scale == 1 && AM.HasBaseReg)
957       return true;
958 
959     return false;
960   } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
961              AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
962     // For an unknown address space, this usually means that this is for some
963     // reason being used for pure arithmetic, and not based on some addressing
964     // computation. We don't have instructions that compute pointers with any
965     // addressing modes, so treat them as having no offset like flat
966     // instructions.
967     return isLegalFlatAddressingMode(AM);
968   } else {
969     llvm_unreachable("unhandled address space");
970   }
971 }
972 
973 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
974                                         const SelectionDAG &DAG) const {
975   if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
976     return (MemVT.getSizeInBits() <= 4 * 32);
977   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
978     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
979     return (MemVT.getSizeInBits() <= MaxPrivateBits);
980   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
981     return (MemVT.getSizeInBits() <= 2 * 32);
982   }
983   return true;
984 }
985 
986 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
987                                                       unsigned AddrSpace,
988                                                       unsigned Align,
989                                                       bool *IsFast) const {
990   if (IsFast)
991     *IsFast = false;
992 
993   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
994   // which isn't a simple VT.
995   // Until MVT is extended to handle this, simply check for the size and
996   // rely on the condition below: allow accesses if the size is a multiple of 4.
997   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
998                            VT.getStoreSize() > 16)) {
999     return false;
1000   }
1001 
1002   if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
1003       AddrSpace == AMDGPUASI.REGION_ADDRESS) {
1004     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1005     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1006     // with adjacent offsets.
1007     bool AlignedBy4 = (Align % 4 == 0);
1008     if (IsFast)
1009       *IsFast = AlignedBy4;
1010 
1011     return AlignedBy4;
1012   }
1013 
1014   // FIXME: We have to be conservative here and assume that flat operations
1015   // will access scratch.  If we had access to the IR function, then we
1016   // could determine if any private memory was used in the function.
1017   if (!Subtarget->hasUnalignedScratchAccess() &&
1018       (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
1019        AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
1020     return false;
1021   }
1022 
1023   if (Subtarget->hasUnalignedBufferAccess()) {
1024     // If we have an uniform constant load, it still requires using a slow
1025     // buffer instruction if unaligned.
1026     if (IsFast) {
1027       *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
1028                  AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
1029         (Align % 4 == 0) : true;
1030     }
1031 
1032     return true;
1033   }
1034 
1035   // Smaller than dword value must be aligned.
1036   if (VT.bitsLT(MVT::i32))
1037     return false;
1038 
1039   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1040   // byte-address are ignored, thus forcing Dword alignment.
1041   // This applies to private, global, and constant memory.
1042   if (IsFast)
1043     *IsFast = true;
1044 
1045   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1046 }
1047 
1048 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
1049                                           unsigned SrcAlign, bool IsMemset,
1050                                           bool ZeroMemset,
1051                                           bool MemcpyStrSrc,
1052                                           MachineFunction &MF) const {
1053   // FIXME: Should account for address space here.
1054 
1055   // The default fallback uses the private pointer size as a guess for a type to
1056   // use. Make sure we switch these to 64-bit accesses.
1057 
1058   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1059     return MVT::v4i32;
1060 
1061   if (Size >= 8 && DstAlign >= 4)
1062     return MVT::v2i32;
1063 
1064   // Use the default.
1065   return MVT::Other;
1066 }
1067 
1068 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
1069   return AS == AMDGPUASI.GLOBAL_ADDRESS ||
1070          AS == AMDGPUASI.FLAT_ADDRESS ||
1071          AS == AMDGPUASI.CONSTANT_ADDRESS ||
1072          AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
1073 }
1074 
1075 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1076                                            unsigned DestAS) const {
1077   return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
1078          isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
1079 }
1080 
1081 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1082   const MemSDNode *MemNode = cast<MemSDNode>(N);
1083   const Value *Ptr = MemNode->getMemOperand()->getValue();
1084   const Instruction *I = dyn_cast<Instruction>(Ptr);
1085   return I && I->getMetadata("amdgpu.noclobber");
1086 }
1087 
1088 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1089                                             unsigned DestAS) const {
1090   // Flat -> private/local is a simple truncate.
1091   // Flat -> global is no-op
1092   if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1093     return true;
1094 
1095   return isNoopAddrSpaceCast(SrcAS, DestAS);
1096 }
1097 
1098 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1099   const MemSDNode *MemNode = cast<MemSDNode>(N);
1100 
1101   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1102 }
1103 
1104 TargetLoweringBase::LegalizeTypeAction
1105 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1106   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1107     return TypeSplitVector;
1108 
1109   return TargetLoweringBase::getPreferredVectorAction(VT);
1110 }
1111 
1112 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1113                                                          Type *Ty) const {
1114   // FIXME: Could be smarter if called for vector constants.
1115   return true;
1116 }
1117 
1118 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1119   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1120     switch (Op) {
1121     case ISD::LOAD:
1122     case ISD::STORE:
1123 
1124     // These operations are done with 32-bit instructions anyway.
1125     case ISD::AND:
1126     case ISD::OR:
1127     case ISD::XOR:
1128     case ISD::SELECT:
1129       // TODO: Extensions?
1130       return true;
1131     default:
1132       return false;
1133     }
1134   }
1135 
1136   // SimplifySetCC uses this function to determine whether or not it should
1137   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1138   if (VT == MVT::i1 && Op == ISD::SETCC)
1139     return false;
1140 
1141   return TargetLowering::isTypeDesirableForOp(Op, VT);
1142 }
1143 
1144 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1145                                                    const SDLoc &SL,
1146                                                    SDValue Chain,
1147                                                    uint64_t Offset) const {
1148   const DataLayout &DL = DAG.getDataLayout();
1149   MachineFunction &MF = DAG.getMachineFunction();
1150   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1151 
1152   const ArgDescriptor *InputPtrReg;
1153   const TargetRegisterClass *RC;
1154 
1155   std::tie(InputPtrReg, RC)
1156     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1157 
1158   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1159   MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1160   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1161     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1162 
1163   return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
1164                      DAG.getConstant(Offset, SL, PtrVT));
1165 }
1166 
1167 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1168                                             const SDLoc &SL) const {
1169   auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
1170   uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
1171   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1172 }
1173 
1174 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1175                                          const SDLoc &SL, SDValue Val,
1176                                          bool Signed,
1177                                          const ISD::InputArg *Arg) const {
1178   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1179       VT.bitsLT(MemVT)) {
1180     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1181     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1182   }
1183 
1184   if (MemVT.isFloatingPoint())
1185     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1186   else if (Signed)
1187     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1188   else
1189     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1190 
1191   return Val;
1192 }
1193 
1194 SDValue SITargetLowering::lowerKernargMemParameter(
1195   SelectionDAG &DAG, EVT VT, EVT MemVT,
1196   const SDLoc &SL, SDValue Chain,
1197   uint64_t Offset, bool Signed,
1198   const ISD::InputArg *Arg) const {
1199   const DataLayout &DL = DAG.getDataLayout();
1200   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1201   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1202   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1203 
1204   unsigned Align = DL.getABITypeAlignment(Ty);
1205 
1206   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1207   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1208                              MachineMemOperand::MONonTemporal |
1209                              MachineMemOperand::MODereferenceable |
1210                              MachineMemOperand::MOInvariant);
1211 
1212   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1213   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1214 }
1215 
1216 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1217                                               const SDLoc &SL, SDValue Chain,
1218                                               const ISD::InputArg &Arg) const {
1219   MachineFunction &MF = DAG.getMachineFunction();
1220   MachineFrameInfo &MFI = MF.getFrameInfo();
1221 
1222   if (Arg.Flags.isByVal()) {
1223     unsigned Size = Arg.Flags.getByValSize();
1224     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1225     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1226   }
1227 
1228   unsigned ArgOffset = VA.getLocMemOffset();
1229   unsigned ArgSize = VA.getValVT().getStoreSize();
1230 
1231   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1232 
1233   // Create load nodes to retrieve arguments from the stack.
1234   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1235   SDValue ArgValue;
1236 
1237   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1238   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1239   MVT MemVT = VA.getValVT();
1240 
1241   switch (VA.getLocInfo()) {
1242   default:
1243     break;
1244   case CCValAssign::BCvt:
1245     MemVT = VA.getLocVT();
1246     break;
1247   case CCValAssign::SExt:
1248     ExtType = ISD::SEXTLOAD;
1249     break;
1250   case CCValAssign::ZExt:
1251     ExtType = ISD::ZEXTLOAD;
1252     break;
1253   case CCValAssign::AExt:
1254     ExtType = ISD::EXTLOAD;
1255     break;
1256   }
1257 
1258   ArgValue = DAG.getExtLoad(
1259     ExtType, SL, VA.getLocVT(), Chain, FIN,
1260     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1261     MemVT);
1262   return ArgValue;
1263 }
1264 
1265 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1266   const SIMachineFunctionInfo &MFI,
1267   EVT VT,
1268   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1269   const ArgDescriptor *Reg;
1270   const TargetRegisterClass *RC;
1271 
1272   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1273   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1274 }
1275 
1276 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1277                                    CallingConv::ID CallConv,
1278                                    ArrayRef<ISD::InputArg> Ins,
1279                                    BitVector &Skipped,
1280                                    FunctionType *FType,
1281                                    SIMachineFunctionInfo *Info) {
1282   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1283     const ISD::InputArg &Arg = Ins[I];
1284 
1285     // First check if it's a PS input addr.
1286     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1287         !Arg.Flags.isByVal() && PSInputNum <= 15) {
1288 
1289       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1290         // We can safely skip PS inputs.
1291         Skipped.set(I);
1292         ++PSInputNum;
1293         continue;
1294       }
1295 
1296       Info->markPSInputAllocated(PSInputNum);
1297       if (Arg.Used)
1298         Info->markPSInputEnabled(PSInputNum);
1299 
1300       ++PSInputNum;
1301     }
1302 
1303     // Second split vertices into their elements.
1304     if (Arg.VT.isVector()) {
1305       ISD::InputArg NewArg = Arg;
1306       NewArg.Flags.setSplit();
1307       NewArg.VT = Arg.VT.getVectorElementType();
1308 
1309       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1310       // three or five element vertex only needs three or five registers,
1311       // NOT four or eight.
1312       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1313       unsigned NumElements = ParamType->getVectorNumElements();
1314 
1315       for (unsigned J = 0; J != NumElements; ++J) {
1316         Splits.push_back(NewArg);
1317         NewArg.PartOffset += NewArg.VT.getStoreSize();
1318       }
1319     } else {
1320       Splits.push_back(Arg);
1321     }
1322   }
1323 }
1324 
1325 // Allocate special inputs passed in VGPRs.
1326 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1327                                            MachineFunction &MF,
1328                                            const SIRegisterInfo &TRI,
1329                                            SIMachineFunctionInfo &Info) {
1330   if (Info.hasWorkItemIDX()) {
1331     unsigned Reg = AMDGPU::VGPR0;
1332     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1333 
1334     CCInfo.AllocateReg(Reg);
1335     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1336   }
1337 
1338   if (Info.hasWorkItemIDY()) {
1339     unsigned Reg = AMDGPU::VGPR1;
1340     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1341 
1342     CCInfo.AllocateReg(Reg);
1343     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1344   }
1345 
1346   if (Info.hasWorkItemIDZ()) {
1347     unsigned Reg = AMDGPU::VGPR2;
1348     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1349 
1350     CCInfo.AllocateReg(Reg);
1351     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1352   }
1353 }
1354 
1355 // Try to allocate a VGPR at the end of the argument list, or if no argument
1356 // VGPRs are left allocating a stack slot.
1357 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1358   ArrayRef<MCPhysReg> ArgVGPRs
1359     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1360   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1361   if (RegIdx == ArgVGPRs.size()) {
1362     // Spill to stack required.
1363     int64_t Offset = CCInfo.AllocateStack(4, 4);
1364 
1365     return ArgDescriptor::createStack(Offset);
1366   }
1367 
1368   unsigned Reg = ArgVGPRs[RegIdx];
1369   Reg = CCInfo.AllocateReg(Reg);
1370   assert(Reg != AMDGPU::NoRegister);
1371 
1372   MachineFunction &MF = CCInfo.getMachineFunction();
1373   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1374   return ArgDescriptor::createRegister(Reg);
1375 }
1376 
1377 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1378                                              const TargetRegisterClass *RC,
1379                                              unsigned NumArgRegs) {
1380   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1381   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1382   if (RegIdx == ArgSGPRs.size())
1383     report_fatal_error("ran out of SGPRs for arguments");
1384 
1385   unsigned Reg = ArgSGPRs[RegIdx];
1386   Reg = CCInfo.AllocateReg(Reg);
1387   assert(Reg != AMDGPU::NoRegister);
1388 
1389   MachineFunction &MF = CCInfo.getMachineFunction();
1390   MF.addLiveIn(Reg, RC);
1391   return ArgDescriptor::createRegister(Reg);
1392 }
1393 
1394 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1395   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1396 }
1397 
1398 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1399   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1400 }
1401 
1402 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1403                                       MachineFunction &MF,
1404                                       const SIRegisterInfo &TRI,
1405                                       SIMachineFunctionInfo &Info) {
1406   if (Info.hasWorkItemIDX())
1407     Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1408 
1409   if (Info.hasWorkItemIDY())
1410     Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1411 
1412   if (Info.hasWorkItemIDZ())
1413     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1414 }
1415 
1416 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1417                                       MachineFunction &MF,
1418                                       const SIRegisterInfo &TRI,
1419                                       SIMachineFunctionInfo &Info) {
1420   auto &ArgInfo = Info.getArgInfo();
1421 
1422   // TODO: Unify handling with private memory pointers.
1423 
1424   if (Info.hasDispatchPtr())
1425     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1426 
1427   if (Info.hasQueuePtr())
1428     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1429 
1430   if (Info.hasKernargSegmentPtr())
1431     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1432 
1433   if (Info.hasDispatchID())
1434     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1435 
1436   // flat_scratch_init is not applicable for non-kernel functions.
1437 
1438   if (Info.hasWorkGroupIDX())
1439     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1440 
1441   if (Info.hasWorkGroupIDY())
1442     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1443 
1444   if (Info.hasWorkGroupIDZ())
1445     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1446 
1447   if (Info.hasImplicitArgPtr())
1448     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1449 }
1450 
1451 // Allocate special inputs passed in user SGPRs.
1452 static void allocateHSAUserSGPRs(CCState &CCInfo,
1453                                  MachineFunction &MF,
1454                                  const SIRegisterInfo &TRI,
1455                                  SIMachineFunctionInfo &Info) {
1456   if (Info.hasImplicitBufferPtr()) {
1457     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1458     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1459     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1460   }
1461 
1462   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1463   if (Info.hasPrivateSegmentBuffer()) {
1464     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1465     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1466     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1467   }
1468 
1469   if (Info.hasDispatchPtr()) {
1470     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1471     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1472     CCInfo.AllocateReg(DispatchPtrReg);
1473   }
1474 
1475   if (Info.hasQueuePtr()) {
1476     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1477     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1478     CCInfo.AllocateReg(QueuePtrReg);
1479   }
1480 
1481   if (Info.hasKernargSegmentPtr()) {
1482     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1483     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1484     CCInfo.AllocateReg(InputPtrReg);
1485   }
1486 
1487   if (Info.hasDispatchID()) {
1488     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1489     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1490     CCInfo.AllocateReg(DispatchIDReg);
1491   }
1492 
1493   if (Info.hasFlatScratchInit()) {
1494     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1495     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1496     CCInfo.AllocateReg(FlatScratchInitReg);
1497   }
1498 
1499   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1500   // these from the dispatch pointer.
1501 }
1502 
1503 // Allocate special input registers that are initialized per-wave.
1504 static void allocateSystemSGPRs(CCState &CCInfo,
1505                                 MachineFunction &MF,
1506                                 SIMachineFunctionInfo &Info,
1507                                 CallingConv::ID CallConv,
1508                                 bool IsShader) {
1509   if (Info.hasWorkGroupIDX()) {
1510     unsigned Reg = Info.addWorkGroupIDX();
1511     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1512     CCInfo.AllocateReg(Reg);
1513   }
1514 
1515   if (Info.hasWorkGroupIDY()) {
1516     unsigned Reg = Info.addWorkGroupIDY();
1517     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1518     CCInfo.AllocateReg(Reg);
1519   }
1520 
1521   if (Info.hasWorkGroupIDZ()) {
1522     unsigned Reg = Info.addWorkGroupIDZ();
1523     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1524     CCInfo.AllocateReg(Reg);
1525   }
1526 
1527   if (Info.hasWorkGroupInfo()) {
1528     unsigned Reg = Info.addWorkGroupInfo();
1529     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1530     CCInfo.AllocateReg(Reg);
1531   }
1532 
1533   if (Info.hasPrivateSegmentWaveByteOffset()) {
1534     // Scratch wave offset passed in system SGPR.
1535     unsigned PrivateSegmentWaveByteOffsetReg;
1536 
1537     if (IsShader) {
1538       PrivateSegmentWaveByteOffsetReg =
1539         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1540 
1541       // This is true if the scratch wave byte offset doesn't have a fixed
1542       // location.
1543       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1544         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1545         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1546       }
1547     } else
1548       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1549 
1550     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1551     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1552   }
1553 }
1554 
1555 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1556                                      MachineFunction &MF,
1557                                      const SIRegisterInfo &TRI,
1558                                      SIMachineFunctionInfo &Info) {
1559   // Now that we've figured out where the scratch register inputs are, see if
1560   // should reserve the arguments and use them directly.
1561   MachineFrameInfo &MFI = MF.getFrameInfo();
1562   bool HasStackObjects = MFI.hasStackObjects();
1563 
1564   // Record that we know we have non-spill stack objects so we don't need to
1565   // check all stack objects later.
1566   if (HasStackObjects)
1567     Info.setHasNonSpillStackObjects(true);
1568 
1569   // Everything live out of a block is spilled with fast regalloc, so it's
1570   // almost certain that spilling will be required.
1571   if (TM.getOptLevel() == CodeGenOpt::None)
1572     HasStackObjects = true;
1573 
1574   // For now assume stack access is needed in any callee functions, so we need
1575   // the scratch registers to pass in.
1576   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1577 
1578   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1579   if (ST.isAmdCodeObjectV2(MF)) {
1580     if (RequiresStackAccess) {
1581       // If we have stack objects, we unquestionably need the private buffer
1582       // resource. For the Code Object V2 ABI, this will be the first 4 user
1583       // SGPR inputs. We can reserve those and use them directly.
1584 
1585       unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1586         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1587       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1588 
1589       if (MFI.hasCalls()) {
1590         // If we have calls, we need to keep the frame register in a register
1591         // that won't be clobbered by a call, so ensure it is copied somewhere.
1592 
1593         // This is not a problem for the scratch wave offset, because the same
1594         // registers are reserved in all functions.
1595 
1596         // FIXME: Nothing is really ensuring this is a call preserved register,
1597         // it's just selected from the end so it happens to be.
1598         unsigned ReservedOffsetReg
1599           = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1600         Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1601       } else {
1602         unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1603           AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1604         Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1605       }
1606     } else {
1607       unsigned ReservedBufferReg
1608         = TRI.reservedPrivateSegmentBufferReg(MF);
1609       unsigned ReservedOffsetReg
1610         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1611 
1612       // We tentatively reserve the last registers (skipping the last two
1613       // which may contain VCC). After register allocation, we'll replace
1614       // these with the ones immediately after those which were really
1615       // allocated. In the prologue copies will be inserted from the argument
1616       // to these reserved registers.
1617       Info.setScratchRSrcReg(ReservedBufferReg);
1618       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1619     }
1620   } else {
1621     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1622 
1623     // Without HSA, relocations are used for the scratch pointer and the
1624     // buffer resource setup is always inserted in the prologue. Scratch wave
1625     // offset is still in an input SGPR.
1626     Info.setScratchRSrcReg(ReservedBufferReg);
1627 
1628     if (HasStackObjects && !MFI.hasCalls()) {
1629       unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1630         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1631       Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1632     } else {
1633       unsigned ReservedOffsetReg
1634         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1635       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1636     }
1637   }
1638 }
1639 
1640 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1641   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1642   return !Info->isEntryFunction();
1643 }
1644 
1645 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1646 
1647 }
1648 
1649 void SITargetLowering::insertCopiesSplitCSR(
1650   MachineBasicBlock *Entry,
1651   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1652   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1653 
1654   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1655   if (!IStart)
1656     return;
1657 
1658   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1659   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1660   MachineBasicBlock::iterator MBBI = Entry->begin();
1661   for (const MCPhysReg *I = IStart; *I; ++I) {
1662     const TargetRegisterClass *RC = nullptr;
1663     if (AMDGPU::SReg_64RegClass.contains(*I))
1664       RC = &AMDGPU::SGPR_64RegClass;
1665     else if (AMDGPU::SReg_32RegClass.contains(*I))
1666       RC = &AMDGPU::SGPR_32RegClass;
1667     else
1668       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1669 
1670     unsigned NewVR = MRI->createVirtualRegister(RC);
1671     // Create copy from CSR to a virtual register.
1672     Entry->addLiveIn(*I);
1673     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1674       .addReg(*I);
1675 
1676     // Insert the copy-back instructions right before the terminator.
1677     for (auto *Exit : Exits)
1678       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1679               TII->get(TargetOpcode::COPY), *I)
1680         .addReg(NewVR);
1681   }
1682 }
1683 
1684 SDValue SITargetLowering::LowerFormalArguments(
1685     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1686     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1687     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1688   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1689 
1690   MachineFunction &MF = DAG.getMachineFunction();
1691   FunctionType *FType = MF.getFunction().getFunctionType();
1692   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1693   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1694 
1695   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1696     const Function &Fn = MF.getFunction();
1697     DiagnosticInfoUnsupported NoGraphicsHSA(
1698         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1699     DAG.getContext()->diagnose(NoGraphicsHSA);
1700     return DAG.getEntryNode();
1701   }
1702 
1703   // Create stack objects that are used for emitting debugger prologue if
1704   // "amdgpu-debugger-emit-prologue" attribute was specified.
1705   if (ST.debuggerEmitPrologue())
1706     createDebuggerPrologueStackObjects(MF);
1707 
1708   SmallVector<ISD::InputArg, 16> Splits;
1709   SmallVector<CCValAssign, 16> ArgLocs;
1710   BitVector Skipped(Ins.size());
1711   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1712                  *DAG.getContext());
1713 
1714   bool IsShader = AMDGPU::isShader(CallConv);
1715   bool IsKernel = AMDGPU::isKernel(CallConv);
1716   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1717 
1718   if (!IsEntryFunc) {
1719     // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1720     // this when allocating argument fixed offsets.
1721     CCInfo.AllocateStack(4, 4);
1722   }
1723 
1724   if (IsShader) {
1725     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1726 
1727     // At least one interpolation mode must be enabled or else the GPU will
1728     // hang.
1729     //
1730     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1731     // set PSInputAddr, the user wants to enable some bits after the compilation
1732     // based on run-time states. Since we can't know what the final PSInputEna
1733     // will look like, so we shouldn't do anything here and the user should take
1734     // responsibility for the correct programming.
1735     //
1736     // Otherwise, the following restrictions apply:
1737     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1738     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1739     //   enabled too.
1740     if (CallConv == CallingConv::AMDGPU_PS) {
1741       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1742            ((Info->getPSInputAddr() & 0xF) == 0 &&
1743             Info->isPSInputAllocated(11))) {
1744         CCInfo.AllocateReg(AMDGPU::VGPR0);
1745         CCInfo.AllocateReg(AMDGPU::VGPR1);
1746         Info->markPSInputAllocated(0);
1747         Info->markPSInputEnabled(0);
1748       }
1749       if (Subtarget->isAmdPalOS()) {
1750         // For isAmdPalOS, the user does not enable some bits after compilation
1751         // based on run-time states; the register values being generated here are
1752         // the final ones set in hardware. Therefore we need to apply the
1753         // workaround to PSInputAddr and PSInputEnable together.  (The case where
1754         // a bit is set in PSInputAddr but not PSInputEnable is where the
1755         // frontend set up an input arg for a particular interpolation mode, but
1756         // nothing uses that input arg. Really we should have an earlier pass
1757         // that removes such an arg.)
1758         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1759         if ((PsInputBits & 0x7F) == 0 ||
1760             ((PsInputBits & 0xF) == 0 &&
1761              (PsInputBits >> 11 & 1)))
1762           Info->markPSInputEnabled(
1763               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1764       }
1765     }
1766 
1767     assert(!Info->hasDispatchPtr() &&
1768            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1769            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1770            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1771            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1772            !Info->hasWorkItemIDZ());
1773   } else if (IsKernel) {
1774     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1775   } else {
1776     Splits.append(Ins.begin(), Ins.end());
1777   }
1778 
1779   if (IsEntryFunc) {
1780     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1781     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1782   }
1783 
1784   if (IsKernel) {
1785     analyzeFormalArgumentsCompute(CCInfo, Ins);
1786   } else {
1787     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1788     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1789   }
1790 
1791   SmallVector<SDValue, 16> Chains;
1792 
1793   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1794     const ISD::InputArg &Arg = Ins[i];
1795     if (Skipped[i]) {
1796       InVals.push_back(DAG.getUNDEF(Arg.VT));
1797       continue;
1798     }
1799 
1800     CCValAssign &VA = ArgLocs[ArgIdx++];
1801     MVT VT = VA.getLocVT();
1802 
1803     if (IsEntryFunc && VA.isMemLoc()) {
1804       VT = Ins[i].VT;
1805       EVT MemVT = VA.getLocVT();
1806 
1807       const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) +
1808         VA.getLocMemOffset();
1809       Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1810 
1811       // The first 36 bytes of the input buffer contains information about
1812       // thread group and global sizes.
1813       SDValue Arg = lowerKernargMemParameter(
1814         DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]);
1815       Chains.push_back(Arg.getValue(1));
1816 
1817       auto *ParamTy =
1818         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1819       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1820           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1821         // On SI local pointers are just offsets into LDS, so they are always
1822         // less than 16-bits.  On CI and newer they could potentially be
1823         // real pointers, so we can't guarantee their size.
1824         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1825                           DAG.getValueType(MVT::i16));
1826       }
1827 
1828       InVals.push_back(Arg);
1829       continue;
1830     } else if (!IsEntryFunc && VA.isMemLoc()) {
1831       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1832       InVals.push_back(Val);
1833       if (!Arg.Flags.isByVal())
1834         Chains.push_back(Val.getValue(1));
1835       continue;
1836     }
1837 
1838     assert(VA.isRegLoc() && "Parameter must be in a register!");
1839 
1840     unsigned Reg = VA.getLocReg();
1841     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1842     EVT ValVT = VA.getValVT();
1843 
1844     Reg = MF.addLiveIn(Reg, RC);
1845     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1846 
1847     if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1848       // The return object should be reasonably addressable.
1849 
1850       // FIXME: This helps when the return is a real sret. If it is a
1851       // automatically inserted sret (i.e. CanLowerReturn returns false), an
1852       // extra copy is inserted in SelectionDAGBuilder which obscures this.
1853       unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1854       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1855         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1856     }
1857 
1858     // If this is an 8 or 16-bit value, it is really passed promoted
1859     // to 32 bits. Insert an assert[sz]ext to capture this, then
1860     // truncate to the right size.
1861     switch (VA.getLocInfo()) {
1862     case CCValAssign::Full:
1863       break;
1864     case CCValAssign::BCvt:
1865       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1866       break;
1867     case CCValAssign::SExt:
1868       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1869                         DAG.getValueType(ValVT));
1870       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1871       break;
1872     case CCValAssign::ZExt:
1873       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1874                         DAG.getValueType(ValVT));
1875       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1876       break;
1877     case CCValAssign::AExt:
1878       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1879       break;
1880     default:
1881       llvm_unreachable("Unknown loc info!");
1882     }
1883 
1884     if (IsShader && Arg.VT.isVector()) {
1885       // Build a vector from the registers
1886       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1887       unsigned NumElements = ParamType->getVectorNumElements();
1888 
1889       SmallVector<SDValue, 4> Regs;
1890       Regs.push_back(Val);
1891       for (unsigned j = 1; j != NumElements; ++j) {
1892         Reg = ArgLocs[ArgIdx++].getLocReg();
1893         Reg = MF.addLiveIn(Reg, RC);
1894 
1895         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1896         Regs.push_back(Copy);
1897       }
1898 
1899       // Fill up the missing vector elements
1900       NumElements = Arg.VT.getVectorNumElements() - NumElements;
1901       Regs.append(NumElements, DAG.getUNDEF(VT));
1902 
1903       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1904       continue;
1905     }
1906 
1907     InVals.push_back(Val);
1908   }
1909 
1910   if (!IsEntryFunc) {
1911     // Special inputs come after user arguments.
1912     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1913   }
1914 
1915   // Start adding system SGPRs.
1916   if (IsEntryFunc) {
1917     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1918   } else {
1919     CCInfo.AllocateReg(Info->getScratchRSrcReg());
1920     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1921     CCInfo.AllocateReg(Info->getFrameOffsetReg());
1922     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1923   }
1924 
1925   auto &ArgUsageInfo =
1926     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1927   ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo());
1928 
1929   unsigned StackArgSize = CCInfo.getNextStackOffset();
1930   Info->setBytesInStackArgArea(StackArgSize);
1931 
1932   return Chains.empty() ? Chain :
1933     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1934 }
1935 
1936 // TODO: If return values can't fit in registers, we should return as many as
1937 // possible in registers before passing on stack.
1938 bool SITargetLowering::CanLowerReturn(
1939   CallingConv::ID CallConv,
1940   MachineFunction &MF, bool IsVarArg,
1941   const SmallVectorImpl<ISD::OutputArg> &Outs,
1942   LLVMContext &Context) const {
1943   // Replacing returns with sret/stack usage doesn't make sense for shaders.
1944   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1945   // for shaders. Vector types should be explicitly handled by CC.
1946   if (AMDGPU::isEntryFunctionCC(CallConv))
1947     return true;
1948 
1949   SmallVector<CCValAssign, 16> RVLocs;
1950   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1951   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1952 }
1953 
1954 SDValue
1955 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1956                               bool isVarArg,
1957                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1958                               const SmallVectorImpl<SDValue> &OutVals,
1959                               const SDLoc &DL, SelectionDAG &DAG) const {
1960   MachineFunction &MF = DAG.getMachineFunction();
1961   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1962 
1963   if (AMDGPU::isKernel(CallConv)) {
1964     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1965                                              OutVals, DL, DAG);
1966   }
1967 
1968   bool IsShader = AMDGPU::isShader(CallConv);
1969 
1970   Info->setIfReturnsVoid(Outs.size() == 0);
1971   bool IsWaveEnd = Info->returnsVoid() && IsShader;
1972 
1973   SmallVector<ISD::OutputArg, 48> Splits;
1974   SmallVector<SDValue, 48> SplitVals;
1975 
1976   // Split vectors into their elements.
1977   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1978     const ISD::OutputArg &Out = Outs[i];
1979 
1980     if (IsShader && Out.VT.isVector()) {
1981       MVT VT = Out.VT.getVectorElementType();
1982       ISD::OutputArg NewOut = Out;
1983       NewOut.Flags.setSplit();
1984       NewOut.VT = VT;
1985 
1986       // We want the original number of vector elements here, e.g.
1987       // three or five, not four or eight.
1988       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1989 
1990       for (unsigned j = 0; j != NumElements; ++j) {
1991         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1992                                    DAG.getConstant(j, DL, MVT::i32));
1993         SplitVals.push_back(Elem);
1994         Splits.push_back(NewOut);
1995         NewOut.PartOffset += NewOut.VT.getStoreSize();
1996       }
1997     } else {
1998       SplitVals.push_back(OutVals[i]);
1999       Splits.push_back(Out);
2000     }
2001   }
2002 
2003   // CCValAssign - represent the assignment of the return value to a location.
2004   SmallVector<CCValAssign, 48> RVLocs;
2005 
2006   // CCState - Info about the registers and stack slots.
2007   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2008                  *DAG.getContext());
2009 
2010   // Analyze outgoing return values.
2011   CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
2012 
2013   SDValue Flag;
2014   SmallVector<SDValue, 48> RetOps;
2015   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2016 
2017   // Add return address for callable functions.
2018   if (!Info->isEntryFunction()) {
2019     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2020     SDValue ReturnAddrReg = CreateLiveInRegister(
2021       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2022 
2023     // FIXME: Should be able to use a vreg here, but need a way to prevent it
2024     // from being allcoated to a CSR.
2025 
2026     SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2027                                                 MVT::i64);
2028 
2029     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2030     Flag = Chain.getValue(1);
2031 
2032     RetOps.push_back(PhysReturnAddrReg);
2033   }
2034 
2035   // Copy the result values into the output registers.
2036   for (unsigned i = 0, realRVLocIdx = 0;
2037        i != RVLocs.size();
2038        ++i, ++realRVLocIdx) {
2039     CCValAssign &VA = RVLocs[i];
2040     assert(VA.isRegLoc() && "Can only return in registers!");
2041     // TODO: Partially return in registers if return values don't fit.
2042 
2043     SDValue Arg = SplitVals[realRVLocIdx];
2044 
2045     // Copied from other backends.
2046     switch (VA.getLocInfo()) {
2047     case CCValAssign::Full:
2048       break;
2049     case CCValAssign::BCvt:
2050       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2051       break;
2052     case CCValAssign::SExt:
2053       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2054       break;
2055     case CCValAssign::ZExt:
2056       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2057       break;
2058     case CCValAssign::AExt:
2059       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2060       break;
2061     default:
2062       llvm_unreachable("Unknown loc info!");
2063     }
2064 
2065     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2066     Flag = Chain.getValue(1);
2067     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2068   }
2069 
2070   // FIXME: Does sret work properly?
2071   if (!Info->isEntryFunction()) {
2072     const SIRegisterInfo *TRI
2073       = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
2074     const MCPhysReg *I =
2075       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2076     if (I) {
2077       for (; *I; ++I) {
2078         if (AMDGPU::SReg_64RegClass.contains(*I))
2079           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2080         else if (AMDGPU::SReg_32RegClass.contains(*I))
2081           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2082         else
2083           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2084       }
2085     }
2086   }
2087 
2088   // Update chain and glue.
2089   RetOps[0] = Chain;
2090   if (Flag.getNode())
2091     RetOps.push_back(Flag);
2092 
2093   unsigned Opc = AMDGPUISD::ENDPGM;
2094   if (!IsWaveEnd)
2095     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2096   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2097 }
2098 
2099 SDValue SITargetLowering::LowerCallResult(
2100     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2101     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2102     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2103     SDValue ThisVal) const {
2104   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2105 
2106   // Assign locations to each value returned by this call.
2107   SmallVector<CCValAssign, 16> RVLocs;
2108   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2109                  *DAG.getContext());
2110   CCInfo.AnalyzeCallResult(Ins, RetCC);
2111 
2112   // Copy all of the result registers out of their specified physreg.
2113   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2114     CCValAssign VA = RVLocs[i];
2115     SDValue Val;
2116 
2117     if (VA.isRegLoc()) {
2118       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2119       Chain = Val.getValue(1);
2120       InFlag = Val.getValue(2);
2121     } else if (VA.isMemLoc()) {
2122       report_fatal_error("TODO: return values in memory");
2123     } else
2124       llvm_unreachable("unknown argument location type");
2125 
2126     switch (VA.getLocInfo()) {
2127     case CCValAssign::Full:
2128       break;
2129     case CCValAssign::BCvt:
2130       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2131       break;
2132     case CCValAssign::ZExt:
2133       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2134                         DAG.getValueType(VA.getValVT()));
2135       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2136       break;
2137     case CCValAssign::SExt:
2138       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2139                         DAG.getValueType(VA.getValVT()));
2140       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2141       break;
2142     case CCValAssign::AExt:
2143       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2144       break;
2145     default:
2146       llvm_unreachable("Unknown loc info!");
2147     }
2148 
2149     InVals.push_back(Val);
2150   }
2151 
2152   return Chain;
2153 }
2154 
2155 // Add code to pass special inputs required depending on used features separate
2156 // from the explicit user arguments present in the IR.
2157 void SITargetLowering::passSpecialInputs(
2158     CallLoweringInfo &CLI,
2159     const SIMachineFunctionInfo &Info,
2160     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2161     SmallVectorImpl<SDValue> &MemOpChains,
2162     SDValue Chain,
2163     SDValue StackPtr) const {
2164   // If we don't have a call site, this was a call inserted by
2165   // legalization. These can never use special inputs.
2166   if (!CLI.CS)
2167     return;
2168 
2169   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2170   assert(CalleeFunc);
2171 
2172   SelectionDAG &DAG = CLI.DAG;
2173   const SDLoc &DL = CLI.DL;
2174 
2175   const SISubtarget *ST = getSubtarget();
2176   const SIRegisterInfo *TRI = ST->getRegisterInfo();
2177 
2178   auto &ArgUsageInfo =
2179     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2180   const AMDGPUFunctionArgInfo &CalleeArgInfo
2181     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2182 
2183   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2184 
2185   // TODO: Unify with private memory register handling. This is complicated by
2186   // the fact that at least in kernels, the input argument is not necessarily
2187   // in the same location as the input.
2188   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2189     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2190     AMDGPUFunctionArgInfo::QUEUE_PTR,
2191     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2192     AMDGPUFunctionArgInfo::DISPATCH_ID,
2193     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2194     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2195     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2196     AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2197     AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2198     AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2199     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2200   };
2201 
2202   for (auto InputID : InputRegs) {
2203     const ArgDescriptor *OutgoingArg;
2204     const TargetRegisterClass *ArgRC;
2205 
2206     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2207     if (!OutgoingArg)
2208       continue;
2209 
2210     const ArgDescriptor *IncomingArg;
2211     const TargetRegisterClass *IncomingArgRC;
2212     std::tie(IncomingArg, IncomingArgRC)
2213       = CallerArgInfo.getPreloadedValue(InputID);
2214     assert(IncomingArgRC == ArgRC);
2215 
2216     // All special arguments are ints for now.
2217     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2218     SDValue InputReg;
2219 
2220     if (IncomingArg) {
2221       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2222     } else {
2223       // The implicit arg ptr is special because it doesn't have a corresponding
2224       // input for kernels, and is computed from the kernarg segment pointer.
2225       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2226       InputReg = getImplicitArgPtr(DAG, DL);
2227     }
2228 
2229     if (OutgoingArg->isRegister()) {
2230       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2231     } else {
2232       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2233                                               InputReg,
2234                                               OutgoingArg->getStackOffset());
2235       MemOpChains.push_back(ArgStore);
2236     }
2237   }
2238 }
2239 
2240 static bool canGuaranteeTCO(CallingConv::ID CC) {
2241   return CC == CallingConv::Fast;
2242 }
2243 
2244 /// Return true if we might ever do TCO for calls with this calling convention.
2245 static bool mayTailCallThisCC(CallingConv::ID CC) {
2246   switch (CC) {
2247   case CallingConv::C:
2248     return true;
2249   default:
2250     return canGuaranteeTCO(CC);
2251   }
2252 }
2253 
2254 bool SITargetLowering::isEligibleForTailCallOptimization(
2255     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2256     const SmallVectorImpl<ISD::OutputArg> &Outs,
2257     const SmallVectorImpl<SDValue> &OutVals,
2258     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2259   if (!mayTailCallThisCC(CalleeCC))
2260     return false;
2261 
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   const Function &CallerF = MF.getFunction();
2264   CallingConv::ID CallerCC = CallerF.getCallingConv();
2265   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2266   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2267 
2268   // Kernels aren't callable, and don't have a live in return address so it
2269   // doesn't make sense to do a tail call with entry functions.
2270   if (!CallerPreserved)
2271     return false;
2272 
2273   bool CCMatch = CallerCC == CalleeCC;
2274 
2275   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2276     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2277       return true;
2278     return false;
2279   }
2280 
2281   // TODO: Can we handle var args?
2282   if (IsVarArg)
2283     return false;
2284 
2285   for (const Argument &Arg : CallerF.args()) {
2286     if (Arg.hasByValAttr())
2287       return false;
2288   }
2289 
2290   LLVMContext &Ctx = *DAG.getContext();
2291 
2292   // Check that the call results are passed in the same way.
2293   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2294                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2295                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2296     return false;
2297 
2298   // The callee has to preserve all registers the caller needs to preserve.
2299   if (!CCMatch) {
2300     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2301     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2302       return false;
2303   }
2304 
2305   // Nothing more to check if the callee is taking no arguments.
2306   if (Outs.empty())
2307     return true;
2308 
2309   SmallVector<CCValAssign, 16> ArgLocs;
2310   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2311 
2312   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2313 
2314   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2315   // If the stack arguments for this call do not fit into our own save area then
2316   // the call cannot be made tail.
2317   // TODO: Is this really necessary?
2318   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2319     return false;
2320 
2321   const MachineRegisterInfo &MRI = MF.getRegInfo();
2322   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2323 }
2324 
2325 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2326   if (!CI->isTailCall())
2327     return false;
2328 
2329   const Function *ParentFn = CI->getParent()->getParent();
2330   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2331     return false;
2332 
2333   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2334   return (Attr.getValueAsString() != "true");
2335 }
2336 
2337 // The wave scratch offset register is used as the global base pointer.
2338 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2339                                     SmallVectorImpl<SDValue> &InVals) const {
2340   SelectionDAG &DAG = CLI.DAG;
2341   const SDLoc &DL = CLI.DL;
2342   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2343   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2344   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2345   SDValue Chain = CLI.Chain;
2346   SDValue Callee = CLI.Callee;
2347   bool &IsTailCall = CLI.IsTailCall;
2348   CallingConv::ID CallConv = CLI.CallConv;
2349   bool IsVarArg = CLI.IsVarArg;
2350   bool IsSibCall = false;
2351   bool IsThisReturn = false;
2352   MachineFunction &MF = DAG.getMachineFunction();
2353 
2354   if (IsVarArg) {
2355     return lowerUnhandledCall(CLI, InVals,
2356                               "unsupported call to variadic function ");
2357   }
2358 
2359   if (!CLI.CS.getCalledFunction()) {
2360     return lowerUnhandledCall(CLI, InVals,
2361                               "unsupported indirect call to function ");
2362   }
2363 
2364   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2365     return lowerUnhandledCall(CLI, InVals,
2366                               "unsupported required tail call to function ");
2367   }
2368 
2369   // The first 4 bytes are reserved for the callee's emergency stack slot.
2370   const unsigned CalleeUsableStackOffset = 4;
2371 
2372   if (IsTailCall) {
2373     IsTailCall = isEligibleForTailCallOptimization(
2374       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2375     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2376       report_fatal_error("failed to perform tail call elimination on a call "
2377                          "site marked musttail");
2378     }
2379 
2380     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2381 
2382     // A sibling call is one where we're under the usual C ABI and not planning
2383     // to change that but can still do a tail call:
2384     if (!TailCallOpt && IsTailCall)
2385       IsSibCall = true;
2386 
2387     if (IsTailCall)
2388       ++NumTailCalls;
2389   }
2390 
2391   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2392     // FIXME: Remove this hack for function pointer types after removing
2393     // support of old address space mapping. In the new address space
2394     // mapping the pointer in default address space is 64 bit, therefore
2395     // does not need this hack.
2396     if (Callee.getValueType() == MVT::i32) {
2397       const GlobalValue *GV = GA->getGlobal();
2398       Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2399                                     GA->getTargetFlags());
2400     }
2401   }
2402   assert(Callee.getValueType() == MVT::i64);
2403 
2404   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2405 
2406   // Analyze operands of the call, assigning locations to each operand.
2407   SmallVector<CCValAssign, 16> ArgLocs;
2408   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2409   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2410   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2411 
2412   // Get a count of how many bytes are to be pushed on the stack.
2413   unsigned NumBytes = CCInfo.getNextStackOffset();
2414 
2415   if (IsSibCall) {
2416     // Since we're not changing the ABI to make this a tail call, the memory
2417     // operands are already available in the caller's incoming argument space.
2418     NumBytes = 0;
2419   }
2420 
2421   // FPDiff is the byte offset of the call's argument area from the callee's.
2422   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2423   // by this amount for a tail call. In a sibling call it must be 0 because the
2424   // caller will deallocate the entire stack and the callee still expects its
2425   // arguments to begin at SP+0. Completely unused for non-tail calls.
2426   int32_t FPDiff = 0;
2427   MachineFrameInfo &MFI = MF.getFrameInfo();
2428   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2429 
2430   SDValue CallerSavedFP;
2431 
2432   // Adjust the stack pointer for the new arguments...
2433   // These operations are automatically eliminated by the prolog/epilog pass
2434   if (!IsSibCall) {
2435     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2436 
2437     unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2438 
2439     // In the HSA case, this should be an identity copy.
2440     SDValue ScratchRSrcReg
2441       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2442     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2443 
2444     // TODO: Don't hardcode these registers and get from the callee function.
2445     SDValue ScratchWaveOffsetReg
2446       = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2447     RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2448 
2449     if (!Info->isEntryFunction()) {
2450       // Avoid clobbering this function's FP value. In the current convention
2451       // callee will overwrite this, so do save/restore around the call site.
2452       CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2453                                          Info->getFrameOffsetReg(), MVT::i32);
2454     }
2455   }
2456 
2457   // Stack pointer relative accesses are done by changing the offset SGPR. This
2458   // is just the VGPR offset component.
2459   SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2460 
2461   SmallVector<SDValue, 8> MemOpChains;
2462   MVT PtrVT = MVT::i32;
2463 
2464   // Walk the register/memloc assignments, inserting copies/loads.
2465   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2466        ++i, ++realArgIdx) {
2467     CCValAssign &VA = ArgLocs[i];
2468     SDValue Arg = OutVals[realArgIdx];
2469 
2470     // Promote the value if needed.
2471     switch (VA.getLocInfo()) {
2472     case CCValAssign::Full:
2473       break;
2474     case CCValAssign::BCvt:
2475       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2476       break;
2477     case CCValAssign::ZExt:
2478       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2479       break;
2480     case CCValAssign::SExt:
2481       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2482       break;
2483     case CCValAssign::AExt:
2484       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2485       break;
2486     case CCValAssign::FPExt:
2487       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2488       break;
2489     default:
2490       llvm_unreachable("Unknown loc info!");
2491     }
2492 
2493     if (VA.isRegLoc()) {
2494       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2495     } else {
2496       assert(VA.isMemLoc());
2497 
2498       SDValue DstAddr;
2499       MachinePointerInfo DstInfo;
2500 
2501       unsigned LocMemOffset = VA.getLocMemOffset();
2502       int32_t Offset = LocMemOffset;
2503 
2504       SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2505 
2506       if (IsTailCall) {
2507         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2508         unsigned OpSize = Flags.isByVal() ?
2509           Flags.getByValSize() : VA.getValVT().getStoreSize();
2510 
2511         Offset = Offset + FPDiff;
2512         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2513 
2514         DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2515                                          StackPtr);
2516         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2517 
2518         // Make sure any stack arguments overlapping with where we're storing
2519         // are loaded before this eventual operation. Otherwise they'll be
2520         // clobbered.
2521 
2522         // FIXME: Why is this really necessary? This seems to just result in a
2523         // lot of code to copy the stack and write them back to the same
2524         // locations, which are supposed to be immutable?
2525         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2526       } else {
2527         DstAddr = PtrOff;
2528         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2529       }
2530 
2531       if (Outs[i].Flags.isByVal()) {
2532         SDValue SizeNode =
2533             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2534         SDValue Cpy = DAG.getMemcpy(
2535             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2536             /*isVol = */ false, /*AlwaysInline = */ true,
2537             /*isTailCall = */ false, DstInfo,
2538             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2539                 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2540 
2541         MemOpChains.push_back(Cpy);
2542       } else {
2543         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2544         MemOpChains.push_back(Store);
2545       }
2546     }
2547   }
2548 
2549   // Copy special input registers after user input arguments.
2550   passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2551 
2552   if (!MemOpChains.empty())
2553     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2554 
2555   // Build a sequence of copy-to-reg nodes chained together with token chain
2556   // and flag operands which copy the outgoing args into the appropriate regs.
2557   SDValue InFlag;
2558   for (auto &RegToPass : RegsToPass) {
2559     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2560                              RegToPass.second, InFlag);
2561     InFlag = Chain.getValue(1);
2562   }
2563 
2564 
2565   SDValue PhysReturnAddrReg;
2566   if (IsTailCall) {
2567     // Since the return is being combined with the call, we need to pass on the
2568     // return address.
2569 
2570     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2571     SDValue ReturnAddrReg = CreateLiveInRegister(
2572       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2573 
2574     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2575                                         MVT::i64);
2576     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2577     InFlag = Chain.getValue(1);
2578   }
2579 
2580   // We don't usually want to end the call-sequence here because we would tidy
2581   // the frame up *after* the call, however in the ABI-changing tail-call case
2582   // we've carefully laid out the parameters so that when sp is reset they'll be
2583   // in the correct location.
2584   if (IsTailCall && !IsSibCall) {
2585     Chain = DAG.getCALLSEQ_END(Chain,
2586                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2587                                DAG.getTargetConstant(0, DL, MVT::i32),
2588                                InFlag, DL);
2589     InFlag = Chain.getValue(1);
2590   }
2591 
2592   std::vector<SDValue> Ops;
2593   Ops.push_back(Chain);
2594   Ops.push_back(Callee);
2595 
2596   if (IsTailCall) {
2597     // Each tail call may have to adjust the stack by a different amount, so
2598     // this information must travel along with the operation for eventual
2599     // consumption by emitEpilogue.
2600     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2601 
2602     Ops.push_back(PhysReturnAddrReg);
2603   }
2604 
2605   // Add argument registers to the end of the list so that they are known live
2606   // into the call.
2607   for (auto &RegToPass : RegsToPass) {
2608     Ops.push_back(DAG.getRegister(RegToPass.first,
2609                                   RegToPass.second.getValueType()));
2610   }
2611 
2612   // Add a register mask operand representing the call-preserved registers.
2613 
2614   const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2615   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2616   assert(Mask && "Missing call preserved mask for calling convention");
2617   Ops.push_back(DAG.getRegisterMask(Mask));
2618 
2619   if (InFlag.getNode())
2620     Ops.push_back(InFlag);
2621 
2622   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2623 
2624   // If we're doing a tall call, use a TC_RETURN here rather than an
2625   // actual call instruction.
2626   if (IsTailCall) {
2627     MFI.setHasTailCall();
2628     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2629   }
2630 
2631   // Returns a chain and a flag for retval copy to use.
2632   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2633   Chain = Call.getValue(0);
2634   InFlag = Call.getValue(1);
2635 
2636   if (CallerSavedFP) {
2637     SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2638     Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2639     InFlag = Chain.getValue(1);
2640   }
2641 
2642   uint64_t CalleePopBytes = NumBytes;
2643   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2644                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2645                              InFlag, DL);
2646   if (!Ins.empty())
2647     InFlag = Chain.getValue(1);
2648 
2649   // Handle result values, copying them out of physregs into vregs that we
2650   // return.
2651   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2652                          InVals, IsThisReturn,
2653                          IsThisReturn ? OutVals[0] : SDValue());
2654 }
2655 
2656 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2657                                              SelectionDAG &DAG) const {
2658   unsigned Reg = StringSwitch<unsigned>(RegName)
2659     .Case("m0", AMDGPU::M0)
2660     .Case("exec", AMDGPU::EXEC)
2661     .Case("exec_lo", AMDGPU::EXEC_LO)
2662     .Case("exec_hi", AMDGPU::EXEC_HI)
2663     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2664     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2665     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2666     .Default(AMDGPU::NoRegister);
2667 
2668   if (Reg == AMDGPU::NoRegister) {
2669     report_fatal_error(Twine("invalid register name \""
2670                              + StringRef(RegName)  + "\"."));
2671 
2672   }
2673 
2674   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2675       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2676     report_fatal_error(Twine("invalid register \""
2677                              + StringRef(RegName)  + "\" for subtarget."));
2678   }
2679 
2680   switch (Reg) {
2681   case AMDGPU::M0:
2682   case AMDGPU::EXEC_LO:
2683   case AMDGPU::EXEC_HI:
2684   case AMDGPU::FLAT_SCR_LO:
2685   case AMDGPU::FLAT_SCR_HI:
2686     if (VT.getSizeInBits() == 32)
2687       return Reg;
2688     break;
2689   case AMDGPU::EXEC:
2690   case AMDGPU::FLAT_SCR:
2691     if (VT.getSizeInBits() == 64)
2692       return Reg;
2693     break;
2694   default:
2695     llvm_unreachable("missing register type checking");
2696   }
2697 
2698   report_fatal_error(Twine("invalid type for register \""
2699                            + StringRef(RegName) + "\"."));
2700 }
2701 
2702 // If kill is not the last instruction, split the block so kill is always a
2703 // proper terminator.
2704 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2705                                                     MachineBasicBlock *BB) const {
2706   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2707 
2708   MachineBasicBlock::iterator SplitPoint(&MI);
2709   ++SplitPoint;
2710 
2711   if (SplitPoint == BB->end()) {
2712     // Don't bother with a new block.
2713     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2714     return BB;
2715   }
2716 
2717   MachineFunction *MF = BB->getParent();
2718   MachineBasicBlock *SplitBB
2719     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2720 
2721   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2722   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2723 
2724   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2725   BB->addSuccessor(SplitBB);
2726 
2727   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2728   return SplitBB;
2729 }
2730 
2731 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2732 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2733 // will only do one iteration. In the worst case, this will loop 64 times.
2734 //
2735 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2736 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2737   const SIInstrInfo *TII,
2738   MachineRegisterInfo &MRI,
2739   MachineBasicBlock &OrigBB,
2740   MachineBasicBlock &LoopBB,
2741   const DebugLoc &DL,
2742   const MachineOperand &IdxReg,
2743   unsigned InitReg,
2744   unsigned ResultReg,
2745   unsigned PhiReg,
2746   unsigned InitSaveExecReg,
2747   int Offset,
2748   bool UseGPRIdxMode) {
2749   MachineBasicBlock::iterator I = LoopBB.begin();
2750 
2751   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2752   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2753   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2754   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2755 
2756   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2757     .addReg(InitReg)
2758     .addMBB(&OrigBB)
2759     .addReg(ResultReg)
2760     .addMBB(&LoopBB);
2761 
2762   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2763     .addReg(InitSaveExecReg)
2764     .addMBB(&OrigBB)
2765     .addReg(NewExec)
2766     .addMBB(&LoopBB);
2767 
2768   // Read the next variant <- also loop target.
2769   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2770     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2771 
2772   // Compare the just read M0 value to all possible Idx values.
2773   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2774     .addReg(CurrentIdxReg)
2775     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2776 
2777   if (UseGPRIdxMode) {
2778     unsigned IdxReg;
2779     if (Offset == 0) {
2780       IdxReg = CurrentIdxReg;
2781     } else {
2782       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2783       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2784         .addReg(CurrentIdxReg, RegState::Kill)
2785         .addImm(Offset);
2786     }
2787 
2788     MachineInstr *SetIdx =
2789       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_IDX))
2790       .addReg(IdxReg, RegState::Kill);
2791     SetIdx->getOperand(2).setIsUndef();
2792   } else {
2793     // Move index from VCC into M0
2794     if (Offset == 0) {
2795       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2796         .addReg(CurrentIdxReg, RegState::Kill);
2797     } else {
2798       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2799         .addReg(CurrentIdxReg, RegState::Kill)
2800         .addImm(Offset);
2801     }
2802   }
2803 
2804   // Update EXEC, save the original EXEC value to VCC.
2805   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2806     .addReg(CondReg, RegState::Kill);
2807 
2808   MRI.setSimpleHint(NewExec, CondReg);
2809 
2810   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2811   MachineInstr *InsertPt =
2812     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2813     .addReg(AMDGPU::EXEC)
2814     .addReg(NewExec);
2815 
2816   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2817   // s_cbranch_scc0?
2818 
2819   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2820   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2821     .addMBB(&LoopBB);
2822 
2823   return InsertPt->getIterator();
2824 }
2825 
2826 // This has slightly sub-optimal regalloc when the source vector is killed by
2827 // the read. The register allocator does not understand that the kill is
2828 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2829 // subregister from it, using 1 more VGPR than necessary. This was saved when
2830 // this was expanded after register allocation.
2831 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2832                                                   MachineBasicBlock &MBB,
2833                                                   MachineInstr &MI,
2834                                                   unsigned InitResultReg,
2835                                                   unsigned PhiReg,
2836                                                   int Offset,
2837                                                   bool UseGPRIdxMode) {
2838   MachineFunction *MF = MBB.getParent();
2839   MachineRegisterInfo &MRI = MF->getRegInfo();
2840   const DebugLoc &DL = MI.getDebugLoc();
2841   MachineBasicBlock::iterator I(&MI);
2842 
2843   unsigned DstReg = MI.getOperand(0).getReg();
2844   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2845   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2846 
2847   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2848 
2849   // Save the EXEC mask
2850   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2851     .addReg(AMDGPU::EXEC);
2852 
2853   // To insert the loop we need to split the block. Move everything after this
2854   // point to a new block, and insert a new empty block between the two.
2855   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2856   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2857   MachineFunction::iterator MBBI(MBB);
2858   ++MBBI;
2859 
2860   MF->insert(MBBI, LoopBB);
2861   MF->insert(MBBI, RemainderBB);
2862 
2863   LoopBB->addSuccessor(LoopBB);
2864   LoopBB->addSuccessor(RemainderBB);
2865 
2866   // Move the rest of the block into a new block.
2867   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2868   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2869 
2870   MBB.addSuccessor(LoopBB);
2871 
2872   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2873 
2874   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2875                                       InitResultReg, DstReg, PhiReg, TmpExec,
2876                                       Offset, UseGPRIdxMode);
2877 
2878   MachineBasicBlock::iterator First = RemainderBB->begin();
2879   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2880     .addReg(SaveExec);
2881 
2882   return InsPt;
2883 }
2884 
2885 // Returns subreg index, offset
2886 static std::pair<unsigned, int>
2887 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2888                             const TargetRegisterClass *SuperRC,
2889                             unsigned VecReg,
2890                             int Offset) {
2891   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2892 
2893   // Skip out of bounds offsets, or else we would end up using an undefined
2894   // register.
2895   if (Offset >= NumElts || Offset < 0)
2896     return std::make_pair(AMDGPU::sub0, Offset);
2897 
2898   return std::make_pair(AMDGPU::sub0 + Offset, 0);
2899 }
2900 
2901 // Return true if the index is an SGPR and was set.
2902 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2903                                  MachineRegisterInfo &MRI,
2904                                  MachineInstr &MI,
2905                                  int Offset,
2906                                  bool UseGPRIdxMode,
2907                                  bool IsIndirectSrc) {
2908   MachineBasicBlock *MBB = MI.getParent();
2909   const DebugLoc &DL = MI.getDebugLoc();
2910   MachineBasicBlock::iterator I(&MI);
2911 
2912   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2913   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2914 
2915   assert(Idx->getReg() != AMDGPU::NoRegister);
2916 
2917   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2918     return false;
2919 
2920   if (UseGPRIdxMode) {
2921     unsigned IdxMode = IsIndirectSrc ?
2922       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2923     if (Offset == 0) {
2924       MachineInstr *SetOn =
2925           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2926               .add(*Idx)
2927               .addImm(IdxMode);
2928 
2929       SetOn->getOperand(3).setIsUndef();
2930     } else {
2931       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2932       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2933           .add(*Idx)
2934           .addImm(Offset);
2935       MachineInstr *SetOn =
2936         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2937         .addReg(Tmp, RegState::Kill)
2938         .addImm(IdxMode);
2939 
2940       SetOn->getOperand(3).setIsUndef();
2941     }
2942 
2943     return true;
2944   }
2945 
2946   if (Offset == 0) {
2947     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2948       .add(*Idx);
2949   } else {
2950     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2951       .add(*Idx)
2952       .addImm(Offset);
2953   }
2954 
2955   return true;
2956 }
2957 
2958 // Control flow needs to be inserted if indexing with a VGPR.
2959 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2960                                           MachineBasicBlock &MBB,
2961                                           const SISubtarget &ST) {
2962   const SIInstrInfo *TII = ST.getInstrInfo();
2963   const SIRegisterInfo &TRI = TII->getRegisterInfo();
2964   MachineFunction *MF = MBB.getParent();
2965   MachineRegisterInfo &MRI = MF->getRegInfo();
2966 
2967   unsigned Dst = MI.getOperand(0).getReg();
2968   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2969   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2970 
2971   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2972 
2973   unsigned SubReg;
2974   std::tie(SubReg, Offset)
2975     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2976 
2977   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2978 
2979   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2980     MachineBasicBlock::iterator I(&MI);
2981     const DebugLoc &DL = MI.getDebugLoc();
2982 
2983     if (UseGPRIdxMode) {
2984       // TODO: Look at the uses to avoid the copy. This may require rescheduling
2985       // to avoid interfering with other uses, so probably requires a new
2986       // optimization pass.
2987       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2988         .addReg(SrcReg, RegState::Undef, SubReg)
2989         .addReg(SrcReg, RegState::Implicit)
2990         .addReg(AMDGPU::M0, RegState::Implicit);
2991       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2992     } else {
2993       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2994         .addReg(SrcReg, RegState::Undef, SubReg)
2995         .addReg(SrcReg, RegState::Implicit);
2996     }
2997 
2998     MI.eraseFromParent();
2999 
3000     return &MBB;
3001   }
3002 
3003   const DebugLoc &DL = MI.getDebugLoc();
3004   MachineBasicBlock::iterator I(&MI);
3005 
3006   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3007   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3008 
3009   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3010 
3011   if (UseGPRIdxMode) {
3012     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3013       .addImm(0) // Reset inside loop.
3014       .addImm(VGPRIndexMode::SRC0_ENABLE);
3015     SetOn->getOperand(3).setIsUndef();
3016 
3017     // Disable again after the loop.
3018     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3019   }
3020 
3021   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, UseGPRIdxMode);
3022   MachineBasicBlock *LoopBB = InsPt->getParent();
3023 
3024   if (UseGPRIdxMode) {
3025     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3026       .addReg(SrcReg, RegState::Undef, SubReg)
3027       .addReg(SrcReg, RegState::Implicit)
3028       .addReg(AMDGPU::M0, RegState::Implicit);
3029   } else {
3030     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3031       .addReg(SrcReg, RegState::Undef, SubReg)
3032       .addReg(SrcReg, RegState::Implicit);
3033   }
3034 
3035   MI.eraseFromParent();
3036 
3037   return LoopBB;
3038 }
3039 
3040 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3041                                  const TargetRegisterClass *VecRC) {
3042   switch (TRI.getRegSizeInBits(*VecRC)) {
3043   case 32: // 4 bytes
3044     return AMDGPU::V_MOVRELD_B32_V1;
3045   case 64: // 8 bytes
3046     return AMDGPU::V_MOVRELD_B32_V2;
3047   case 128: // 16 bytes
3048     return AMDGPU::V_MOVRELD_B32_V4;
3049   case 256: // 32 bytes
3050     return AMDGPU::V_MOVRELD_B32_V8;
3051   case 512: // 64 bytes
3052     return AMDGPU::V_MOVRELD_B32_V16;
3053   default:
3054     llvm_unreachable("unsupported size for MOVRELD pseudos");
3055   }
3056 }
3057 
3058 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3059                                           MachineBasicBlock &MBB,
3060                                           const SISubtarget &ST) {
3061   const SIInstrInfo *TII = ST.getInstrInfo();
3062   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3063   MachineFunction *MF = MBB.getParent();
3064   MachineRegisterInfo &MRI = MF->getRegInfo();
3065 
3066   unsigned Dst = MI.getOperand(0).getReg();
3067   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3068   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3069   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3070   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3071   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3072 
3073   // This can be an immediate, but will be folded later.
3074   assert(Val->getReg());
3075 
3076   unsigned SubReg;
3077   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3078                                                          SrcVec->getReg(),
3079                                                          Offset);
3080   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3081 
3082   if (Idx->getReg() == AMDGPU::NoRegister) {
3083     MachineBasicBlock::iterator I(&MI);
3084     const DebugLoc &DL = MI.getDebugLoc();
3085 
3086     assert(Offset == 0);
3087 
3088     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3089         .add(*SrcVec)
3090         .add(*Val)
3091         .addImm(SubReg);
3092 
3093     MI.eraseFromParent();
3094     return &MBB;
3095   }
3096 
3097   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3098     MachineBasicBlock::iterator I(&MI);
3099     const DebugLoc &DL = MI.getDebugLoc();
3100 
3101     if (UseGPRIdxMode) {
3102       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3103           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3104           .add(*Val)
3105           .addReg(Dst, RegState::ImplicitDefine)
3106           .addReg(SrcVec->getReg(), RegState::Implicit)
3107           .addReg(AMDGPU::M0, RegState::Implicit);
3108 
3109       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3110     } else {
3111       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3112 
3113       BuildMI(MBB, I, DL, MovRelDesc)
3114           .addReg(Dst, RegState::Define)
3115           .addReg(SrcVec->getReg())
3116           .add(*Val)
3117           .addImm(SubReg - AMDGPU::sub0);
3118     }
3119 
3120     MI.eraseFromParent();
3121     return &MBB;
3122   }
3123 
3124   if (Val->isReg())
3125     MRI.clearKillFlags(Val->getReg());
3126 
3127   const DebugLoc &DL = MI.getDebugLoc();
3128 
3129   if (UseGPRIdxMode) {
3130     MachineBasicBlock::iterator I(&MI);
3131 
3132     MachineInstr *SetOn = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3133       .addImm(0) // Reset inside loop.
3134       .addImm(VGPRIndexMode::DST_ENABLE);
3135     SetOn->getOperand(3).setIsUndef();
3136 
3137     // Disable again after the loop.
3138     BuildMI(MBB, std::next(I), DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3139   }
3140 
3141   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3142 
3143   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3144                               Offset, UseGPRIdxMode);
3145   MachineBasicBlock *LoopBB = InsPt->getParent();
3146 
3147   if (UseGPRIdxMode) {
3148     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3149         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3150         .add(*Val)                               // src0
3151         .addReg(Dst, RegState::ImplicitDefine)
3152         .addReg(PhiReg, RegState::Implicit)
3153         .addReg(AMDGPU::M0, RegState::Implicit);
3154   } else {
3155     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3156 
3157     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3158         .addReg(Dst, RegState::Define)
3159         .addReg(PhiReg)
3160         .add(*Val)
3161         .addImm(SubReg - AMDGPU::sub0);
3162   }
3163 
3164   MI.eraseFromParent();
3165 
3166   return LoopBB;
3167 }
3168 
3169 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3170   MachineInstr &MI, MachineBasicBlock *BB) const {
3171 
3172   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3173   MachineFunction *MF = BB->getParent();
3174   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3175 
3176   if (TII->isMIMG(MI)) {
3177     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3178       report_fatal_error("missing mem operand from MIMG instruction");
3179     }
3180     // Add a memoperand for mimg instructions so that they aren't assumed to
3181     // be ordered memory instuctions.
3182 
3183     return BB;
3184   }
3185 
3186   switch (MI.getOpcode()) {
3187   case AMDGPU::S_ADD_U64_PSEUDO:
3188   case AMDGPU::S_SUB_U64_PSEUDO: {
3189     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3190     const DebugLoc &DL = MI.getDebugLoc();
3191 
3192     MachineOperand &Dest = MI.getOperand(0);
3193     MachineOperand &Src0 = MI.getOperand(1);
3194     MachineOperand &Src1 = MI.getOperand(2);
3195 
3196     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3197     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3198 
3199     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3200      Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3201      &AMDGPU::SReg_32_XM0RegClass);
3202     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3203       Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3204       &AMDGPU::SReg_32_XM0RegClass);
3205 
3206     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3207       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3208       &AMDGPU::SReg_32_XM0RegClass);
3209     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3210       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3211       &AMDGPU::SReg_32_XM0RegClass);
3212 
3213     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3214 
3215     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3216     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3217     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3218       .add(Src0Sub0)
3219       .add(Src1Sub0);
3220     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3221       .add(Src0Sub1)
3222       .add(Src1Sub1);
3223     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3224       .addReg(DestSub0)
3225       .addImm(AMDGPU::sub0)
3226       .addReg(DestSub1)
3227       .addImm(AMDGPU::sub1);
3228     MI.eraseFromParent();
3229     return BB;
3230   }
3231   case AMDGPU::SI_INIT_M0: {
3232     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3233             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3234         .add(MI.getOperand(0));
3235     MI.eraseFromParent();
3236     return BB;
3237   }
3238   case AMDGPU::SI_INIT_EXEC:
3239     // This should be before all vector instructions.
3240     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3241             AMDGPU::EXEC)
3242         .addImm(MI.getOperand(0).getImm());
3243     MI.eraseFromParent();
3244     return BB;
3245 
3246   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3247     // Extract the thread count from an SGPR input and set EXEC accordingly.
3248     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3249     //
3250     // S_BFE_U32 count, input, {shift, 7}
3251     // S_BFM_B64 exec, count, 0
3252     // S_CMP_EQ_U32 count, 64
3253     // S_CMOV_B64 exec, -1
3254     MachineInstr *FirstMI = &*BB->begin();
3255     MachineRegisterInfo &MRI = MF->getRegInfo();
3256     unsigned InputReg = MI.getOperand(0).getReg();
3257     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3258     bool Found = false;
3259 
3260     // Move the COPY of the input reg to the beginning, so that we can use it.
3261     for (auto I = BB->begin(); I != &MI; I++) {
3262       if (I->getOpcode() != TargetOpcode::COPY ||
3263           I->getOperand(0).getReg() != InputReg)
3264         continue;
3265 
3266       if (I == FirstMI) {
3267         FirstMI = &*++BB->begin();
3268       } else {
3269         I->removeFromParent();
3270         BB->insert(FirstMI, &*I);
3271       }
3272       Found = true;
3273       break;
3274     }
3275     assert(Found);
3276     (void)Found;
3277 
3278     // This should be before all vector instructions.
3279     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3280         .addReg(InputReg)
3281         .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3282     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3283             AMDGPU::EXEC)
3284         .addReg(CountReg)
3285         .addImm(0);
3286     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3287         .addReg(CountReg, RegState::Kill)
3288         .addImm(64);
3289     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3290             AMDGPU::EXEC)
3291         .addImm(-1);
3292     MI.eraseFromParent();
3293     return BB;
3294   }
3295 
3296   case AMDGPU::GET_GROUPSTATICSIZE: {
3297     DebugLoc DL = MI.getDebugLoc();
3298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3299         .add(MI.getOperand(0))
3300         .addImm(MFI->getLDSSize());
3301     MI.eraseFromParent();
3302     return BB;
3303   }
3304   case AMDGPU::SI_INDIRECT_SRC_V1:
3305   case AMDGPU::SI_INDIRECT_SRC_V2:
3306   case AMDGPU::SI_INDIRECT_SRC_V4:
3307   case AMDGPU::SI_INDIRECT_SRC_V8:
3308   case AMDGPU::SI_INDIRECT_SRC_V16:
3309     return emitIndirectSrc(MI, *BB, *getSubtarget());
3310   case AMDGPU::SI_INDIRECT_DST_V1:
3311   case AMDGPU::SI_INDIRECT_DST_V2:
3312   case AMDGPU::SI_INDIRECT_DST_V4:
3313   case AMDGPU::SI_INDIRECT_DST_V8:
3314   case AMDGPU::SI_INDIRECT_DST_V16:
3315     return emitIndirectDst(MI, *BB, *getSubtarget());
3316   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3317   case AMDGPU::SI_KILL_I1_PSEUDO:
3318     return splitKillBlock(MI, BB);
3319   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3320     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3321 
3322     unsigned Dst = MI.getOperand(0).getReg();
3323     unsigned Src0 = MI.getOperand(1).getReg();
3324     unsigned Src1 = MI.getOperand(2).getReg();
3325     const DebugLoc &DL = MI.getDebugLoc();
3326     unsigned SrcCond = MI.getOperand(3).getReg();
3327 
3328     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3329     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3330     unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3331 
3332     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3333       .addReg(SrcCond);
3334     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3335       .addReg(Src0, 0, AMDGPU::sub0)
3336       .addReg(Src1, 0, AMDGPU::sub0)
3337       .addReg(SrcCondCopy);
3338     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3339       .addReg(Src0, 0, AMDGPU::sub1)
3340       .addReg(Src1, 0, AMDGPU::sub1)
3341       .addReg(SrcCondCopy);
3342 
3343     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3344       .addReg(DstLo)
3345       .addImm(AMDGPU::sub0)
3346       .addReg(DstHi)
3347       .addImm(AMDGPU::sub1);
3348     MI.eraseFromParent();
3349     return BB;
3350   }
3351   case AMDGPU::SI_BR_UNDEF: {
3352     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3353     const DebugLoc &DL = MI.getDebugLoc();
3354     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3355                            .add(MI.getOperand(0));
3356     Br->getOperand(1).setIsUndef(true); // read undef SCC
3357     MI.eraseFromParent();
3358     return BB;
3359   }
3360   case AMDGPU::ADJCALLSTACKUP:
3361   case AMDGPU::ADJCALLSTACKDOWN: {
3362     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3363     MachineInstrBuilder MIB(*MF, &MI);
3364     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3365         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
3366     return BB;
3367   }
3368   case AMDGPU::SI_CALL_ISEL:
3369   case AMDGPU::SI_TCRETURN_ISEL: {
3370     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3371     const DebugLoc &DL = MI.getDebugLoc();
3372     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3373 
3374     MachineRegisterInfo &MRI = MF->getRegInfo();
3375     unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3376     MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3377     assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3378 
3379     const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3380 
3381     MachineInstrBuilder MIB;
3382     if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3383       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3384         .add(MI.getOperand(0))
3385         .addGlobalAddress(G);
3386     } else {
3387       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3388         .add(MI.getOperand(0))
3389         .addGlobalAddress(G);
3390 
3391       // There is an additional imm operand for tcreturn, but it should be in the
3392       // right place already.
3393     }
3394 
3395     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3396       MIB.add(MI.getOperand(I));
3397 
3398     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3399     MI.eraseFromParent();
3400     return BB;
3401   }
3402   default:
3403     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3404   }
3405 }
3406 
3407 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3408   return isTypeLegal(VT.getScalarType());
3409 }
3410 
3411 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3412   // This currently forces unfolding various combinations of fsub into fma with
3413   // free fneg'd operands. As long as we have fast FMA (controlled by
3414   // isFMAFasterThanFMulAndFAdd), we should perform these.
3415 
3416   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3417   // most of these combines appear to be cycle neutral but save on instruction
3418   // count / code size.
3419   return true;
3420 }
3421 
3422 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3423                                          EVT VT) const {
3424   if (!VT.isVector()) {
3425     return MVT::i1;
3426   }
3427   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3428 }
3429 
3430 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3431   // TODO: Should i16 be used always if legal? For now it would force VALU
3432   // shifts.
3433   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3434 }
3435 
3436 // Answering this is somewhat tricky and depends on the specific device which
3437 // have different rates for fma or all f64 operations.
3438 //
3439 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3440 // regardless of which device (although the number of cycles differs between
3441 // devices), so it is always profitable for f64.
3442 //
3443 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3444 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3445 // which we can always do even without fused FP ops since it returns the same
3446 // result as the separate operations and since it is always full
3447 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3448 // however does not support denormals, so we do report fma as faster if we have
3449 // a fast fma device and require denormals.
3450 //
3451 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3452   VT = VT.getScalarType();
3453 
3454   switch (VT.getSimpleVT().SimpleTy) {
3455   case MVT::f32:
3456     // This is as fast on some subtargets. However, we always have full rate f32
3457     // mad available which returns the same result as the separate operations
3458     // which we should prefer over fma. We can't use this if we want to support
3459     // denormals, so only report this in these cases.
3460     return Subtarget->hasFP32Denormals() && Subtarget->hasFastFMAF32();
3461   case MVT::f64:
3462     return true;
3463   case MVT::f16:
3464     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3465   default:
3466     break;
3467   }
3468 
3469   return false;
3470 }
3471 
3472 //===----------------------------------------------------------------------===//
3473 // Custom DAG Lowering Operations
3474 //===----------------------------------------------------------------------===//
3475 
3476 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3477   switch (Op.getOpcode()) {
3478   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3479   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3480   case ISD::LOAD: {
3481     SDValue Result = LowerLOAD(Op, DAG);
3482     assert((!Result.getNode() ||
3483             Result.getNode()->getNumValues() == 2) &&
3484            "Load should return a value and a chain");
3485     return Result;
3486   }
3487 
3488   case ISD::FSIN:
3489   case ISD::FCOS:
3490     return LowerTrig(Op, DAG);
3491   case ISD::SELECT: return LowerSELECT(Op, DAG);
3492   case ISD::FDIV: return LowerFDIV(Op, DAG);
3493   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3494   case ISD::STORE: return LowerSTORE(Op, DAG);
3495   case ISD::GlobalAddress: {
3496     MachineFunction &MF = DAG.getMachineFunction();
3497     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3498     return LowerGlobalAddress(MFI, Op, DAG);
3499   }
3500   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3501   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3502   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3503   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3504   case ISD::INSERT_VECTOR_ELT:
3505     return lowerINSERT_VECTOR_ELT(Op, DAG);
3506   case ISD::EXTRACT_VECTOR_ELT:
3507     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3508   case ISD::FP_ROUND:
3509     return lowerFP_ROUND(Op, DAG);
3510   case ISD::TRAP:
3511   case ISD::DEBUGTRAP:
3512     return lowerTRAP(Op, DAG);
3513   }
3514   return SDValue();
3515 }
3516 
3517 static unsigned getImageOpcode(unsigned IID) {
3518   switch (IID) {
3519   case Intrinsic::amdgcn_image_load:
3520     return AMDGPUISD::IMAGE_LOAD;
3521   case Intrinsic::amdgcn_image_load_mip:
3522     return AMDGPUISD::IMAGE_LOAD_MIP;
3523 
3524   // Basic sample.
3525   case Intrinsic::amdgcn_image_sample:
3526     return AMDGPUISD::IMAGE_SAMPLE;
3527   case Intrinsic::amdgcn_image_sample_cl:
3528     return AMDGPUISD::IMAGE_SAMPLE_CL;
3529   case Intrinsic::amdgcn_image_sample_d:
3530     return AMDGPUISD::IMAGE_SAMPLE_D;
3531   case Intrinsic::amdgcn_image_sample_d_cl:
3532     return AMDGPUISD::IMAGE_SAMPLE_D_CL;
3533   case Intrinsic::amdgcn_image_sample_l:
3534     return AMDGPUISD::IMAGE_SAMPLE_L;
3535   case Intrinsic::amdgcn_image_sample_b:
3536     return AMDGPUISD::IMAGE_SAMPLE_B;
3537   case Intrinsic::amdgcn_image_sample_b_cl:
3538     return AMDGPUISD::IMAGE_SAMPLE_B_CL;
3539   case Intrinsic::amdgcn_image_sample_lz:
3540     return AMDGPUISD::IMAGE_SAMPLE_LZ;
3541   case Intrinsic::amdgcn_image_sample_cd:
3542     return AMDGPUISD::IMAGE_SAMPLE_CD;
3543   case Intrinsic::amdgcn_image_sample_cd_cl:
3544     return AMDGPUISD::IMAGE_SAMPLE_CD_CL;
3545 
3546   // Sample with comparison.
3547   case Intrinsic::amdgcn_image_sample_c:
3548     return AMDGPUISD::IMAGE_SAMPLE_C;
3549   case Intrinsic::amdgcn_image_sample_c_cl:
3550     return AMDGPUISD::IMAGE_SAMPLE_C_CL;
3551   case Intrinsic::amdgcn_image_sample_c_d:
3552     return AMDGPUISD::IMAGE_SAMPLE_C_D;
3553   case Intrinsic::amdgcn_image_sample_c_d_cl:
3554     return AMDGPUISD::IMAGE_SAMPLE_C_D_CL;
3555   case Intrinsic::amdgcn_image_sample_c_l:
3556     return AMDGPUISD::IMAGE_SAMPLE_C_L;
3557   case Intrinsic::amdgcn_image_sample_c_b:
3558     return AMDGPUISD::IMAGE_SAMPLE_C_B;
3559   case Intrinsic::amdgcn_image_sample_c_b_cl:
3560     return AMDGPUISD::IMAGE_SAMPLE_C_B_CL;
3561   case Intrinsic::amdgcn_image_sample_c_lz:
3562     return AMDGPUISD::IMAGE_SAMPLE_C_LZ;
3563   case Intrinsic::amdgcn_image_sample_c_cd:
3564     return AMDGPUISD::IMAGE_SAMPLE_C_CD;
3565   case Intrinsic::amdgcn_image_sample_c_cd_cl:
3566     return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL;
3567 
3568   // Sample with offsets.
3569   case Intrinsic::amdgcn_image_sample_o:
3570     return AMDGPUISD::IMAGE_SAMPLE_O;
3571   case Intrinsic::amdgcn_image_sample_cl_o:
3572     return AMDGPUISD::IMAGE_SAMPLE_CL_O;
3573   case Intrinsic::amdgcn_image_sample_d_o:
3574     return AMDGPUISD::IMAGE_SAMPLE_D_O;
3575   case Intrinsic::amdgcn_image_sample_d_cl_o:
3576     return AMDGPUISD::IMAGE_SAMPLE_D_CL_O;
3577   case Intrinsic::amdgcn_image_sample_l_o:
3578     return AMDGPUISD::IMAGE_SAMPLE_L_O;
3579   case Intrinsic::amdgcn_image_sample_b_o:
3580     return AMDGPUISD::IMAGE_SAMPLE_B_O;
3581   case Intrinsic::amdgcn_image_sample_b_cl_o:
3582     return AMDGPUISD::IMAGE_SAMPLE_B_CL_O;
3583   case Intrinsic::amdgcn_image_sample_lz_o:
3584     return AMDGPUISD::IMAGE_SAMPLE_LZ_O;
3585   case Intrinsic::amdgcn_image_sample_cd_o:
3586     return AMDGPUISD::IMAGE_SAMPLE_CD_O;
3587   case Intrinsic::amdgcn_image_sample_cd_cl_o:
3588     return AMDGPUISD::IMAGE_SAMPLE_CD_CL_O;
3589 
3590   // Sample with comparison and offsets.
3591   case Intrinsic::amdgcn_image_sample_c_o:
3592     return AMDGPUISD::IMAGE_SAMPLE_C_O;
3593   case Intrinsic::amdgcn_image_sample_c_cl_o:
3594     return AMDGPUISD::IMAGE_SAMPLE_C_CL_O;
3595   case Intrinsic::amdgcn_image_sample_c_d_o:
3596     return AMDGPUISD::IMAGE_SAMPLE_C_D_O;
3597   case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3598     return AMDGPUISD::IMAGE_SAMPLE_C_D_CL_O;
3599   case Intrinsic::amdgcn_image_sample_c_l_o:
3600     return AMDGPUISD::IMAGE_SAMPLE_C_L_O;
3601   case Intrinsic::amdgcn_image_sample_c_b_o:
3602     return AMDGPUISD::IMAGE_SAMPLE_C_B_O;
3603   case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3604     return AMDGPUISD::IMAGE_SAMPLE_C_B_CL_O;
3605   case Intrinsic::amdgcn_image_sample_c_lz_o:
3606     return AMDGPUISD::IMAGE_SAMPLE_C_LZ_O;
3607   case Intrinsic::amdgcn_image_sample_c_cd_o:
3608     return AMDGPUISD::IMAGE_SAMPLE_C_CD_O;
3609   case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3610     return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL_O;
3611 
3612   // Basic gather4.
3613   case Intrinsic::amdgcn_image_gather4:
3614     return AMDGPUISD::IMAGE_GATHER4;
3615   case Intrinsic::amdgcn_image_gather4_cl:
3616     return AMDGPUISD::IMAGE_GATHER4_CL;
3617   case Intrinsic::amdgcn_image_gather4_l:
3618     return AMDGPUISD::IMAGE_GATHER4_L;
3619   case Intrinsic::amdgcn_image_gather4_b:
3620     return AMDGPUISD::IMAGE_GATHER4_B;
3621   case Intrinsic::amdgcn_image_gather4_b_cl:
3622     return AMDGPUISD::IMAGE_GATHER4_B_CL;
3623   case Intrinsic::amdgcn_image_gather4_lz:
3624     return AMDGPUISD::IMAGE_GATHER4_LZ;
3625 
3626   // Gather4 with comparison.
3627   case Intrinsic::amdgcn_image_gather4_c:
3628     return AMDGPUISD::IMAGE_GATHER4_C;
3629   case Intrinsic::amdgcn_image_gather4_c_cl:
3630     return AMDGPUISD::IMAGE_GATHER4_C_CL;
3631   case Intrinsic::amdgcn_image_gather4_c_l:
3632     return AMDGPUISD::IMAGE_GATHER4_C_L;
3633   case Intrinsic::amdgcn_image_gather4_c_b:
3634     return AMDGPUISD::IMAGE_GATHER4_C_B;
3635   case Intrinsic::amdgcn_image_gather4_c_b_cl:
3636     return AMDGPUISD::IMAGE_GATHER4_C_B_CL;
3637   case Intrinsic::amdgcn_image_gather4_c_lz:
3638     return AMDGPUISD::IMAGE_GATHER4_C_LZ;
3639 
3640   // Gather4 with offsets.
3641   case Intrinsic::amdgcn_image_gather4_o:
3642     return AMDGPUISD::IMAGE_GATHER4_O;
3643   case Intrinsic::amdgcn_image_gather4_cl_o:
3644     return AMDGPUISD::IMAGE_GATHER4_CL_O;
3645   case Intrinsic::amdgcn_image_gather4_l_o:
3646     return AMDGPUISD::IMAGE_GATHER4_L_O;
3647   case Intrinsic::amdgcn_image_gather4_b_o:
3648     return AMDGPUISD::IMAGE_GATHER4_B_O;
3649   case Intrinsic::amdgcn_image_gather4_b_cl_o:
3650     return AMDGPUISD::IMAGE_GATHER4_B_CL_O;
3651   case Intrinsic::amdgcn_image_gather4_lz_o:
3652     return AMDGPUISD::IMAGE_GATHER4_LZ_O;
3653 
3654   // Gather4 with comparison and offsets.
3655   case Intrinsic::amdgcn_image_gather4_c_o:
3656     return AMDGPUISD::IMAGE_GATHER4_C_O;
3657   case Intrinsic::amdgcn_image_gather4_c_cl_o:
3658     return AMDGPUISD::IMAGE_GATHER4_C_CL_O;
3659   case Intrinsic::amdgcn_image_gather4_c_l_o:
3660     return AMDGPUISD::IMAGE_GATHER4_C_L_O;
3661   case Intrinsic::amdgcn_image_gather4_c_b_o:
3662     return AMDGPUISD::IMAGE_GATHER4_C_B_O;
3663   case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
3664     return AMDGPUISD::IMAGE_GATHER4_C_B_CL_O;
3665   case Intrinsic::amdgcn_image_gather4_c_lz_o:
3666     return AMDGPUISD::IMAGE_GATHER4_C_LZ_O;
3667 
3668   default:
3669     break;
3670   }
3671   return 0;
3672 }
3673 
3674 static SDValue adjustLoadValueType(SDValue Result, EVT LoadVT, SDLoc DL,
3675                                    SelectionDAG &DAG, bool Unpacked) {
3676   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3677     // Truncate to v2i16/v4i16.
3678     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3679     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntLoadVT, Result);
3680     // Bitcast to original type (v2f16/v4f16).
3681     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc);
3682   }
3683   // Cast back to the original packed type.
3684   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3685 }
3686 
3687 // This is to lower INTRINSIC_W_CHAIN with illegal result types.
3688 SDValue SITargetLowering::lowerIntrinsicWChain_IllegalReturnType(SDValue Op,
3689                                      SDValue &Chain, SelectionDAG &DAG) const {
3690   EVT LoadVT = Op.getValueType();
3691   // TODO: handle v3f16.
3692   if (LoadVT != MVT::v2f16 && LoadVT != MVT::v4f16)
3693     return SDValue();
3694 
3695   bool Unpacked = Subtarget->hasUnpackedD16VMem();
3696   EVT UnpackedLoadVT = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
3697   EVT EquivLoadVT = Unpacked ? UnpackedLoadVT :
3698                                getEquivalentMemType(*DAG.getContext(), LoadVT);
3699   // Change from v4f16/v2f16 to EquivLoadVT.
3700   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3701 
3702   SDValue Res;
3703   SDLoc DL(Op);
3704   MemSDNode *M = cast<MemSDNode>(Op);
3705   unsigned IID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
3706   switch (IID) {
3707   case Intrinsic::amdgcn_tbuffer_load: {
3708     SDValue Ops[] = {
3709       Op.getOperand(0),  // Chain
3710       Op.getOperand(2),  // rsrc
3711       Op.getOperand(3),  // vindex
3712       Op.getOperand(4),  // voffset
3713       Op.getOperand(5),  // soffset
3714       Op.getOperand(6),  // offset
3715       Op.getOperand(7),  // dfmt
3716       Op.getOperand(8),  // nfmt
3717       Op.getOperand(9),  // glc
3718       Op.getOperand(10)  // slc
3719     };
3720     Res = DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, DL,
3721                                   VTList, Ops, M->getMemoryVT(),
3722                                   M->getMemOperand());
3723     Chain = Res.getValue(1);
3724     return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3725   }
3726   case Intrinsic::amdgcn_buffer_load_format: {
3727     SDValue Ops[] = {
3728       Op.getOperand(0), // Chain
3729       Op.getOperand(2), // rsrc
3730       Op.getOperand(3), // vindex
3731       Op.getOperand(4), // offset
3732       Op.getOperand(5), // glc
3733       Op.getOperand(6)  // slc
3734     };
3735     Res = DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
3736                                    DL, VTList, Ops, M->getMemoryVT(),
3737                                    M->getMemOperand());
3738     Chain = Res.getValue(1);
3739     return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3740   }
3741   case Intrinsic::amdgcn_image_load:
3742   case Intrinsic::amdgcn_image_load_mip: {
3743     SDValue Ops[] = {
3744         Op.getOperand(0),  // Chain
3745         Op.getOperand(2),  // vaddr
3746         Op.getOperand(3),  // rsrc
3747         Op.getOperand(4),  // dmask
3748         Op.getOperand(5),  // glc
3749         Op.getOperand(6),  // slc
3750         Op.getOperand(7),  // lwe
3751         Op.getOperand(8)   // da
3752     };
3753     unsigned Opc = getImageOpcode(IID);
3754     Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(),
3755                                   M->getMemOperand());
3756     Chain = Res.getValue(1);
3757     return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3758   }
3759   // Basic sample.
3760   case Intrinsic::amdgcn_image_sample:
3761   case Intrinsic::amdgcn_image_sample_cl:
3762   case Intrinsic::amdgcn_image_sample_d:
3763   case Intrinsic::amdgcn_image_sample_d_cl:
3764   case Intrinsic::amdgcn_image_sample_l:
3765   case Intrinsic::amdgcn_image_sample_b:
3766   case Intrinsic::amdgcn_image_sample_b_cl:
3767   case Intrinsic::amdgcn_image_sample_lz:
3768   case Intrinsic::amdgcn_image_sample_cd:
3769   case Intrinsic::amdgcn_image_sample_cd_cl:
3770 
3771   // Sample with comparison.
3772   case Intrinsic::amdgcn_image_sample_c:
3773   case Intrinsic::amdgcn_image_sample_c_cl:
3774   case Intrinsic::amdgcn_image_sample_c_d:
3775   case Intrinsic::amdgcn_image_sample_c_d_cl:
3776   case Intrinsic::amdgcn_image_sample_c_l:
3777   case Intrinsic::amdgcn_image_sample_c_b:
3778   case Intrinsic::amdgcn_image_sample_c_b_cl:
3779   case Intrinsic::amdgcn_image_sample_c_lz:
3780   case Intrinsic::amdgcn_image_sample_c_cd:
3781   case Intrinsic::amdgcn_image_sample_c_cd_cl:
3782 
3783   // Sample with offsets.
3784   case Intrinsic::amdgcn_image_sample_o:
3785   case Intrinsic::amdgcn_image_sample_cl_o:
3786   case Intrinsic::amdgcn_image_sample_d_o:
3787   case Intrinsic::amdgcn_image_sample_d_cl_o:
3788   case Intrinsic::amdgcn_image_sample_l_o:
3789   case Intrinsic::amdgcn_image_sample_b_o:
3790   case Intrinsic::amdgcn_image_sample_b_cl_o:
3791   case Intrinsic::amdgcn_image_sample_lz_o:
3792   case Intrinsic::amdgcn_image_sample_cd_o:
3793   case Intrinsic::amdgcn_image_sample_cd_cl_o:
3794 
3795   // Sample with comparison and offsets.
3796   case Intrinsic::amdgcn_image_sample_c_o:
3797   case Intrinsic::amdgcn_image_sample_c_cl_o:
3798   case Intrinsic::amdgcn_image_sample_c_d_o:
3799   case Intrinsic::amdgcn_image_sample_c_d_cl_o:
3800   case Intrinsic::amdgcn_image_sample_c_l_o:
3801   case Intrinsic::amdgcn_image_sample_c_b_o:
3802   case Intrinsic::amdgcn_image_sample_c_b_cl_o:
3803   case Intrinsic::amdgcn_image_sample_c_lz_o:
3804   case Intrinsic::amdgcn_image_sample_c_cd_o:
3805   case Intrinsic::amdgcn_image_sample_c_cd_cl_o:
3806 
3807   // Basic gather4
3808   case Intrinsic::amdgcn_image_gather4:
3809   case Intrinsic::amdgcn_image_gather4_cl:
3810   case Intrinsic::amdgcn_image_gather4_l:
3811   case Intrinsic::amdgcn_image_gather4_b:
3812   case Intrinsic::amdgcn_image_gather4_b_cl:
3813   case Intrinsic::amdgcn_image_gather4_lz:
3814 
3815   // Gather4 with comparison
3816   case Intrinsic::amdgcn_image_gather4_c:
3817   case Intrinsic::amdgcn_image_gather4_c_cl:
3818   case Intrinsic::amdgcn_image_gather4_c_l:
3819   case Intrinsic::amdgcn_image_gather4_c_b:
3820   case Intrinsic::amdgcn_image_gather4_c_b_cl:
3821   case Intrinsic::amdgcn_image_gather4_c_lz:
3822 
3823   // Gather4 with offsets
3824   case Intrinsic::amdgcn_image_gather4_o:
3825   case Intrinsic::amdgcn_image_gather4_cl_o:
3826   case Intrinsic::amdgcn_image_gather4_l_o:
3827   case Intrinsic::amdgcn_image_gather4_b_o:
3828   case Intrinsic::amdgcn_image_gather4_b_cl_o:
3829   case Intrinsic::amdgcn_image_gather4_lz_o:
3830 
3831   // Gather4 with comparison and offsets
3832   case Intrinsic::amdgcn_image_gather4_c_o:
3833   case Intrinsic::amdgcn_image_gather4_c_cl_o:
3834   case Intrinsic::amdgcn_image_gather4_c_l_o:
3835   case Intrinsic::amdgcn_image_gather4_c_b_o:
3836   case Intrinsic::amdgcn_image_gather4_c_b_cl_o:
3837   case Intrinsic::amdgcn_image_gather4_c_lz_o: {
3838     SDValue Ops[] = {
3839       Op.getOperand(0),  // Chain
3840       Op.getOperand(2),  // vaddr
3841       Op.getOperand(3),  // rsrc
3842       Op.getOperand(4),  // sampler
3843       Op.getOperand(5),  // dmask
3844       Op.getOperand(6),  // unorm
3845       Op.getOperand(7),  // glc
3846       Op.getOperand(8),  // slc
3847       Op.getOperand(9),  // lwe
3848       Op.getOperand(10)  // da
3849     };
3850     unsigned Opc = getImageOpcode(IID);
3851     Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(),
3852                                    M->getMemOperand());
3853     Chain = Res.getValue(1);
3854     return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked);
3855   }
3856   default:
3857     return SDValue();
3858   }
3859 }
3860 
3861 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3862                                           SmallVectorImpl<SDValue> &Results,
3863                                           SelectionDAG &DAG) const {
3864   switch (N->getOpcode()) {
3865   case ISD::INSERT_VECTOR_ELT: {
3866     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3867       Results.push_back(Res);
3868     return;
3869   }
3870   case ISD::EXTRACT_VECTOR_ELT: {
3871     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3872       Results.push_back(Res);
3873     return;
3874   }
3875   case ISD::INTRINSIC_WO_CHAIN: {
3876     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3877     switch (IID) {
3878     case Intrinsic::amdgcn_cvt_pkrtz: {
3879       SDValue Src0 = N->getOperand(1);
3880       SDValue Src1 = N->getOperand(2);
3881       SDLoc SL(N);
3882       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3883                                 Src0, Src1);
3884       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3885       return;
3886     }
3887     case Intrinsic::amdgcn_cvt_pknorm_i16:
3888     case Intrinsic::amdgcn_cvt_pknorm_u16:
3889     case Intrinsic::amdgcn_cvt_pk_i16:
3890     case Intrinsic::amdgcn_cvt_pk_u16: {
3891       SDValue Src0 = N->getOperand(1);
3892       SDValue Src1 = N->getOperand(2);
3893       SDLoc SL(N);
3894       unsigned Opcode;
3895 
3896       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3897         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3898       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3899         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3900       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3901         Opcode = AMDGPUISD::CVT_PK_I16_I32;
3902       else
3903         Opcode = AMDGPUISD::CVT_PK_U16_U32;
3904 
3905       SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3906       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3907       return;
3908     }
3909     }
3910     break;
3911   }
3912   case ISD::INTRINSIC_W_CHAIN: {
3913     SDValue Chain;
3914     if (SDValue Res = lowerIntrinsicWChain_IllegalReturnType(SDValue(N, 0),
3915                                                              Chain, DAG)) {
3916       Results.push_back(Res);
3917       Results.push_back(Chain);
3918       return;
3919     }
3920     break;
3921   }
3922   case ISD::SELECT: {
3923     SDLoc SL(N);
3924     EVT VT = N->getValueType(0);
3925     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3926     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3927     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3928 
3929     EVT SelectVT = NewVT;
3930     if (NewVT.bitsLT(MVT::i32)) {
3931       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3932       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3933       SelectVT = MVT::i32;
3934     }
3935 
3936     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3937                                     N->getOperand(0), LHS, RHS);
3938 
3939     if (NewVT != SelectVT)
3940       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3941     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3942     return;
3943   }
3944   default:
3945     break;
3946   }
3947 }
3948 
3949 /// \brief Helper function for LowerBRCOND
3950 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3951 
3952   SDNode *Parent = Value.getNode();
3953   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3954        I != E; ++I) {
3955 
3956     if (I.getUse().get() != Value)
3957       continue;
3958 
3959     if (I->getOpcode() == Opcode)
3960       return *I;
3961   }
3962   return nullptr;
3963 }
3964 
3965 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3966   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3967     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3968     case Intrinsic::amdgcn_if:
3969       return AMDGPUISD::IF;
3970     case Intrinsic::amdgcn_else:
3971       return AMDGPUISD::ELSE;
3972     case Intrinsic::amdgcn_loop:
3973       return AMDGPUISD::LOOP;
3974     case Intrinsic::amdgcn_end_cf:
3975       llvm_unreachable("should not occur");
3976     default:
3977       return 0;
3978     }
3979   }
3980 
3981   // break, if_break, else_break are all only used as inputs to loop, not
3982   // directly as branch conditions.
3983   return 0;
3984 }
3985 
3986 void SITargetLowering::createDebuggerPrologueStackObjects(
3987     MachineFunction &MF) const {
3988   // Create stack objects that are used for emitting debugger prologue.
3989   //
3990   // Debugger prologue writes work group IDs and work item IDs to scratch memory
3991   // at fixed location in the following format:
3992   //   offset 0:  work group ID x
3993   //   offset 4:  work group ID y
3994   //   offset 8:  work group ID z
3995   //   offset 16: work item ID x
3996   //   offset 20: work item ID y
3997   //   offset 24: work item ID z
3998   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3999   int ObjectIdx = 0;
4000 
4001   // For each dimension:
4002   for (unsigned i = 0; i < 3; ++i) {
4003     // Create fixed stack object for work group ID.
4004     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
4005     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
4006     // Create fixed stack object for work item ID.
4007     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
4008     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
4009   }
4010 }
4011 
4012 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4013   const Triple &TT = getTargetMachine().getTargetTriple();
4014   return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4015           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4016          AMDGPU::shouldEmitConstantsToTextSection(TT);
4017 }
4018 
4019 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4020   return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4021           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4022           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4023          !shouldEmitFixup(GV) &&
4024          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4025 }
4026 
4027 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4028   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4029 }
4030 
4031 /// This transforms the control flow intrinsics to get the branch destination as
4032 /// last parameter, also switches branch target with BR if the need arise
4033 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4034                                       SelectionDAG &DAG) const {
4035   SDLoc DL(BRCOND);
4036 
4037   SDNode *Intr = BRCOND.getOperand(1).getNode();
4038   SDValue Target = BRCOND.getOperand(2);
4039   SDNode *BR = nullptr;
4040   SDNode *SetCC = nullptr;
4041 
4042   if (Intr->getOpcode() == ISD::SETCC) {
4043     // As long as we negate the condition everything is fine
4044     SetCC = Intr;
4045     Intr = SetCC->getOperand(0).getNode();
4046 
4047   } else {
4048     // Get the target from BR if we don't negate the condition
4049     BR = findUser(BRCOND, ISD::BR);
4050     Target = BR->getOperand(1);
4051   }
4052 
4053   // FIXME: This changes the types of the intrinsics instead of introducing new
4054   // nodes with the correct types.
4055   // e.g. llvm.amdgcn.loop
4056 
4057   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4058   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4059 
4060   unsigned CFNode = isCFIntrinsic(Intr);
4061   if (CFNode == 0) {
4062     // This is a uniform branch so we don't need to legalize.
4063     return BRCOND;
4064   }
4065 
4066   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4067                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4068 
4069   assert(!SetCC ||
4070         (SetCC->getConstantOperandVal(1) == 1 &&
4071          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4072                                                              ISD::SETNE));
4073 
4074   // operands of the new intrinsic call
4075   SmallVector<SDValue, 4> Ops;
4076   if (HaveChain)
4077     Ops.push_back(BRCOND.getOperand(0));
4078 
4079   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4080   Ops.push_back(Target);
4081 
4082   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4083 
4084   // build the new intrinsic call
4085   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4086 
4087   if (!HaveChain) {
4088     SDValue Ops[] =  {
4089       SDValue(Result, 0),
4090       BRCOND.getOperand(0)
4091     };
4092 
4093     Result = DAG.getMergeValues(Ops, DL).getNode();
4094   }
4095 
4096   if (BR) {
4097     // Give the branch instruction our target
4098     SDValue Ops[] = {
4099       BR->getOperand(0),
4100       BRCOND.getOperand(2)
4101     };
4102     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4103     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4104     BR = NewBR.getNode();
4105   }
4106 
4107   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4108 
4109   // Copy the intrinsic results to registers
4110   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4111     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4112     if (!CopyToReg)
4113       continue;
4114 
4115     Chain = DAG.getCopyToReg(
4116       Chain, DL,
4117       CopyToReg->getOperand(1),
4118       SDValue(Result, i - 1),
4119       SDValue());
4120 
4121     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4122   }
4123 
4124   // Remove the old intrinsic from the chain
4125   DAG.ReplaceAllUsesOfValueWith(
4126     SDValue(Intr, Intr->getNumValues() - 1),
4127     Intr->getOperand(0));
4128 
4129   return Chain;
4130 }
4131 
4132 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4133                                             SDValue Op,
4134                                             const SDLoc &DL,
4135                                             EVT VT) const {
4136   return Op.getValueType().bitsLE(VT) ?
4137       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4138       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4139 }
4140 
4141 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4142   assert(Op.getValueType() == MVT::f16 &&
4143          "Do not know how to custom lower FP_ROUND for non-f16 type");
4144 
4145   SDValue Src = Op.getOperand(0);
4146   EVT SrcVT = Src.getValueType();
4147   if (SrcVT != MVT::f64)
4148     return Op;
4149 
4150   SDLoc DL(Op);
4151 
4152   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4153   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4154   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4155 }
4156 
4157 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4158   SDLoc SL(Op);
4159   MachineFunction &MF = DAG.getMachineFunction();
4160   SDValue Chain = Op.getOperand(0);
4161 
4162   unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ?
4163     SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap;
4164 
4165   if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa &&
4166       Subtarget->isTrapHandlerEnabled()) {
4167     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4168     unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4169     assert(UserSGPR != AMDGPU::NoRegister);
4170 
4171     SDValue QueuePtr = CreateLiveInRegister(
4172       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4173 
4174     SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4175 
4176     SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4177                                      QueuePtr, SDValue());
4178 
4179     SDValue Ops[] = {
4180       ToReg,
4181       DAG.getTargetConstant(TrapID, SL, MVT::i16),
4182       SGPR01,
4183       ToReg.getValue(1)
4184     };
4185 
4186     return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4187   }
4188 
4189   switch (TrapID) {
4190   case SISubtarget::TrapIDLLVMTrap:
4191     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4192   case SISubtarget::TrapIDLLVMDebugTrap: {
4193     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4194                                      "debugtrap handler not supported",
4195                                      Op.getDebugLoc(),
4196                                      DS_Warning);
4197     LLVMContext &Ctx = MF.getFunction().getContext();
4198     Ctx.diagnose(NoTrap);
4199     return Chain;
4200   }
4201   default:
4202     llvm_unreachable("unsupported trap handler type!");
4203   }
4204 
4205   return Chain;
4206 }
4207 
4208 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4209                                              SelectionDAG &DAG) const {
4210   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4211   if (Subtarget->hasApertureRegs()) {
4212     unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
4213         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4214         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4215     unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
4216         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4217         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4218     unsigned Encoding =
4219         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4220         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4221         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4222 
4223     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4224     SDValue ApertureReg = SDValue(
4225         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4226     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4227     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4228   }
4229 
4230   MachineFunction &MF = DAG.getMachineFunction();
4231   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4232   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4233   assert(UserSGPR != AMDGPU::NoRegister);
4234 
4235   SDValue QueuePtr = CreateLiveInRegister(
4236     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4237 
4238   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4239   // private_segment_aperture_base_hi.
4240   uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
4241 
4242   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4243 
4244   // TODO: Use custom target PseudoSourceValue.
4245   // TODO: We should use the value from the IR intrinsic call, but it might not
4246   // be available and how do we get it?
4247   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4248                                               AMDGPUASI.CONSTANT_ADDRESS));
4249 
4250   MachinePointerInfo PtrInfo(V, StructOffset);
4251   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4252                      MinAlign(64, StructOffset),
4253                      MachineMemOperand::MODereferenceable |
4254                          MachineMemOperand::MOInvariant);
4255 }
4256 
4257 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4258                                              SelectionDAG &DAG) const {
4259   SDLoc SL(Op);
4260   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4261 
4262   SDValue Src = ASC->getOperand(0);
4263   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4264 
4265   const AMDGPUTargetMachine &TM =
4266     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4267 
4268   // flat -> local/private
4269   if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4270     unsigned DestAS = ASC->getDestAddressSpace();
4271 
4272     if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4273         DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4274       unsigned NullVal = TM.getNullPointerValue(DestAS);
4275       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4276       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4277       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4278 
4279       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4280                          NonNull, Ptr, SegmentNullPtr);
4281     }
4282   }
4283 
4284   // local/private -> flat
4285   if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4286     unsigned SrcAS = ASC->getSrcAddressSpace();
4287 
4288     if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4289         SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4290       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4291       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4292 
4293       SDValue NonNull
4294         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4295 
4296       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4297       SDValue CvtPtr
4298         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4299 
4300       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4301                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4302                          FlatNullPtr);
4303     }
4304   }
4305 
4306   // global <-> flat are no-ops and never emitted.
4307 
4308   const MachineFunction &MF = DAG.getMachineFunction();
4309   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4310     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4311   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4312 
4313   return DAG.getUNDEF(ASC->getValueType(0));
4314 }
4315 
4316 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4317                                                  SelectionDAG &DAG) const {
4318   SDValue Idx = Op.getOperand(2);
4319   if (isa<ConstantSDNode>(Idx))
4320     return SDValue();
4321 
4322   // Avoid stack access for dynamic indexing.
4323   SDLoc SL(Op);
4324   SDValue Vec = Op.getOperand(0);
4325   SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1));
4326 
4327   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4328   SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val);
4329 
4330   // Convert vector index to bit-index.
4331   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx,
4332                                   DAG.getConstant(16, SL, MVT::i32));
4333 
4334   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4335 
4336   SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32,
4337                             DAG.getConstant(0xffff, SL, MVT::i32),
4338                             ScaledIdx);
4339 
4340   SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal);
4341   SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32,
4342                             DAG.getNOT(SL, BFM, MVT::i32), BCVec);
4343 
4344   SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS);
4345   return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI);
4346 }
4347 
4348 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4349                                                   SelectionDAG &DAG) const {
4350   SDLoc SL(Op);
4351 
4352   EVT ResultVT = Op.getValueType();
4353   SDValue Vec = Op.getOperand(0);
4354   SDValue Idx = Op.getOperand(1);
4355 
4356   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4357 
4358   // Make sure we we do any optimizations that will make it easier to fold
4359   // source modifiers before obscuring it with bit operations.
4360 
4361   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4362   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4363     return Combined;
4364 
4365   if (const ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
4366     SDValue Result = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4367 
4368     if (CIdx->getZExtValue() == 1) {
4369       Result = DAG.getNode(ISD::SRL, SL, MVT::i32, Result,
4370                            DAG.getConstant(16, SL, MVT::i32));
4371     } else {
4372       assert(CIdx->getZExtValue() == 0);
4373     }
4374 
4375     if (ResultVT.bitsLT(MVT::i32))
4376       Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
4377     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4378   }
4379 
4380   SDValue Sixteen = DAG.getConstant(16, SL, MVT::i32);
4381 
4382   // Convert vector index to bit-index.
4383   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Sixteen);
4384 
4385   SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
4386   SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx);
4387 
4388   SDValue Result = Elt;
4389   if (ResultVT.bitsLT(MVT::i32))
4390     Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result);
4391 
4392   return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4393 }
4394 
4395 bool
4396 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4397   // We can fold offsets for anything that doesn't require a GOT relocation.
4398   return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4399           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4400           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4401          !shouldEmitGOTReloc(GA->getGlobal());
4402 }
4403 
4404 static SDValue
4405 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4406                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4407                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4408   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4409   // lowered to the following code sequence:
4410   //
4411   // For constant address space:
4412   //   s_getpc_b64 s[0:1]
4413   //   s_add_u32 s0, s0, $symbol
4414   //   s_addc_u32 s1, s1, 0
4415   //
4416   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4417   //   a fixup or relocation is emitted to replace $symbol with a literal
4418   //   constant, which is a pc-relative offset from the encoding of the $symbol
4419   //   operand to the global variable.
4420   //
4421   // For global address space:
4422   //   s_getpc_b64 s[0:1]
4423   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4424   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4425   //
4426   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4427   //   fixups or relocations are emitted to replace $symbol@*@lo and
4428   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4429   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4430   //   operand to the global variable.
4431   //
4432   // What we want here is an offset from the value returned by s_getpc
4433   // (which is the address of the s_add_u32 instruction) to the global
4434   // variable, but since the encoding of $symbol starts 4 bytes after the start
4435   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4436   // small. This requires us to add 4 to the global variable offset in order to
4437   // compute the correct address.
4438   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4439                                              GAFlags);
4440   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4441                                              GAFlags == SIInstrInfo::MO_NONE ?
4442                                              GAFlags : GAFlags + 1);
4443   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4444 }
4445 
4446 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4447                                              SDValue Op,
4448                                              SelectionDAG &DAG) const {
4449   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4450   const GlobalValue *GV = GSD->getGlobal();
4451 
4452   if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4453       GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4454       GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4455       // FIXME: It isn't correct to rely on the type of the pointer. This should
4456       // be removed when address space 0 is 64-bit.
4457       !GV->getType()->getElementType()->isFunctionTy())
4458     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4459 
4460   SDLoc DL(GSD);
4461   EVT PtrVT = Op.getValueType();
4462 
4463   if (shouldEmitFixup(GV))
4464     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4465   else if (shouldEmitPCReloc(GV))
4466     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4467                                    SIInstrInfo::MO_REL32);
4468 
4469   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4470                                             SIInstrInfo::MO_GOTPCREL32);
4471 
4472   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4473   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4474   const DataLayout &DataLayout = DAG.getDataLayout();
4475   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4476   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4477   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4478 
4479   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4480                      MachineMemOperand::MODereferenceable |
4481                          MachineMemOperand::MOInvariant);
4482 }
4483 
4484 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4485                                    const SDLoc &DL, SDValue V) const {
4486   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4487   // the destination register.
4488   //
4489   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4490   // so we will end up with redundant moves to m0.
4491   //
4492   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4493 
4494   // A Null SDValue creates a glue result.
4495   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4496                                   V, Chain);
4497   return SDValue(M0, 0);
4498 }
4499 
4500 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4501                                                  SDValue Op,
4502                                                  MVT VT,
4503                                                  unsigned Offset) const {
4504   SDLoc SL(Op);
4505   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4506                                            DAG.getEntryNode(), Offset, false);
4507   // The local size values will have the hi 16-bits as zero.
4508   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4509                      DAG.getValueType(VT));
4510 }
4511 
4512 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4513                                         EVT VT) {
4514   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4515                                       "non-hsa intrinsic with hsa target",
4516                                       DL.getDebugLoc());
4517   DAG.getContext()->diagnose(BadIntrin);
4518   return DAG.getUNDEF(VT);
4519 }
4520 
4521 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4522                                          EVT VT) {
4523   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4524                                       "intrinsic not supported on subtarget",
4525                                       DL.getDebugLoc());
4526   DAG.getContext()->diagnose(BadIntrin);
4527   return DAG.getUNDEF(VT);
4528 }
4529 
4530 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4531                                                   SelectionDAG &DAG) const {
4532   MachineFunction &MF = DAG.getMachineFunction();
4533   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4534 
4535   EVT VT = Op.getValueType();
4536   SDLoc DL(Op);
4537   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4538 
4539   // TODO: Should this propagate fast-math-flags?
4540 
4541   switch (IntrinsicID) {
4542   case Intrinsic::amdgcn_implicit_buffer_ptr: {
4543     if (getSubtarget()->isAmdCodeObjectV2(MF))
4544       return emitNonHSAIntrinsicError(DAG, DL, VT);
4545     return getPreloadedValue(DAG, *MFI, VT,
4546                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4547   }
4548   case Intrinsic::amdgcn_dispatch_ptr:
4549   case Intrinsic::amdgcn_queue_ptr: {
4550     if (!Subtarget->isAmdCodeObjectV2(MF)) {
4551       DiagnosticInfoUnsupported BadIntrin(
4552           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4553           DL.getDebugLoc());
4554       DAG.getContext()->diagnose(BadIntrin);
4555       return DAG.getUNDEF(VT);
4556     }
4557 
4558     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4559       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4560     return getPreloadedValue(DAG, *MFI, VT, RegID);
4561   }
4562   case Intrinsic::amdgcn_implicitarg_ptr: {
4563     if (MFI->isEntryFunction())
4564       return getImplicitArgPtr(DAG, DL);
4565     return getPreloadedValue(DAG, *MFI, VT,
4566                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4567   }
4568   case Intrinsic::amdgcn_kernarg_segment_ptr: {
4569     return getPreloadedValue(DAG, *MFI, VT,
4570                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4571   }
4572   case Intrinsic::amdgcn_dispatch_id: {
4573     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4574   }
4575   case Intrinsic::amdgcn_rcp:
4576     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4577   case Intrinsic::amdgcn_rsq:
4578     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4579   case Intrinsic::amdgcn_rsq_legacy:
4580     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4581       return emitRemovedIntrinsicError(DAG, DL, VT);
4582 
4583     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4584   case Intrinsic::amdgcn_rcp_legacy:
4585     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4586       return emitRemovedIntrinsicError(DAG, DL, VT);
4587     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4588   case Intrinsic::amdgcn_rsq_clamp: {
4589     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4590       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4591 
4592     Type *Type = VT.getTypeForEVT(*DAG.getContext());
4593     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4594     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4595 
4596     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4597     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4598                               DAG.getConstantFP(Max, DL, VT));
4599     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4600                        DAG.getConstantFP(Min, DL, VT));
4601   }
4602   case Intrinsic::r600_read_ngroups_x:
4603     if (Subtarget->isAmdHsaOS())
4604       return emitNonHSAIntrinsicError(DAG, DL, VT);
4605 
4606     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4607                                     SI::KernelInputOffsets::NGROUPS_X, false);
4608   case Intrinsic::r600_read_ngroups_y:
4609     if (Subtarget->isAmdHsaOS())
4610       return emitNonHSAIntrinsicError(DAG, DL, VT);
4611 
4612     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4613                                     SI::KernelInputOffsets::NGROUPS_Y, false);
4614   case Intrinsic::r600_read_ngroups_z:
4615     if (Subtarget->isAmdHsaOS())
4616       return emitNonHSAIntrinsicError(DAG, DL, VT);
4617 
4618     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4619                                     SI::KernelInputOffsets::NGROUPS_Z, false);
4620   case Intrinsic::r600_read_global_size_x:
4621     if (Subtarget->isAmdHsaOS())
4622       return emitNonHSAIntrinsicError(DAG, DL, VT);
4623 
4624     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4625                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, false);
4626   case Intrinsic::r600_read_global_size_y:
4627     if (Subtarget->isAmdHsaOS())
4628       return emitNonHSAIntrinsicError(DAG, DL, VT);
4629 
4630     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4631                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, false);
4632   case Intrinsic::r600_read_global_size_z:
4633     if (Subtarget->isAmdHsaOS())
4634       return emitNonHSAIntrinsicError(DAG, DL, VT);
4635 
4636     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4637                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, false);
4638   case Intrinsic::r600_read_local_size_x:
4639     if (Subtarget->isAmdHsaOS())
4640       return emitNonHSAIntrinsicError(DAG, DL, VT);
4641 
4642     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4643                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
4644   case Intrinsic::r600_read_local_size_y:
4645     if (Subtarget->isAmdHsaOS())
4646       return emitNonHSAIntrinsicError(DAG, DL, VT);
4647 
4648     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4649                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
4650   case Intrinsic::r600_read_local_size_z:
4651     if (Subtarget->isAmdHsaOS())
4652       return emitNonHSAIntrinsicError(DAG, DL, VT);
4653 
4654     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4655                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
4656   case Intrinsic::amdgcn_workgroup_id_x:
4657   case Intrinsic::r600_read_tgid_x:
4658     return getPreloadedValue(DAG, *MFI, VT,
4659                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4660   case Intrinsic::amdgcn_workgroup_id_y:
4661   case Intrinsic::r600_read_tgid_y:
4662     return getPreloadedValue(DAG, *MFI, VT,
4663                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4664   case Intrinsic::amdgcn_workgroup_id_z:
4665   case Intrinsic::r600_read_tgid_z:
4666     return getPreloadedValue(DAG, *MFI, VT,
4667                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4668   case Intrinsic::amdgcn_workitem_id_x: {
4669   case Intrinsic::r600_read_tidig_x:
4670     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4671                           SDLoc(DAG.getEntryNode()),
4672                           MFI->getArgInfo().WorkItemIDX);
4673   }
4674   case Intrinsic::amdgcn_workitem_id_y:
4675   case Intrinsic::r600_read_tidig_y:
4676     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4677                           SDLoc(DAG.getEntryNode()),
4678                           MFI->getArgInfo().WorkItemIDY);
4679   case Intrinsic::amdgcn_workitem_id_z:
4680   case Intrinsic::r600_read_tidig_z:
4681     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4682                           SDLoc(DAG.getEntryNode()),
4683                           MFI->getArgInfo().WorkItemIDZ);
4684   case AMDGPUIntrinsic::SI_load_const: {
4685     SDValue Ops[] = {
4686       Op.getOperand(1),
4687       Op.getOperand(2)
4688     };
4689 
4690     MachineMemOperand *MMO = MF.getMachineMemOperand(
4691         MachinePointerInfo(),
4692         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4693             MachineMemOperand::MOInvariant,
4694         VT.getStoreSize(), 4);
4695     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4696                                    Op->getVTList(), Ops, VT, MMO);
4697   }
4698   case Intrinsic::amdgcn_fdiv_fast:
4699     return lowerFDIV_FAST(Op, DAG);
4700   case Intrinsic::amdgcn_interp_mov: {
4701     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4702     SDValue Glue = M0.getValue(1);
4703     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4704                        Op.getOperand(2), Op.getOperand(3), Glue);
4705   }
4706   case Intrinsic::amdgcn_interp_p1: {
4707     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4708     SDValue Glue = M0.getValue(1);
4709     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4710                        Op.getOperand(2), Op.getOperand(3), Glue);
4711   }
4712   case Intrinsic::amdgcn_interp_p2: {
4713     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4714     SDValue Glue = SDValue(M0.getNode(), 1);
4715     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4716                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4717                        Glue);
4718   }
4719   case Intrinsic::amdgcn_sin:
4720     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4721 
4722   case Intrinsic::amdgcn_cos:
4723     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4724 
4725   case Intrinsic::amdgcn_log_clamp: {
4726     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4727       return SDValue();
4728 
4729     DiagnosticInfoUnsupported BadIntrin(
4730       MF.getFunction(), "intrinsic not supported on subtarget",
4731       DL.getDebugLoc());
4732       DAG.getContext()->diagnose(BadIntrin);
4733       return DAG.getUNDEF(VT);
4734   }
4735   case Intrinsic::amdgcn_ldexp:
4736     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4737                        Op.getOperand(1), Op.getOperand(2));
4738 
4739   case Intrinsic::amdgcn_fract:
4740     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4741 
4742   case Intrinsic::amdgcn_class:
4743     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4744                        Op.getOperand(1), Op.getOperand(2));
4745   case Intrinsic::amdgcn_div_fmas:
4746     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4747                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4748                        Op.getOperand(4));
4749 
4750   case Intrinsic::amdgcn_div_fixup:
4751     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4752                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4753 
4754   case Intrinsic::amdgcn_trig_preop:
4755     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4756                        Op.getOperand(1), Op.getOperand(2));
4757   case Intrinsic::amdgcn_div_scale: {
4758     // 3rd parameter required to be a constant.
4759     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4760     if (!Param)
4761       return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4762 
4763     // Translate to the operands expected by the machine instruction. The
4764     // first parameter must be the same as the first instruction.
4765     SDValue Numerator = Op.getOperand(1);
4766     SDValue Denominator = Op.getOperand(2);
4767 
4768     // Note this order is opposite of the machine instruction's operations,
4769     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4770     // intrinsic has the numerator as the first operand to match a normal
4771     // division operation.
4772 
4773     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4774 
4775     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4776                        Denominator, Numerator);
4777   }
4778   case Intrinsic::amdgcn_icmp: {
4779     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4780     if (!CD)
4781       return DAG.getUNDEF(VT);
4782 
4783     int CondCode = CD->getSExtValue();
4784     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4785         CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4786       return DAG.getUNDEF(VT);
4787 
4788     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4789     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4790     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4791                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4792   }
4793   case Intrinsic::amdgcn_fcmp: {
4794     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4795     if (!CD)
4796       return DAG.getUNDEF(VT);
4797 
4798     int CondCode = CD->getSExtValue();
4799     if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4800         CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4801       return DAG.getUNDEF(VT);
4802 
4803     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4804     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4805     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4806                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4807   }
4808   case Intrinsic::amdgcn_fmed3:
4809     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4810                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4811   case Intrinsic::amdgcn_fmul_legacy:
4812     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4813                        Op.getOperand(1), Op.getOperand(2));
4814   case Intrinsic::amdgcn_sffbh:
4815     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4816   case Intrinsic::amdgcn_sbfe:
4817     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4818                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4819   case Intrinsic::amdgcn_ubfe:
4820     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4821                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4822   case Intrinsic::amdgcn_cvt_pkrtz:
4823   case Intrinsic::amdgcn_cvt_pknorm_i16:
4824   case Intrinsic::amdgcn_cvt_pknorm_u16:
4825   case Intrinsic::amdgcn_cvt_pk_i16:
4826   case Intrinsic::amdgcn_cvt_pk_u16: {
4827     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
4828     EVT VT = Op.getValueType();
4829     unsigned Opcode;
4830 
4831     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
4832       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
4833     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
4834       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4835     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
4836       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4837     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
4838       Opcode = AMDGPUISD::CVT_PK_I16_I32;
4839     else
4840       Opcode = AMDGPUISD::CVT_PK_U16_U32;
4841 
4842     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
4843                                Op.getOperand(1), Op.getOperand(2));
4844     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4845   }
4846   case Intrinsic::amdgcn_wqm: {
4847     SDValue Src = Op.getOperand(1);
4848     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4849                    0);
4850   }
4851   case Intrinsic::amdgcn_wwm: {
4852     SDValue Src = Op.getOperand(1);
4853     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4854                    0);
4855   }
4856   case Intrinsic::amdgcn_image_getlod:
4857   case Intrinsic::amdgcn_image_getresinfo: {
4858     unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4;
4859 
4860     // Replace dmask with everything disabled with undef.
4861     const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx));
4862     if (!DMask || DMask->isNullValue())
4863       return DAG.getUNDEF(Op.getValueType());
4864     return SDValue();
4865   }
4866   default:
4867     return Op;
4868   }
4869 }
4870 
4871 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4872                                                  SelectionDAG &DAG) const {
4873   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4874   SDLoc DL(Op);
4875 
4876   switch (IntrID) {
4877   case Intrinsic::amdgcn_atomic_inc:
4878   case Intrinsic::amdgcn_atomic_dec:
4879   case Intrinsic::amdgcn_ds_fadd:
4880   case Intrinsic::amdgcn_ds_fmin:
4881   case Intrinsic::amdgcn_ds_fmax: {
4882     MemSDNode *M = cast<MemSDNode>(Op);
4883     unsigned Opc;
4884     switch (IntrID) {
4885     case Intrinsic::amdgcn_atomic_inc:
4886       Opc = AMDGPUISD::ATOMIC_INC;
4887       break;
4888     case Intrinsic::amdgcn_atomic_dec:
4889       Opc = AMDGPUISD::ATOMIC_DEC;
4890       break;
4891     case Intrinsic::amdgcn_ds_fadd:
4892       Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
4893       break;
4894     case Intrinsic::amdgcn_ds_fmin:
4895       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
4896       break;
4897     case Intrinsic::amdgcn_ds_fmax:
4898       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
4899       break;
4900     default:
4901       llvm_unreachable("Unknown intrinsic!");
4902     }
4903     SDValue Ops[] = {
4904       M->getOperand(0), // Chain
4905       M->getOperand(2), // Ptr
4906       M->getOperand(3)  // Value
4907     };
4908 
4909     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4910                                    M->getMemoryVT(), M->getMemOperand());
4911   }
4912   case Intrinsic::amdgcn_buffer_load:
4913   case Intrinsic::amdgcn_buffer_load_format: {
4914     SDValue Ops[] = {
4915       Op.getOperand(0), // Chain
4916       Op.getOperand(2), // rsrc
4917       Op.getOperand(3), // vindex
4918       Op.getOperand(4), // offset
4919       Op.getOperand(5), // glc
4920       Op.getOperand(6)  // slc
4921     };
4922 
4923     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4924         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4925     EVT VT = Op.getValueType();
4926     EVT IntVT = VT.changeTypeToInteger();
4927 
4928     auto *M = cast<MemSDNode>(Op);
4929     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
4930                                    M->getMemOperand());
4931   }
4932   case Intrinsic::amdgcn_tbuffer_load: {
4933     MemSDNode *M = cast<MemSDNode>(Op);
4934     SDValue Ops[] = {
4935       Op.getOperand(0),  // Chain
4936       Op.getOperand(2),  // rsrc
4937       Op.getOperand(3),  // vindex
4938       Op.getOperand(4),  // voffset
4939       Op.getOperand(5),  // soffset
4940       Op.getOperand(6),  // offset
4941       Op.getOperand(7),  // dfmt
4942       Op.getOperand(8),  // nfmt
4943       Op.getOperand(9),  // glc
4944       Op.getOperand(10)   // slc
4945     };
4946 
4947     EVT VT = Op.getValueType();
4948 
4949     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
4950                                    Op->getVTList(), Ops, VT, M->getMemOperand());
4951   }
4952   case Intrinsic::amdgcn_buffer_atomic_swap:
4953   case Intrinsic::amdgcn_buffer_atomic_add:
4954   case Intrinsic::amdgcn_buffer_atomic_sub:
4955   case Intrinsic::amdgcn_buffer_atomic_smin:
4956   case Intrinsic::amdgcn_buffer_atomic_umin:
4957   case Intrinsic::amdgcn_buffer_atomic_smax:
4958   case Intrinsic::amdgcn_buffer_atomic_umax:
4959   case Intrinsic::amdgcn_buffer_atomic_and:
4960   case Intrinsic::amdgcn_buffer_atomic_or:
4961   case Intrinsic::amdgcn_buffer_atomic_xor: {
4962     SDValue Ops[] = {
4963       Op.getOperand(0), // Chain
4964       Op.getOperand(2), // vdata
4965       Op.getOperand(3), // rsrc
4966       Op.getOperand(4), // vindex
4967       Op.getOperand(5), // offset
4968       Op.getOperand(6)  // slc
4969     };
4970     EVT VT = Op.getValueType();
4971 
4972     auto *M = cast<MemSDNode>(Op);
4973     unsigned Opcode = 0;
4974 
4975     switch (IntrID) {
4976     case Intrinsic::amdgcn_buffer_atomic_swap:
4977       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
4978       break;
4979     case Intrinsic::amdgcn_buffer_atomic_add:
4980       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
4981       break;
4982     case Intrinsic::amdgcn_buffer_atomic_sub:
4983       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
4984       break;
4985     case Intrinsic::amdgcn_buffer_atomic_smin:
4986       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
4987       break;
4988     case Intrinsic::amdgcn_buffer_atomic_umin:
4989       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
4990       break;
4991     case Intrinsic::amdgcn_buffer_atomic_smax:
4992       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
4993       break;
4994     case Intrinsic::amdgcn_buffer_atomic_umax:
4995       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
4996       break;
4997     case Intrinsic::amdgcn_buffer_atomic_and:
4998       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
4999       break;
5000     case Intrinsic::amdgcn_buffer_atomic_or:
5001       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5002       break;
5003     case Intrinsic::amdgcn_buffer_atomic_xor:
5004       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5005       break;
5006     default:
5007       llvm_unreachable("unhandled atomic opcode");
5008     }
5009 
5010     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5011                                    M->getMemOperand());
5012   }
5013 
5014   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5015     SDValue Ops[] = {
5016       Op.getOperand(0), // Chain
5017       Op.getOperand(2), // src
5018       Op.getOperand(3), // cmp
5019       Op.getOperand(4), // rsrc
5020       Op.getOperand(5), // vindex
5021       Op.getOperand(6), // offset
5022       Op.getOperand(7)  // slc
5023     };
5024     EVT VT = Op.getValueType();
5025     auto *M = cast<MemSDNode>(Op);
5026 
5027     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5028                                    Op->getVTList(), Ops, VT, M->getMemOperand());
5029   }
5030 
5031   // Basic sample.
5032   case Intrinsic::amdgcn_image_sample:
5033   case Intrinsic::amdgcn_image_sample_cl:
5034   case Intrinsic::amdgcn_image_sample_d:
5035   case Intrinsic::amdgcn_image_sample_d_cl:
5036   case Intrinsic::amdgcn_image_sample_l:
5037   case Intrinsic::amdgcn_image_sample_b:
5038   case Intrinsic::amdgcn_image_sample_b_cl:
5039   case Intrinsic::amdgcn_image_sample_lz:
5040   case Intrinsic::amdgcn_image_sample_cd:
5041   case Intrinsic::amdgcn_image_sample_cd_cl:
5042 
5043   // Sample with comparison.
5044   case Intrinsic::amdgcn_image_sample_c:
5045   case Intrinsic::amdgcn_image_sample_c_cl:
5046   case Intrinsic::amdgcn_image_sample_c_d:
5047   case Intrinsic::amdgcn_image_sample_c_d_cl:
5048   case Intrinsic::amdgcn_image_sample_c_l:
5049   case Intrinsic::amdgcn_image_sample_c_b:
5050   case Intrinsic::amdgcn_image_sample_c_b_cl:
5051   case Intrinsic::amdgcn_image_sample_c_lz:
5052   case Intrinsic::amdgcn_image_sample_c_cd:
5053   case Intrinsic::amdgcn_image_sample_c_cd_cl:
5054 
5055   // Sample with offsets.
5056   case Intrinsic::amdgcn_image_sample_o:
5057   case Intrinsic::amdgcn_image_sample_cl_o:
5058   case Intrinsic::amdgcn_image_sample_d_o:
5059   case Intrinsic::amdgcn_image_sample_d_cl_o:
5060   case Intrinsic::amdgcn_image_sample_l_o:
5061   case Intrinsic::amdgcn_image_sample_b_o:
5062   case Intrinsic::amdgcn_image_sample_b_cl_o:
5063   case Intrinsic::amdgcn_image_sample_lz_o:
5064   case Intrinsic::amdgcn_image_sample_cd_o:
5065   case Intrinsic::amdgcn_image_sample_cd_cl_o:
5066 
5067   // Sample with comparison and offsets.
5068   case Intrinsic::amdgcn_image_sample_c_o:
5069   case Intrinsic::amdgcn_image_sample_c_cl_o:
5070   case Intrinsic::amdgcn_image_sample_c_d_o:
5071   case Intrinsic::amdgcn_image_sample_c_d_cl_o:
5072   case Intrinsic::amdgcn_image_sample_c_l_o:
5073   case Intrinsic::amdgcn_image_sample_c_b_o:
5074   case Intrinsic::amdgcn_image_sample_c_b_cl_o:
5075   case Intrinsic::amdgcn_image_sample_c_lz_o:
5076   case Intrinsic::amdgcn_image_sample_c_cd_o:
5077   case Intrinsic::amdgcn_image_sample_c_cd_cl_o: {
5078     // Replace dmask with everything disabled with undef.
5079     const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5));
5080     if (!DMask || DMask->isNullValue()) {
5081       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5082       return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op));
5083     }
5084 
5085     return SDValue();
5086   }
5087   default:
5088     return SDValue();
5089   }
5090 }
5091 
5092 SDValue SITargetLowering::handleD16VData(SDValue VData,
5093                                          SelectionDAG &DAG) const {
5094   EVT StoreVT = VData.getValueType();
5095   SDLoc DL(VData);
5096 
5097   if (StoreVT.isVector()) {
5098     assert ((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5099     if (!Subtarget->hasUnpackedD16VMem()) {
5100       if (!isTypeLegal(StoreVT)) {
5101         // If Target supports packed vmem, we just need to workaround
5102         // the illegal type by casting to an equivalent one.
5103         EVT EquivStoreVT = getEquivalentMemType(*DAG.getContext(), StoreVT);
5104         return DAG.getNode(ISD::BITCAST, DL, EquivStoreVT, VData);
5105       }
5106     } else { // We need to unpack the packed data to store.
5107       EVT IntStoreVT = StoreVT.changeTypeToInteger();
5108       SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5109       EVT EquivStoreVT = (StoreVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
5110       return DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5111     }
5112   }
5113   // No change for f16 and legal vector D16 types.
5114   return VData;
5115 }
5116 
5117 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5118                                               SelectionDAG &DAG) const {
5119   SDLoc DL(Op);
5120   SDValue Chain = Op.getOperand(0);
5121   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5122   MachineFunction &MF = DAG.getMachineFunction();
5123 
5124   switch (IntrinsicID) {
5125   case Intrinsic::amdgcn_exp: {
5126     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5127     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5128     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5129     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5130 
5131     const SDValue Ops[] = {
5132       Chain,
5133       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5134       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5135       Op.getOperand(4), // src0
5136       Op.getOperand(5), // src1
5137       Op.getOperand(6), // src2
5138       Op.getOperand(7), // src3
5139       DAG.getTargetConstant(0, DL, MVT::i1), // compr
5140       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5141     };
5142 
5143     unsigned Opc = Done->isNullValue() ?
5144       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5145     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5146   }
5147   case Intrinsic::amdgcn_exp_compr: {
5148     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5149     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5150     SDValue Src0 = Op.getOperand(4);
5151     SDValue Src1 = Op.getOperand(5);
5152     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5153     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5154 
5155     SDValue Undef = DAG.getUNDEF(MVT::f32);
5156     const SDValue Ops[] = {
5157       Chain,
5158       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5159       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5160       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5161       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5162       Undef, // src2
5163       Undef, // src3
5164       DAG.getTargetConstant(1, DL, MVT::i1), // compr
5165       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5166     };
5167 
5168     unsigned Opc = Done->isNullValue() ?
5169       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5170     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5171   }
5172   case Intrinsic::amdgcn_s_sendmsg:
5173   case Intrinsic::amdgcn_s_sendmsghalt: {
5174     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5175       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5176     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5177     SDValue Glue = Chain.getValue(1);
5178     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5179                        Op.getOperand(2), Glue);
5180   }
5181   case Intrinsic::amdgcn_init_exec: {
5182     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5183                        Op.getOperand(2));
5184   }
5185   case Intrinsic::amdgcn_init_exec_from_input: {
5186     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5187                        Op.getOperand(2), Op.getOperand(3));
5188   }
5189   case AMDGPUIntrinsic::AMDGPU_kill: {
5190     SDValue Src = Op.getOperand(2);
5191     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5192       if (!K->isNegative())
5193         return Chain;
5194 
5195       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5196       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5197     }
5198 
5199     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5200     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5201   }
5202   case Intrinsic::amdgcn_s_barrier: {
5203     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5204       const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
5205       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5206       if (WGSize <= ST.getWavefrontSize())
5207         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5208                                           Op.getOperand(0)), 0);
5209     }
5210     return SDValue();
5211   };
5212   case AMDGPUIntrinsic::SI_tbuffer_store: {
5213 
5214     // Extract vindex and voffset from vaddr as appropriate
5215     const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5216     const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5217     SDValue VAddr = Op.getOperand(5);
5218 
5219     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5220 
5221     assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5222            "Legacy intrinsic doesn't support both offset and index - use new version");
5223 
5224     SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5225     SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5226 
5227     // Deal with the vec-3 case
5228     const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5229     auto Opcode = NumChannels->getZExtValue() == 3 ?
5230       AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5231 
5232     SDValue Ops[] = {
5233      Chain,
5234      Op.getOperand(3),  // vdata
5235      Op.getOperand(2),  // rsrc
5236      VIndex,
5237      VOffset,
5238      Op.getOperand(6),  // soffset
5239      Op.getOperand(7),  // inst_offset
5240      Op.getOperand(8),  // dfmt
5241      Op.getOperand(9),  // nfmt
5242      Op.getOperand(12), // glc
5243      Op.getOperand(13), // slc
5244     };
5245 
5246     assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5247            "Value of tfe other than zero is unsupported");
5248 
5249     EVT VT = Op.getOperand(3).getValueType();
5250     MachineMemOperand *MMO = MF.getMachineMemOperand(
5251       MachinePointerInfo(),
5252       MachineMemOperand::MOStore,
5253       VT.getStoreSize(), 4);
5254     return DAG.getMemIntrinsicNode(Opcode, DL,
5255                                    Op->getVTList(), Ops, VT, MMO);
5256   }
5257 
5258   case Intrinsic::amdgcn_tbuffer_store: {
5259     SDValue VData = Op.getOperand(2);
5260     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5261     if (IsD16)
5262       VData = handleD16VData(VData, DAG);
5263     SDValue Ops[] = {
5264       Chain,
5265       VData,             // vdata
5266       Op.getOperand(3),  // rsrc
5267       Op.getOperand(4),  // vindex
5268       Op.getOperand(5),  // voffset
5269       Op.getOperand(6),  // soffset
5270       Op.getOperand(7),  // offset
5271       Op.getOperand(8),  // dfmt
5272       Op.getOperand(9),  // nfmt
5273       Op.getOperand(10), // glc
5274       Op.getOperand(11)  // slc
5275     };
5276     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5277                            AMDGPUISD::TBUFFER_STORE_FORMAT;
5278     MemSDNode *M = cast<MemSDNode>(Op);
5279     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5280                                    M->getMemoryVT(), M->getMemOperand());
5281   }
5282 
5283   case Intrinsic::amdgcn_buffer_store:
5284   case Intrinsic::amdgcn_buffer_store_format: {
5285     SDValue VData = Op.getOperand(2);
5286     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5287     if (IsD16)
5288       VData = handleD16VData(VData, DAG);
5289     SDValue Ops[] = {
5290       Chain,
5291       VData,            // vdata
5292       Op.getOperand(3), // rsrc
5293       Op.getOperand(4), // vindex
5294       Op.getOperand(5), // offset
5295       Op.getOperand(6), // glc
5296       Op.getOperand(7)  // slc
5297     };
5298     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5299                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5300     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5301     MemSDNode *M = cast<MemSDNode>(Op);
5302     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5303                                    M->getMemoryVT(), M->getMemOperand());
5304   }
5305 
5306   case Intrinsic::amdgcn_image_store:
5307   case Intrinsic::amdgcn_image_store_mip: {
5308     SDValue VData = Op.getOperand(2);
5309     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5310     if (IsD16)
5311       VData = handleD16VData(VData, DAG);
5312     SDValue Ops[] = {
5313       Chain, // Chain
5314       VData, // vdata
5315       Op.getOperand(3), // vaddr
5316       Op.getOperand(4), // rsrc
5317       Op.getOperand(5), // dmask
5318       Op.getOperand(6), // glc
5319       Op.getOperand(7), // slc
5320       Op.getOperand(8), // lwe
5321       Op.getOperand(9)  // da
5322     };
5323     unsigned Opc = (IntrinsicID==Intrinsic::amdgcn_image_store) ?
5324                   AMDGPUISD::IMAGE_STORE : AMDGPUISD::IMAGE_STORE_MIP;
5325     MemSDNode *M = cast<MemSDNode>(Op);
5326     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5327                                    M->getMemoryVT(), M->getMemOperand());
5328   }
5329 
5330   default:
5331     return Op;
5332   }
5333 }
5334 
5335 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5336   SDLoc DL(Op);
5337   LoadSDNode *Load = cast<LoadSDNode>(Op);
5338   ISD::LoadExtType ExtType = Load->getExtensionType();
5339   EVT MemVT = Load->getMemoryVT();
5340 
5341   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5342     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5343       return SDValue();
5344 
5345     // FIXME: Copied from PPC
5346     // First, load into 32 bits, then truncate to 1 bit.
5347 
5348     SDValue Chain = Load->getChain();
5349     SDValue BasePtr = Load->getBasePtr();
5350     MachineMemOperand *MMO = Load->getMemOperand();
5351 
5352     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5353 
5354     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5355                                    BasePtr, RealMemVT, MMO);
5356 
5357     SDValue Ops[] = {
5358       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5359       NewLD.getValue(1)
5360     };
5361 
5362     return DAG.getMergeValues(Ops, DL);
5363   }
5364 
5365   if (!MemVT.isVector())
5366     return SDValue();
5367 
5368   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5369          "Custom lowering for non-i32 vectors hasn't been implemented.");
5370 
5371   unsigned AS = Load->getAddressSpace();
5372   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5373                           AS, Load->getAlignment())) {
5374     SDValue Ops[2];
5375     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5376     return DAG.getMergeValues(Ops, DL);
5377   }
5378 
5379   MachineFunction &MF = DAG.getMachineFunction();
5380   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5381   // If there is a possibilty that flat instruction access scratch memory
5382   // then we need to use the same legalization rules we use for private.
5383   if (AS == AMDGPUASI.FLAT_ADDRESS)
5384     AS = MFI->hasFlatScratchInit() ?
5385          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5386 
5387   unsigned NumElements = MemVT.getVectorNumElements();
5388   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5389       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5390     if (isMemOpUniform(Load))
5391       return SDValue();
5392     // Non-uniform loads will be selected to MUBUF instructions, so they
5393     // have the same legalization requirements as global and private
5394     // loads.
5395     //
5396   }
5397   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5398       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5399       AS == AMDGPUASI.GLOBAL_ADDRESS) {
5400     if (Subtarget->getScalarizeGlobalBehavior() && isMemOpUniform(Load) &&
5401         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load))
5402       return SDValue();
5403     // Non-uniform loads will be selected to MUBUF instructions, so they
5404     // have the same legalization requirements as global and private
5405     // loads.
5406     //
5407   }
5408   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5409       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5410       AS == AMDGPUASI.GLOBAL_ADDRESS ||
5411       AS == AMDGPUASI.FLAT_ADDRESS) {
5412     if (NumElements > 4)
5413       return SplitVectorLoad(Op, DAG);
5414     // v4 loads are supported for private and global memory.
5415     return SDValue();
5416   }
5417   if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5418     // Depending on the setting of the private_element_size field in the
5419     // resource descriptor, we can only make private accesses up to a certain
5420     // size.
5421     switch (Subtarget->getMaxPrivateElementSize()) {
5422     case 4:
5423       return scalarizeVectorLoad(Load, DAG);
5424     case 8:
5425       if (NumElements > 2)
5426         return SplitVectorLoad(Op, DAG);
5427       return SDValue();
5428     case 16:
5429       // Same as global/flat
5430       if (NumElements > 4)
5431         return SplitVectorLoad(Op, DAG);
5432       return SDValue();
5433     default:
5434       llvm_unreachable("unsupported private_element_size");
5435     }
5436   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5437     if (NumElements > 2)
5438       return SplitVectorLoad(Op, DAG);
5439 
5440     if (NumElements == 2)
5441       return SDValue();
5442 
5443     // If properly aligned, if we split we might be able to use ds_read_b64.
5444     return SplitVectorLoad(Op, DAG);
5445   }
5446   return SDValue();
5447 }
5448 
5449 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5450   if (Op.getValueType() != MVT::i64)
5451     return SDValue();
5452 
5453   SDLoc DL(Op);
5454   SDValue Cond = Op.getOperand(0);
5455 
5456   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5457   SDValue One = DAG.getConstant(1, DL, MVT::i32);
5458 
5459   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5460   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5461 
5462   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5463   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5464 
5465   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5466 
5467   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5468   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5469 
5470   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5471 
5472   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5473   return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res);
5474 }
5475 
5476 // Catch division cases where we can use shortcuts with rcp and rsq
5477 // instructions.
5478 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5479                                               SelectionDAG &DAG) const {
5480   SDLoc SL(Op);
5481   SDValue LHS = Op.getOperand(0);
5482   SDValue RHS = Op.getOperand(1);
5483   EVT VT = Op.getValueType();
5484   const SDNodeFlags Flags = Op->getFlags();
5485   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath ||
5486                 Flags.hasUnsafeAlgebra() || Flags.hasAllowReciprocal();
5487 
5488   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5489     return SDValue();
5490 
5491   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5492     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5493       if (CLHS->isExactlyValue(1.0)) {
5494         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5495         // the CI documentation has a worst case error of 1 ulp.
5496         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5497         // use it as long as we aren't trying to use denormals.
5498         //
5499         // v_rcp_f16 and v_rsq_f16 DO support denormals.
5500 
5501         // 1.0 / sqrt(x) -> rsq(x)
5502 
5503         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5504         // error seems really high at 2^29 ULP.
5505         if (RHS.getOpcode() == ISD::FSQRT)
5506           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5507 
5508         // 1.0 / x -> rcp(x)
5509         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5510       }
5511 
5512       // Same as for 1.0, but expand the sign out of the constant.
5513       if (CLHS->isExactlyValue(-1.0)) {
5514         // -1.0 / x -> rcp (fneg x)
5515         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5516         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5517       }
5518     }
5519   }
5520 
5521   if (Unsafe) {
5522     // Turn into multiply by the reciprocal.
5523     // x / y -> x * (1.0 / y)
5524     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5525     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5526   }
5527 
5528   return SDValue();
5529 }
5530 
5531 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5532                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5533   if (GlueChain->getNumValues() <= 1) {
5534     return DAG.getNode(Opcode, SL, VT, A, B);
5535   }
5536 
5537   assert(GlueChain->getNumValues() == 3);
5538 
5539   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5540   switch (Opcode) {
5541   default: llvm_unreachable("no chain equivalent for opcode");
5542   case ISD::FMUL:
5543     Opcode = AMDGPUISD::FMUL_W_CHAIN;
5544     break;
5545   }
5546 
5547   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5548                      GlueChain.getValue(2));
5549 }
5550 
5551 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5552                            EVT VT, SDValue A, SDValue B, SDValue C,
5553                            SDValue GlueChain) {
5554   if (GlueChain->getNumValues() <= 1) {
5555     return DAG.getNode(Opcode, SL, VT, A, B, C);
5556   }
5557 
5558   assert(GlueChain->getNumValues() == 3);
5559 
5560   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5561   switch (Opcode) {
5562   default: llvm_unreachable("no chain equivalent for opcode");
5563   case ISD::FMA:
5564     Opcode = AMDGPUISD::FMA_W_CHAIN;
5565     break;
5566   }
5567 
5568   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5569                      GlueChain.getValue(2));
5570 }
5571 
5572 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5573   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5574     return FastLowered;
5575 
5576   SDLoc SL(Op);
5577   SDValue Src0 = Op.getOperand(0);
5578   SDValue Src1 = Op.getOperand(1);
5579 
5580   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5581   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5582 
5583   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5584   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5585 
5586   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5587   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5588 
5589   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5590 }
5591 
5592 // Faster 2.5 ULP division that does not support denormals.
5593 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5594   SDLoc SL(Op);
5595   SDValue LHS = Op.getOperand(1);
5596   SDValue RHS = Op.getOperand(2);
5597 
5598   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5599 
5600   const APFloat K0Val(BitsToFloat(0x6f800000));
5601   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5602 
5603   const APFloat K1Val(BitsToFloat(0x2f800000));
5604   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5605 
5606   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5607 
5608   EVT SetCCVT =
5609     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5610 
5611   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5612 
5613   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5614 
5615   // TODO: Should this propagate fast-math-flags?
5616   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5617 
5618   // rcp does not support denormals.
5619   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5620 
5621   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5622 
5623   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5624 }
5625 
5626 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5627   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5628     return FastLowered;
5629 
5630   SDLoc SL(Op);
5631   SDValue LHS = Op.getOperand(0);
5632   SDValue RHS = Op.getOperand(1);
5633 
5634   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5635 
5636   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5637 
5638   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5639                                           RHS, RHS, LHS);
5640   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5641                                         LHS, RHS, LHS);
5642 
5643   // Denominator is scaled to not be denormal, so using rcp is ok.
5644   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5645                                   DenominatorScaled);
5646   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5647                                      DenominatorScaled);
5648 
5649   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5650                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5651                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5652 
5653   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5654 
5655   if (!Subtarget->hasFP32Denormals()) {
5656     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5657     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5658                                                       SL, MVT::i32);
5659     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5660                                        DAG.getEntryNode(),
5661                                        EnableDenormValue, BitField);
5662     SDValue Ops[3] = {
5663       NegDivScale0,
5664       EnableDenorm.getValue(0),
5665       EnableDenorm.getValue(1)
5666     };
5667 
5668     NegDivScale0 = DAG.getMergeValues(Ops, SL);
5669   }
5670 
5671   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5672                              ApproxRcp, One, NegDivScale0);
5673 
5674   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5675                              ApproxRcp, Fma0);
5676 
5677   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5678                            Fma1, Fma1);
5679 
5680   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5681                              NumeratorScaled, Mul);
5682 
5683   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5684 
5685   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5686                              NumeratorScaled, Fma3);
5687 
5688   if (!Subtarget->hasFP32Denormals()) {
5689     const SDValue DisableDenormValue =
5690         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5691     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5692                                         Fma4.getValue(1),
5693                                         DisableDenormValue,
5694                                         BitField,
5695                                         Fma4.getValue(2));
5696 
5697     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5698                                       DisableDenorm, DAG.getRoot());
5699     DAG.setRoot(OutputChain);
5700   }
5701 
5702   SDValue Scale = NumeratorScaled.getValue(1);
5703   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5704                              Fma4, Fma1, Fma3, Scale);
5705 
5706   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5707 }
5708 
5709 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5710   if (DAG.getTarget().Options.UnsafeFPMath)
5711     return lowerFastUnsafeFDIV(Op, DAG);
5712 
5713   SDLoc SL(Op);
5714   SDValue X = Op.getOperand(0);
5715   SDValue Y = Op.getOperand(1);
5716 
5717   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5718 
5719   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5720 
5721   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5722 
5723   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5724 
5725   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5726 
5727   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5728 
5729   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5730 
5731   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5732 
5733   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5734 
5735   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5736   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5737 
5738   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5739                              NegDivScale0, Mul, DivScale1);
5740 
5741   SDValue Scale;
5742 
5743   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5744     // Workaround a hardware bug on SI where the condition output from div_scale
5745     // is not usable.
5746 
5747     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5748 
5749     // Figure out if the scale to use for div_fmas.
5750     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5751     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5752     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5753     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5754 
5755     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5756     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5757 
5758     SDValue Scale0Hi
5759       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5760     SDValue Scale1Hi
5761       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5762 
5763     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5764     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5765     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5766   } else {
5767     Scale = DivScale1.getValue(1);
5768   }
5769 
5770   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5771                              Fma4, Fma3, Mul, Scale);
5772 
5773   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5774 }
5775 
5776 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5777   EVT VT = Op.getValueType();
5778 
5779   if (VT == MVT::f32)
5780     return LowerFDIV32(Op, DAG);
5781 
5782   if (VT == MVT::f64)
5783     return LowerFDIV64(Op, DAG);
5784 
5785   if (VT == MVT::f16)
5786     return LowerFDIV16(Op, DAG);
5787 
5788   llvm_unreachable("Unexpected type for fdiv");
5789 }
5790 
5791 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5792   SDLoc DL(Op);
5793   StoreSDNode *Store = cast<StoreSDNode>(Op);
5794   EVT VT = Store->getMemoryVT();
5795 
5796   if (VT == MVT::i1) {
5797     return DAG.getTruncStore(Store->getChain(), DL,
5798        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5799        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5800   }
5801 
5802   assert(VT.isVector() &&
5803          Store->getValue().getValueType().getScalarType() == MVT::i32);
5804 
5805   unsigned AS = Store->getAddressSpace();
5806   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5807                           AS, Store->getAlignment())) {
5808     return expandUnalignedStore(Store, DAG);
5809   }
5810 
5811   MachineFunction &MF = DAG.getMachineFunction();
5812   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5813   // If there is a possibilty that flat instruction access scratch memory
5814   // then we need to use the same legalization rules we use for private.
5815   if (AS == AMDGPUASI.FLAT_ADDRESS)
5816     AS = MFI->hasFlatScratchInit() ?
5817          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5818 
5819   unsigned NumElements = VT.getVectorNumElements();
5820   if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5821       AS == AMDGPUASI.FLAT_ADDRESS) {
5822     if (NumElements > 4)
5823       return SplitVectorStore(Op, DAG);
5824     return SDValue();
5825   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5826     switch (Subtarget->getMaxPrivateElementSize()) {
5827     case 4:
5828       return scalarizeVectorStore(Store, DAG);
5829     case 8:
5830       if (NumElements > 2)
5831         return SplitVectorStore(Op, DAG);
5832       return SDValue();
5833     case 16:
5834       if (NumElements > 4)
5835         return SplitVectorStore(Op, DAG);
5836       return SDValue();
5837     default:
5838       llvm_unreachable("unsupported private_element_size");
5839     }
5840   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5841     if (NumElements > 2)
5842       return SplitVectorStore(Op, DAG);
5843 
5844     if (NumElements == 2)
5845       return Op;
5846 
5847     // If properly aligned, if we split we might be able to use ds_write_b64.
5848     return SplitVectorStore(Op, DAG);
5849   } else {
5850     llvm_unreachable("unhandled address space");
5851   }
5852 }
5853 
5854 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5855   SDLoc DL(Op);
5856   EVT VT = Op.getValueType();
5857   SDValue Arg = Op.getOperand(0);
5858   // TODO: Should this propagate fast-math-flags?
5859   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5860                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
5861                                               DAG.getConstantFP(0.5/M_PI, DL,
5862                                                                 VT)));
5863 
5864   switch (Op.getOpcode()) {
5865   case ISD::FCOS:
5866     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5867   case ISD::FSIN:
5868     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5869   default:
5870     llvm_unreachable("Wrong trig opcode");
5871   }
5872 }
5873 
5874 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5875   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5876   assert(AtomicNode->isCompareAndSwap());
5877   unsigned AS = AtomicNode->getAddressSpace();
5878 
5879   // No custom lowering required for local address space
5880   if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5881     return Op;
5882 
5883   // Non-local address space requires custom lowering for atomic compare
5884   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5885   SDLoc DL(Op);
5886   SDValue ChainIn = Op.getOperand(0);
5887   SDValue Addr = Op.getOperand(1);
5888   SDValue Old = Op.getOperand(2);
5889   SDValue New = Op.getOperand(3);
5890   EVT VT = Op.getValueType();
5891   MVT SimpleVT = VT.getSimpleVT();
5892   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5893 
5894   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5895   SDValue Ops[] = { ChainIn, Addr, NewOld };
5896 
5897   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5898                                  Ops, VT, AtomicNode->getMemOperand());
5899 }
5900 
5901 //===----------------------------------------------------------------------===//
5902 // Custom DAG optimizations
5903 //===----------------------------------------------------------------------===//
5904 
5905 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
5906                                                      DAGCombinerInfo &DCI) const {
5907   EVT VT = N->getValueType(0);
5908   EVT ScalarVT = VT.getScalarType();
5909   if (ScalarVT != MVT::f32)
5910     return SDValue();
5911 
5912   SelectionDAG &DAG = DCI.DAG;
5913   SDLoc DL(N);
5914 
5915   SDValue Src = N->getOperand(0);
5916   EVT SrcVT = Src.getValueType();
5917 
5918   // TODO: We could try to match extracting the higher bytes, which would be
5919   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
5920   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
5921   // about in practice.
5922   if (DCI.isAfterLegalizeVectorOps() && SrcVT == MVT::i32) {
5923     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
5924       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
5925       DCI.AddToWorklist(Cvt.getNode());
5926       return Cvt;
5927     }
5928   }
5929 
5930   return SDValue();
5931 }
5932 
5933 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
5934 
5935 // This is a variant of
5936 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
5937 //
5938 // The normal DAG combiner will do this, but only if the add has one use since
5939 // that would increase the number of instructions.
5940 //
5941 // This prevents us from seeing a constant offset that can be folded into a
5942 // memory instruction's addressing mode. If we know the resulting add offset of
5943 // a pointer can be folded into an addressing offset, we can replace the pointer
5944 // operand with the add of new constant offset. This eliminates one of the uses,
5945 // and may allow the remaining use to also be simplified.
5946 //
5947 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
5948                                                unsigned AddrSpace,
5949                                                EVT MemVT,
5950                                                DAGCombinerInfo &DCI) const {
5951   SDValue N0 = N->getOperand(0);
5952   SDValue N1 = N->getOperand(1);
5953 
5954   // We only do this to handle cases where it's profitable when there are
5955   // multiple uses of the add, so defer to the standard combine.
5956   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
5957       N0->hasOneUse())
5958     return SDValue();
5959 
5960   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
5961   if (!CN1)
5962     return SDValue();
5963 
5964   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5965   if (!CAdd)
5966     return SDValue();
5967 
5968   // If the resulting offset is too large, we can't fold it into the addressing
5969   // mode offset.
5970   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
5971   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
5972 
5973   AddrMode AM;
5974   AM.HasBaseReg = true;
5975   AM.BaseOffs = Offset.getSExtValue();
5976   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
5977     return SDValue();
5978 
5979   SelectionDAG &DAG = DCI.DAG;
5980   SDLoc SL(N);
5981   EVT VT = N->getValueType(0);
5982 
5983   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
5984   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
5985 
5986   SDNodeFlags Flags;
5987   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
5988                           (N0.getOpcode() == ISD::OR ||
5989                            N0->getFlags().hasNoUnsignedWrap()));
5990 
5991   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
5992 }
5993 
5994 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
5995                                                   DAGCombinerInfo &DCI) const {
5996   SDValue Ptr = N->getBasePtr();
5997   SelectionDAG &DAG = DCI.DAG;
5998   SDLoc SL(N);
5999 
6000   // TODO: We could also do this for multiplies.
6001   if (Ptr.getOpcode() == ISD::SHL) {
6002     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
6003                                           N->getMemoryVT(), DCI);
6004     if (NewPtr) {
6005       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6006 
6007       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6008       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6009     }
6010   }
6011 
6012   return SDValue();
6013 }
6014 
6015 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6016   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6017          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6018          (Opc == ISD::XOR && Val == 0);
6019 }
6020 
6021 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6022 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6023 // integer combine opportunities since most 64-bit operations are decomposed
6024 // this way.  TODO: We won't want this for SALU especially if it is an inline
6025 // immediate.
6026 SDValue SITargetLowering::splitBinaryBitConstantOp(
6027   DAGCombinerInfo &DCI,
6028   const SDLoc &SL,
6029   unsigned Opc, SDValue LHS,
6030   const ConstantSDNode *CRHS) const {
6031   uint64_t Val = CRHS->getZExtValue();
6032   uint32_t ValLo = Lo_32(Val);
6033   uint32_t ValHi = Hi_32(Val);
6034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6035 
6036     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6037          bitOpWithConstantIsReducible(Opc, ValHi)) ||
6038         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6039     // If we need to materialize a 64-bit immediate, it will be split up later
6040     // anyway. Avoid creating the harder to understand 64-bit immediate
6041     // materialization.
6042     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6043   }
6044 
6045   return SDValue();
6046 }
6047 
6048 // Returns true if argument is a boolean value which is not serialized into
6049 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6050 static bool isBoolSGPR(SDValue V) {
6051   if (V.getValueType() != MVT::i1)
6052     return false;
6053   switch (V.getOpcode()) {
6054   default: break;
6055   case ISD::SETCC:
6056   case ISD::AND:
6057   case ISD::OR:
6058   case ISD::XOR:
6059   case AMDGPUISD::FP_CLASS:
6060     return true;
6061   }
6062   return false;
6063 }
6064 
6065 SDValue SITargetLowering::performAndCombine(SDNode *N,
6066                                             DAGCombinerInfo &DCI) const {
6067   if (DCI.isBeforeLegalize())
6068     return SDValue();
6069 
6070   SelectionDAG &DAG = DCI.DAG;
6071   EVT VT = N->getValueType(0);
6072   SDValue LHS = N->getOperand(0);
6073   SDValue RHS = N->getOperand(1);
6074 
6075 
6076   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6077   if (VT == MVT::i64 && CRHS) {
6078     if (SDValue Split
6079         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6080       return Split;
6081   }
6082 
6083   if (CRHS && VT == MVT::i32) {
6084     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6085     // nb = number of trailing zeroes in mask
6086     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6087     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6088     uint64_t Mask = CRHS->getZExtValue();
6089     unsigned Bits = countPopulation(Mask);
6090     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6091         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6092       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6093         unsigned Shift = CShift->getZExtValue();
6094         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6095         unsigned Offset = NB + Shift;
6096         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6097           SDLoc SL(N);
6098           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6099                                     LHS->getOperand(0),
6100                                     DAG.getConstant(Offset, SL, MVT::i32),
6101                                     DAG.getConstant(Bits, SL, MVT::i32));
6102           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6103           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6104                                     DAG.getValueType(NarrowVT));
6105           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6106                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6107           return Shl;
6108         }
6109       }
6110     }
6111   }
6112 
6113   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6114   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6115   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6116     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6117     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6118 
6119     SDValue X = LHS.getOperand(0);
6120     SDValue Y = RHS.getOperand(0);
6121     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6122       return SDValue();
6123 
6124     if (LCC == ISD::SETO) {
6125       if (X != LHS.getOperand(1))
6126         return SDValue();
6127 
6128       if (RCC == ISD::SETUNE) {
6129         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6130         if (!C1 || !C1->isInfinity() || C1->isNegative())
6131           return SDValue();
6132 
6133         const uint32_t Mask = SIInstrFlags::N_NORMAL |
6134                               SIInstrFlags::N_SUBNORMAL |
6135                               SIInstrFlags::N_ZERO |
6136                               SIInstrFlags::P_ZERO |
6137                               SIInstrFlags::P_SUBNORMAL |
6138                               SIInstrFlags::P_NORMAL;
6139 
6140         static_assert(((~(SIInstrFlags::S_NAN |
6141                           SIInstrFlags::Q_NAN |
6142                           SIInstrFlags::N_INFINITY |
6143                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6144                       "mask not equal");
6145 
6146         SDLoc DL(N);
6147         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6148                            X, DAG.getConstant(Mask, DL, MVT::i32));
6149       }
6150     }
6151   }
6152 
6153   if (VT == MVT::i32 &&
6154       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6155     // and x, (sext cc from i1) => select cc, x, 0
6156     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6157       std::swap(LHS, RHS);
6158     if (isBoolSGPR(RHS.getOperand(0)))
6159       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6160                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6161   }
6162 
6163   return SDValue();
6164 }
6165 
6166 SDValue SITargetLowering::performOrCombine(SDNode *N,
6167                                            DAGCombinerInfo &DCI) const {
6168   SelectionDAG &DAG = DCI.DAG;
6169   SDValue LHS = N->getOperand(0);
6170   SDValue RHS = N->getOperand(1);
6171 
6172   EVT VT = N->getValueType(0);
6173   if (VT == MVT::i1) {
6174     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6175     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6176         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6177       SDValue Src = LHS.getOperand(0);
6178       if (Src != RHS.getOperand(0))
6179         return SDValue();
6180 
6181       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6182       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6183       if (!CLHS || !CRHS)
6184         return SDValue();
6185 
6186       // Only 10 bits are used.
6187       static const uint32_t MaxMask = 0x3ff;
6188 
6189       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6190       SDLoc DL(N);
6191       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6192                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
6193     }
6194 
6195     return SDValue();
6196   }
6197 
6198   if (VT != MVT::i64)
6199     return SDValue();
6200 
6201   // TODO: This could be a generic combine with a predicate for extracting the
6202   // high half of an integer being free.
6203 
6204   // (or i64:x, (zero_extend i32:y)) ->
6205   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6206   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6207       RHS.getOpcode() != ISD::ZERO_EXTEND)
6208     std::swap(LHS, RHS);
6209 
6210   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6211     SDValue ExtSrc = RHS.getOperand(0);
6212     EVT SrcVT = ExtSrc.getValueType();
6213     if (SrcVT == MVT::i32) {
6214       SDLoc SL(N);
6215       SDValue LowLHS, HiBits;
6216       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6217       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6218 
6219       DCI.AddToWorklist(LowOr.getNode());
6220       DCI.AddToWorklist(HiBits.getNode());
6221 
6222       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6223                                 LowOr, HiBits);
6224       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6225     }
6226   }
6227 
6228   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6229   if (CRHS) {
6230     if (SDValue Split
6231           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6232       return Split;
6233   }
6234 
6235   return SDValue();
6236 }
6237 
6238 SDValue SITargetLowering::performXorCombine(SDNode *N,
6239                                             DAGCombinerInfo &DCI) const {
6240   EVT VT = N->getValueType(0);
6241   if (VT != MVT::i64)
6242     return SDValue();
6243 
6244   SDValue LHS = N->getOperand(0);
6245   SDValue RHS = N->getOperand(1);
6246 
6247   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6248   if (CRHS) {
6249     if (SDValue Split
6250           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6251       return Split;
6252   }
6253 
6254   return SDValue();
6255 }
6256 
6257 // Instructions that will be lowered with a final instruction that zeros the
6258 // high result bits.
6259 // XXX - probably only need to list legal operations.
6260 static bool fp16SrcZerosHighBits(unsigned Opc) {
6261   switch (Opc) {
6262   case ISD::FADD:
6263   case ISD::FSUB:
6264   case ISD::FMUL:
6265   case ISD::FDIV:
6266   case ISD::FREM:
6267   case ISD::FMA:
6268   case ISD::FMAD:
6269   case ISD::FCANONICALIZE:
6270   case ISD::FP_ROUND:
6271   case ISD::UINT_TO_FP:
6272   case ISD::SINT_TO_FP:
6273   case ISD::FABS:
6274     // Fabs is lowered to a bit operation, but it's an and which will clear the
6275     // high bits anyway.
6276   case ISD::FSQRT:
6277   case ISD::FSIN:
6278   case ISD::FCOS:
6279   case ISD::FPOWI:
6280   case ISD::FPOW:
6281   case ISD::FLOG:
6282   case ISD::FLOG2:
6283   case ISD::FLOG10:
6284   case ISD::FEXP:
6285   case ISD::FEXP2:
6286   case ISD::FCEIL:
6287   case ISD::FTRUNC:
6288   case ISD::FRINT:
6289   case ISD::FNEARBYINT:
6290   case ISD::FROUND:
6291   case ISD::FFLOOR:
6292   case ISD::FMINNUM:
6293   case ISD::FMAXNUM:
6294   case AMDGPUISD::FRACT:
6295   case AMDGPUISD::CLAMP:
6296   case AMDGPUISD::COS_HW:
6297   case AMDGPUISD::SIN_HW:
6298   case AMDGPUISD::FMIN3:
6299   case AMDGPUISD::FMAX3:
6300   case AMDGPUISD::FMED3:
6301   case AMDGPUISD::FMAD_FTZ:
6302   case AMDGPUISD::RCP:
6303   case AMDGPUISD::RSQ:
6304   case AMDGPUISD::LDEXP:
6305     return true;
6306   default:
6307     // fcopysign, select and others may be lowered to 32-bit bit operations
6308     // which don't zero the high bits.
6309     return false;
6310   }
6311 }
6312 
6313 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6314                                                    DAGCombinerInfo &DCI) const {
6315   if (!Subtarget->has16BitInsts() ||
6316       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6317     return SDValue();
6318 
6319   EVT VT = N->getValueType(0);
6320   if (VT != MVT::i32)
6321     return SDValue();
6322 
6323   SDValue Src = N->getOperand(0);
6324   if (Src.getValueType() != MVT::i16)
6325     return SDValue();
6326 
6327   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6328   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6329   if (Src.getOpcode() == ISD::BITCAST) {
6330     SDValue BCSrc = Src.getOperand(0);
6331     if (BCSrc.getValueType() == MVT::f16 &&
6332         fp16SrcZerosHighBits(BCSrc.getOpcode()))
6333       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6334   }
6335 
6336   return SDValue();
6337 }
6338 
6339 SDValue SITargetLowering::performClassCombine(SDNode *N,
6340                                               DAGCombinerInfo &DCI) const {
6341   SelectionDAG &DAG = DCI.DAG;
6342   SDValue Mask = N->getOperand(1);
6343 
6344   // fp_class x, 0 -> false
6345   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6346     if (CMask->isNullValue())
6347       return DAG.getConstant(0, SDLoc(N), MVT::i1);
6348   }
6349 
6350   if (N->getOperand(0).isUndef())
6351     return DAG.getUNDEF(MVT::i1);
6352 
6353   return SDValue();
6354 }
6355 
6356 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6357   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6358     return true;
6359 
6360   return DAG.isKnownNeverNaN(Op);
6361 }
6362 
6363 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6364                             const SISubtarget *ST, unsigned MaxDepth=5) {
6365   // If source is a result of another standard FP operation it is already in
6366   // canonical form.
6367 
6368   switch (Op.getOpcode()) {
6369   default:
6370     break;
6371 
6372   // These will flush denorms if required.
6373   case ISD::FADD:
6374   case ISD::FSUB:
6375   case ISD::FMUL:
6376   case ISD::FSQRT:
6377   case ISD::FCEIL:
6378   case ISD::FFLOOR:
6379   case ISD::FMA:
6380   case ISD::FMAD:
6381 
6382   case ISD::FCANONICALIZE:
6383     return true;
6384 
6385   case ISD::FP_ROUND:
6386     return Op.getValueType().getScalarType() != MVT::f16 ||
6387            ST->hasFP16Denormals();
6388 
6389   case ISD::FP_EXTEND:
6390     return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6391            ST->hasFP16Denormals();
6392 
6393   case ISD::FP16_TO_FP:
6394   case ISD::FP_TO_FP16:
6395     return ST->hasFP16Denormals();
6396 
6397   // It can/will be lowered or combined as a bit operation.
6398   // Need to check their input recursively to handle.
6399   case ISD::FNEG:
6400   case ISD::FABS:
6401     return (MaxDepth > 0) &&
6402            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6403 
6404   case ISD::FSIN:
6405   case ISD::FCOS:
6406   case ISD::FSINCOS:
6407     return Op.getValueType().getScalarType() != MVT::f16;
6408 
6409   // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6410   // For such targets need to check their input recursively.
6411   case ISD::FMINNUM:
6412   case ISD::FMAXNUM:
6413   case ISD::FMINNAN:
6414   case ISD::FMAXNAN:
6415 
6416     if (ST->supportsMinMaxDenormModes() &&
6417         DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6418         DAG.isKnownNeverNaN(Op.getOperand(1)))
6419       return true;
6420 
6421     return (MaxDepth > 0) &&
6422            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6423            isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6424 
6425   case ISD::ConstantFP: {
6426     auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6427     return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6428   }
6429   }
6430   return false;
6431 }
6432 
6433 // Constant fold canonicalize.
6434 SDValue SITargetLowering::performFCanonicalizeCombine(
6435   SDNode *N,
6436   DAGCombinerInfo &DCI) const {
6437   SelectionDAG &DAG = DCI.DAG;
6438   ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
6439 
6440   if (!CFP) {
6441     SDValue N0 = N->getOperand(0);
6442     EVT VT = N0.getValueType().getScalarType();
6443     auto ST = getSubtarget();
6444 
6445     if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6446          (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6447          (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6448         DAG.isKnownNeverNaN(N0))
6449       return N0;
6450 
6451     bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6452 
6453     if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6454         isCanonicalized(DAG, N0, ST))
6455       return N0;
6456 
6457     return SDValue();
6458   }
6459 
6460   const APFloat &C = CFP->getValueAPF();
6461 
6462   // Flush denormals to 0 if not enabled.
6463   if (C.isDenormal()) {
6464     EVT VT = N->getValueType(0);
6465     EVT SVT = VT.getScalarType();
6466     if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6467       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6468 
6469     if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6470       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6471 
6472     if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6473       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6474   }
6475 
6476   if (C.isNaN()) {
6477     EVT VT = N->getValueType(0);
6478     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6479     if (C.isSignaling()) {
6480       // Quiet a signaling NaN.
6481       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6482     }
6483 
6484     // Make sure it is the canonical NaN bitpattern.
6485     //
6486     // TODO: Can we use -1 as the canonical NaN value since it's an inline
6487     // immediate?
6488     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6489       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6490   }
6491 
6492   return N->getOperand(0);
6493 }
6494 
6495 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6496   switch (Opc) {
6497   case ISD::FMAXNUM:
6498     return AMDGPUISD::FMAX3;
6499   case ISD::SMAX:
6500     return AMDGPUISD::SMAX3;
6501   case ISD::UMAX:
6502     return AMDGPUISD::UMAX3;
6503   case ISD::FMINNUM:
6504     return AMDGPUISD::FMIN3;
6505   case ISD::SMIN:
6506     return AMDGPUISD::SMIN3;
6507   case ISD::UMIN:
6508     return AMDGPUISD::UMIN3;
6509   default:
6510     llvm_unreachable("Not a min/max opcode");
6511   }
6512 }
6513 
6514 SDValue SITargetLowering::performIntMed3ImmCombine(
6515   SelectionDAG &DAG, const SDLoc &SL,
6516   SDValue Op0, SDValue Op1, bool Signed) const {
6517   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6518   if (!K1)
6519     return SDValue();
6520 
6521   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6522   if (!K0)
6523     return SDValue();
6524 
6525   if (Signed) {
6526     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6527       return SDValue();
6528   } else {
6529     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6530       return SDValue();
6531   }
6532 
6533   EVT VT = K0->getValueType(0);
6534   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6535   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6536     return DAG.getNode(Med3Opc, SL, VT,
6537                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6538   }
6539 
6540   // If there isn't a 16-bit med3 operation, convert to 32-bit.
6541   MVT NVT = MVT::i32;
6542   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6543 
6544   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6545   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6546   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6547 
6548   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6549   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6550 }
6551 
6552 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6553   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6554     return C;
6555 
6556   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6557     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6558       return C;
6559   }
6560 
6561   return nullptr;
6562 }
6563 
6564 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6565                                                   const SDLoc &SL,
6566                                                   SDValue Op0,
6567                                                   SDValue Op1) const {
6568   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6569   if (!K1)
6570     return SDValue();
6571 
6572   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6573   if (!K0)
6574     return SDValue();
6575 
6576   // Ordered >= (although NaN inputs should have folded away by now).
6577   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6578   if (Cmp == APFloat::cmpGreaterThan)
6579     return SDValue();
6580 
6581   // TODO: Check IEEE bit enabled?
6582   EVT VT = Op0.getValueType();
6583   if (Subtarget->enableDX10Clamp()) {
6584     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6585     // hardware fmed3 behavior converting to a min.
6586     // FIXME: Should this be allowing -0.0?
6587     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6588       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6589   }
6590 
6591   // med3 for f16 is only available on gfx9+, and not available for v2f16.
6592   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6593     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6594     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6595     // then give the other result, which is different from med3 with a NaN
6596     // input.
6597     SDValue Var = Op0.getOperand(0);
6598     if (!isKnownNeverSNan(DAG, Var))
6599       return SDValue();
6600 
6601     return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6602                        Var, SDValue(K0, 0), SDValue(K1, 0));
6603   }
6604 
6605   return SDValue();
6606 }
6607 
6608 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6609                                                DAGCombinerInfo &DCI) const {
6610   SelectionDAG &DAG = DCI.DAG;
6611 
6612   EVT VT = N->getValueType(0);
6613   unsigned Opc = N->getOpcode();
6614   SDValue Op0 = N->getOperand(0);
6615   SDValue Op1 = N->getOperand(1);
6616 
6617   // Only do this if the inner op has one use since this will just increases
6618   // register pressure for no benefit.
6619 
6620 
6621   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6622       VT != MVT::f64 &&
6623       ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6624     // max(max(a, b), c) -> max3(a, b, c)
6625     // min(min(a, b), c) -> min3(a, b, c)
6626     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6627       SDLoc DL(N);
6628       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6629                          DL,
6630                          N->getValueType(0),
6631                          Op0.getOperand(0),
6632                          Op0.getOperand(1),
6633                          Op1);
6634     }
6635 
6636     // Try commuted.
6637     // max(a, max(b, c)) -> max3(a, b, c)
6638     // min(a, min(b, c)) -> min3(a, b, c)
6639     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
6640       SDLoc DL(N);
6641       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6642                          DL,
6643                          N->getValueType(0),
6644                          Op0,
6645                          Op1.getOperand(0),
6646                          Op1.getOperand(1));
6647     }
6648   }
6649 
6650   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
6651   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
6652     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
6653       return Med3;
6654   }
6655 
6656   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
6657     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
6658       return Med3;
6659   }
6660 
6661   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
6662   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
6663        (Opc == AMDGPUISD::FMIN_LEGACY &&
6664         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
6665       (VT == MVT::f32 || VT == MVT::f64 ||
6666        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
6667        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
6668       Op0.hasOneUse()) {
6669     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
6670       return Res;
6671   }
6672 
6673   return SDValue();
6674 }
6675 
6676 static bool isClampZeroToOne(SDValue A, SDValue B) {
6677   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
6678     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
6679       // FIXME: Should this be allowing -0.0?
6680       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
6681              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
6682     }
6683   }
6684 
6685   return false;
6686 }
6687 
6688 // FIXME: Should only worry about snans for version with chain.
6689 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6690                                               DAGCombinerInfo &DCI) const {
6691   EVT VT = N->getValueType(0);
6692   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6693   // NaNs. With a NaN input, the order of the operands may change the result.
6694 
6695   SelectionDAG &DAG = DCI.DAG;
6696   SDLoc SL(N);
6697 
6698   SDValue Src0 = N->getOperand(0);
6699   SDValue Src1 = N->getOperand(1);
6700   SDValue Src2 = N->getOperand(2);
6701 
6702   if (isClampZeroToOne(Src0, Src1)) {
6703     // const_a, const_b, x -> clamp is safe in all cases including signaling
6704     // nans.
6705     // FIXME: Should this be allowing -0.0?
6706     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
6707   }
6708 
6709   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
6710   // handling no dx10-clamp?
6711   if (Subtarget->enableDX10Clamp()) {
6712     // If NaNs is clamped to 0, we are free to reorder the inputs.
6713 
6714     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6715       std::swap(Src0, Src1);
6716 
6717     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
6718       std::swap(Src1, Src2);
6719 
6720     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
6721       std::swap(Src0, Src1);
6722 
6723     if (isClampZeroToOne(Src1, Src2))
6724       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
6725   }
6726 
6727   return SDValue();
6728 }
6729 
6730 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
6731                                                  DAGCombinerInfo &DCI) const {
6732   SDValue Src0 = N->getOperand(0);
6733   SDValue Src1 = N->getOperand(1);
6734   if (Src0.isUndef() && Src1.isUndef())
6735     return DCI.DAG.getUNDEF(N->getValueType(0));
6736   return SDValue();
6737 }
6738 
6739 SDValue SITargetLowering::performExtractVectorEltCombine(
6740   SDNode *N, DAGCombinerInfo &DCI) const {
6741   SDValue Vec = N->getOperand(0);
6742 
6743   SelectionDAG &DAG = DCI.DAG;
6744   if (Vec.getOpcode() == ISD::FNEG && allUsesHaveSourceMods(N)) {
6745     SDLoc SL(N);
6746     EVT EltVT = N->getValueType(0);
6747     SDValue Idx = N->getOperand(1);
6748     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6749                               Vec.getOperand(0), Idx);
6750     return DAG.getNode(ISD::FNEG, SL, EltVT, Elt);
6751   }
6752 
6753   return SDValue();
6754 }
6755 
6756 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
6757                                       SDValue &Lo, SDValue &Hi) {
6758   if (Hi.getOpcode() == ISD::BITCAST &&
6759       Hi.getOperand(0).getValueType() == MVT::f16 &&
6760       (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
6761     Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
6762     Hi = Hi.getOperand(0);
6763     return true;
6764   }
6765 
6766   return false;
6767 }
6768 
6769 SDValue SITargetLowering::performBuildVectorCombine(
6770   SDNode *N, DAGCombinerInfo &DCI) const {
6771   SDLoc SL(N);
6772 
6773   if (!isTypeLegal(MVT::v2i16))
6774     return SDValue();
6775   SelectionDAG &DAG = DCI.DAG;
6776   EVT VT = N->getValueType(0);
6777 
6778   if (VT == MVT::v2i16) {
6779     SDValue Lo = N->getOperand(0);
6780     SDValue Hi = N->getOperand(1);
6781 
6782     // v2i16 build_vector (const|undef), (bitcast f16:$x)
6783     // -> bitcast (v2f16 build_vector const|undef, $x
6784     if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
6785       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi  });
6786       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6787     }
6788 
6789     if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
6790       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo  });
6791       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
6792     }
6793   }
6794 
6795   return SDValue();
6796 }
6797 
6798 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
6799                                           const SDNode *N0,
6800                                           const SDNode *N1) const {
6801   EVT VT = N0->getValueType(0);
6802 
6803   // Only do this if we are not trying to support denormals. v_mad_f32 does not
6804   // support denormals ever.
6805   if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
6806       (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
6807     return ISD::FMAD;
6808 
6809   const TargetOptions &Options = DAG.getTarget().Options;
6810   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
6811        (N0->getFlags().hasUnsafeAlgebra() &&
6812         N1->getFlags().hasUnsafeAlgebra())) &&
6813       isFMAFasterThanFMulAndFAdd(VT)) {
6814     return ISD::FMA;
6815   }
6816 
6817   return 0;
6818 }
6819 
6820 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
6821                            EVT VT,
6822                            SDValue N0, SDValue N1, SDValue N2,
6823                            bool Signed) {
6824   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
6825   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
6826   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
6827   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
6828 }
6829 
6830 SDValue SITargetLowering::performAddCombine(SDNode *N,
6831                                             DAGCombinerInfo &DCI) const {
6832   SelectionDAG &DAG = DCI.DAG;
6833   EVT VT = N->getValueType(0);
6834   SDLoc SL(N);
6835   SDValue LHS = N->getOperand(0);
6836   SDValue RHS = N->getOperand(1);
6837 
6838   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
6839       && Subtarget->hasMad64_32() &&
6840       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
6841       VT.getScalarSizeInBits() <= 64) {
6842     if (LHS.getOpcode() != ISD::MUL)
6843       std::swap(LHS, RHS);
6844 
6845     SDValue MulLHS = LHS.getOperand(0);
6846     SDValue MulRHS = LHS.getOperand(1);
6847     SDValue AddRHS = RHS;
6848 
6849     // TODO: Maybe restrict if SGPR inputs.
6850     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
6851         numBitsUnsigned(MulRHS, DAG) <= 32) {
6852       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
6853       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
6854       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
6855       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
6856     }
6857 
6858     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
6859       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
6860       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
6861       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
6862       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
6863     }
6864 
6865     return SDValue();
6866   }
6867 
6868   if (VT != MVT::i32)
6869     return SDValue();
6870 
6871   // add x, zext (setcc) => addcarry x, 0, setcc
6872   // add x, sext (setcc) => subcarry x, 0, setcc
6873   unsigned Opc = LHS.getOpcode();
6874   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
6875       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
6876     std::swap(RHS, LHS);
6877 
6878   Opc = RHS.getOpcode();
6879   switch (Opc) {
6880   default: break;
6881   case ISD::ZERO_EXTEND:
6882   case ISD::SIGN_EXTEND:
6883   case ISD::ANY_EXTEND: {
6884     auto Cond = RHS.getOperand(0);
6885     if (!isBoolSGPR(Cond))
6886       break;
6887     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
6888     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
6889     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
6890     return DAG.getNode(Opc, SL, VTList, Args);
6891   }
6892   case ISD::ADDCARRY: {
6893     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
6894     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6895     if (!C || C->getZExtValue() != 0) break;
6896     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
6897     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
6898   }
6899   }
6900   return SDValue();
6901 }
6902 
6903 SDValue SITargetLowering::performSubCombine(SDNode *N,
6904                                             DAGCombinerInfo &DCI) const {
6905   SelectionDAG &DAG = DCI.DAG;
6906   EVT VT = N->getValueType(0);
6907 
6908   if (VT != MVT::i32)
6909     return SDValue();
6910 
6911   SDLoc SL(N);
6912   SDValue LHS = N->getOperand(0);
6913   SDValue RHS = N->getOperand(1);
6914 
6915   unsigned Opc = LHS.getOpcode();
6916   if (Opc != ISD::SUBCARRY)
6917     std::swap(RHS, LHS);
6918 
6919   if (LHS.getOpcode() == ISD::SUBCARRY) {
6920     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
6921     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6922     if (!C || C->getZExtValue() != 0)
6923       return SDValue();
6924     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
6925     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
6926   }
6927   return SDValue();
6928 }
6929 
6930 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
6931   DAGCombinerInfo &DCI) const {
6932 
6933   if (N->getValueType(0) != MVT::i32)
6934     return SDValue();
6935 
6936   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6937   if (!C || C->getZExtValue() != 0)
6938     return SDValue();
6939 
6940   SelectionDAG &DAG = DCI.DAG;
6941   SDValue LHS = N->getOperand(0);
6942 
6943   // addcarry (add x, y), 0, cc => addcarry x, y, cc
6944   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
6945   unsigned LHSOpc = LHS.getOpcode();
6946   unsigned Opc = N->getOpcode();
6947   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
6948       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
6949     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
6950     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
6951   }
6952   return SDValue();
6953 }
6954 
6955 SDValue SITargetLowering::performFAddCombine(SDNode *N,
6956                                              DAGCombinerInfo &DCI) const {
6957   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6958     return SDValue();
6959 
6960   SelectionDAG &DAG = DCI.DAG;
6961   EVT VT = N->getValueType(0);
6962 
6963   SDLoc SL(N);
6964   SDValue LHS = N->getOperand(0);
6965   SDValue RHS = N->getOperand(1);
6966 
6967   // These should really be instruction patterns, but writing patterns with
6968   // source modiifiers is a pain.
6969 
6970   // fadd (fadd (a, a), b) -> mad 2.0, a, b
6971   if (LHS.getOpcode() == ISD::FADD) {
6972     SDValue A = LHS.getOperand(0);
6973     if (A == LHS.getOperand(1)) {
6974       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
6975       if (FusedOp != 0) {
6976         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6977         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
6978       }
6979     }
6980   }
6981 
6982   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
6983   if (RHS.getOpcode() == ISD::FADD) {
6984     SDValue A = RHS.getOperand(0);
6985     if (A == RHS.getOperand(1)) {
6986       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
6987       if (FusedOp != 0) {
6988         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
6989         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
6990       }
6991     }
6992   }
6993 
6994   return SDValue();
6995 }
6996 
6997 SDValue SITargetLowering::performFSubCombine(SDNode *N,
6998                                              DAGCombinerInfo &DCI) const {
6999   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7000     return SDValue();
7001 
7002   SelectionDAG &DAG = DCI.DAG;
7003   SDLoc SL(N);
7004   EVT VT = N->getValueType(0);
7005   assert(!VT.isVector());
7006 
7007   // Try to get the fneg to fold into the source modifier. This undoes generic
7008   // DAG combines and folds them into the mad.
7009   //
7010   // Only do this if we are not trying to support denormals. v_mad_f32 does
7011   // not support denormals ever.
7012   SDValue LHS = N->getOperand(0);
7013   SDValue RHS = N->getOperand(1);
7014   if (LHS.getOpcode() == ISD::FADD) {
7015     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7016     SDValue A = LHS.getOperand(0);
7017     if (A == LHS.getOperand(1)) {
7018       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7019       if (FusedOp != 0){
7020         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7021         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7022 
7023         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7024       }
7025     }
7026   }
7027 
7028   if (RHS.getOpcode() == ISD::FADD) {
7029     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7030 
7031     SDValue A = RHS.getOperand(0);
7032     if (A == RHS.getOperand(1)) {
7033       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7034       if (FusedOp != 0){
7035         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7036         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7037       }
7038     }
7039   }
7040 
7041   return SDValue();
7042 }
7043 
7044 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7045                                               DAGCombinerInfo &DCI) const {
7046   SelectionDAG &DAG = DCI.DAG;
7047   SDLoc SL(N);
7048 
7049   SDValue LHS = N->getOperand(0);
7050   SDValue RHS = N->getOperand(1);
7051   EVT VT = LHS.getValueType();
7052   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7053 
7054   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7055   if (!CRHS) {
7056     CRHS = dyn_cast<ConstantSDNode>(LHS);
7057     if (CRHS) {
7058       std::swap(LHS, RHS);
7059       CC = getSetCCSwappedOperands(CC);
7060     }
7061   }
7062 
7063   if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7064       isBoolSGPR(LHS.getOperand(0))) {
7065     // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7066     // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7067     // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
7068     // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
7069     if ((CRHS->isAllOnesValue() &&
7070          (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7071         (CRHS->isNullValue() &&
7072          (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7073       return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7074                          DAG.getConstant(-1, SL, MVT::i1));
7075     if ((CRHS->isAllOnesValue() &&
7076          (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7077         (CRHS->isNullValue() &&
7078          (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7079       return LHS.getOperand(0);
7080   }
7081 
7082   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7083                                            VT != MVT::f16))
7084     return SDValue();
7085 
7086   // Match isinf pattern
7087   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7088   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7089     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7090     if (!CRHS)
7091       return SDValue();
7092 
7093     const APFloat &APF = CRHS->getValueAPF();
7094     if (APF.isInfinity() && !APF.isNegative()) {
7095       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7096       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7097                          DAG.getConstant(Mask, SL, MVT::i32));
7098     }
7099   }
7100 
7101   return SDValue();
7102 }
7103 
7104 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7105                                                      DAGCombinerInfo &DCI) const {
7106   SelectionDAG &DAG = DCI.DAG;
7107   SDLoc SL(N);
7108   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7109 
7110   SDValue Src = N->getOperand(0);
7111   SDValue Srl = N->getOperand(0);
7112   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7113     Srl = Srl.getOperand(0);
7114 
7115   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7116   if (Srl.getOpcode() == ISD::SRL) {
7117     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7118     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7119     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7120 
7121     if (const ConstantSDNode *C =
7122         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7123       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7124                                EVT(MVT::i32));
7125 
7126       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7127       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7128         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7129                            MVT::f32, Srl);
7130       }
7131     }
7132   }
7133 
7134   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7135 
7136   KnownBits Known;
7137   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7138                                         !DCI.isBeforeLegalizeOps());
7139   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7140   if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7141       TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7142     DCI.CommitTargetLoweringOpt(TLO);
7143   }
7144 
7145   return SDValue();
7146 }
7147 
7148 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7149                                             DAGCombinerInfo &DCI) const {
7150   switch (N->getOpcode()) {
7151   default:
7152     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7153   case ISD::ADD:
7154     return performAddCombine(N, DCI);
7155   case ISD::SUB:
7156     return performSubCombine(N, DCI);
7157   case ISD::ADDCARRY:
7158   case ISD::SUBCARRY:
7159     return performAddCarrySubCarryCombine(N, DCI);
7160   case ISD::FADD:
7161     return performFAddCombine(N, DCI);
7162   case ISD::FSUB:
7163     return performFSubCombine(N, DCI);
7164   case ISD::SETCC:
7165     return performSetCCCombine(N, DCI);
7166   case ISD::FMAXNUM:
7167   case ISD::FMINNUM:
7168   case ISD::SMAX:
7169   case ISD::SMIN:
7170   case ISD::UMAX:
7171   case ISD::UMIN:
7172   case AMDGPUISD::FMIN_LEGACY:
7173   case AMDGPUISD::FMAX_LEGACY: {
7174     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7175         getTargetMachine().getOptLevel() > CodeGenOpt::None)
7176       return performMinMaxCombine(N, DCI);
7177     break;
7178   }
7179   case ISD::LOAD:
7180   case ISD::STORE:
7181   case ISD::ATOMIC_LOAD:
7182   case ISD::ATOMIC_STORE:
7183   case ISD::ATOMIC_CMP_SWAP:
7184   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7185   case ISD::ATOMIC_SWAP:
7186   case ISD::ATOMIC_LOAD_ADD:
7187   case ISD::ATOMIC_LOAD_SUB:
7188   case ISD::ATOMIC_LOAD_AND:
7189   case ISD::ATOMIC_LOAD_OR:
7190   case ISD::ATOMIC_LOAD_XOR:
7191   case ISD::ATOMIC_LOAD_NAND:
7192   case ISD::ATOMIC_LOAD_MIN:
7193   case ISD::ATOMIC_LOAD_MAX:
7194   case ISD::ATOMIC_LOAD_UMIN:
7195   case ISD::ATOMIC_LOAD_UMAX:
7196   case AMDGPUISD::ATOMIC_INC:
7197   case AMDGPUISD::ATOMIC_DEC:
7198   case AMDGPUISD::ATOMIC_LOAD_FADD:
7199   case AMDGPUISD::ATOMIC_LOAD_FMIN:
7200   case AMDGPUISD::ATOMIC_LOAD_FMAX:  // TODO: Target mem intrinsics.
7201     if (DCI.isBeforeLegalize())
7202       break;
7203     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7204   case ISD::AND:
7205     return performAndCombine(N, DCI);
7206   case ISD::OR:
7207     return performOrCombine(N, DCI);
7208   case ISD::XOR:
7209     return performXorCombine(N, DCI);
7210   case ISD::ZERO_EXTEND:
7211     return performZeroExtendCombine(N, DCI);
7212   case AMDGPUISD::FP_CLASS:
7213     return performClassCombine(N, DCI);
7214   case ISD::FCANONICALIZE:
7215     return performFCanonicalizeCombine(N, DCI);
7216   case AMDGPUISD::FRACT:
7217   case AMDGPUISD::RCP:
7218   case AMDGPUISD::RSQ:
7219   case AMDGPUISD::RCP_LEGACY:
7220   case AMDGPUISD::RSQ_LEGACY:
7221   case AMDGPUISD::RSQ_CLAMP:
7222   case AMDGPUISD::LDEXP: {
7223     SDValue Src = N->getOperand(0);
7224     if (Src.isUndef())
7225       return Src;
7226     break;
7227   }
7228   case ISD::SINT_TO_FP:
7229   case ISD::UINT_TO_FP:
7230     return performUCharToFloatCombine(N, DCI);
7231   case AMDGPUISD::CVT_F32_UBYTE0:
7232   case AMDGPUISD::CVT_F32_UBYTE1:
7233   case AMDGPUISD::CVT_F32_UBYTE2:
7234   case AMDGPUISD::CVT_F32_UBYTE3:
7235     return performCvtF32UByteNCombine(N, DCI);
7236   case AMDGPUISD::FMED3:
7237     return performFMed3Combine(N, DCI);
7238   case AMDGPUISD::CVT_PKRTZ_F16_F32:
7239     return performCvtPkRTZCombine(N, DCI);
7240   case ISD::SCALAR_TO_VECTOR: {
7241     SelectionDAG &DAG = DCI.DAG;
7242     EVT VT = N->getValueType(0);
7243 
7244     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7245     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7246       SDLoc SL(N);
7247       SDValue Src = N->getOperand(0);
7248       EVT EltVT = Src.getValueType();
7249       if (EltVT == MVT::f16)
7250         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7251 
7252       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7253       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7254     }
7255 
7256     break;
7257   }
7258   case ISD::EXTRACT_VECTOR_ELT:
7259     return performExtractVectorEltCombine(N, DCI);
7260   case ISD::BUILD_VECTOR:
7261     return performBuildVectorCombine(N, DCI);
7262   }
7263   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7264 }
7265 
7266 /// \brief Helper function for adjustWritemask
7267 static unsigned SubIdx2Lane(unsigned Idx) {
7268   switch (Idx) {
7269   default: return 0;
7270   case AMDGPU::sub0: return 0;
7271   case AMDGPU::sub1: return 1;
7272   case AMDGPU::sub2: return 2;
7273   case AMDGPU::sub3: return 3;
7274   }
7275 }
7276 
7277 /// \brief Adjust the writemask of MIMG instructions
7278 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7279                                           SelectionDAG &DAG) const {
7280   SDNode *Users[4] = { nullptr };
7281   unsigned Lane = 0;
7282   unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3;
7283   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7284   unsigned NewDmask = 0;
7285   bool HasChain = Node->getNumValues() > 1;
7286 
7287   if (OldDmask == 0) {
7288     // These are folded out, but on the chance it happens don't assert.
7289     return Node;
7290   }
7291 
7292   // Try to figure out the used register components
7293   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7294        I != E; ++I) {
7295 
7296     // Don't look at users of the chain.
7297     if (I.getUse().getResNo() != 0)
7298       continue;
7299 
7300     // Abort if we can't understand the usage
7301     if (!I->isMachineOpcode() ||
7302         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7303       return Node;
7304 
7305     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7306     // Note that subregs are packed, i.e. Lane==0 is the first bit set
7307     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7308     // set, etc.
7309     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7310 
7311     // Set which texture component corresponds to the lane.
7312     unsigned Comp;
7313     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7314       Comp = countTrailingZeros(Dmask);
7315       Dmask &= ~(1 << Comp);
7316     }
7317 
7318     // Abort if we have more than one user per component
7319     if (Users[Lane])
7320       return Node;
7321 
7322     Users[Lane] = *I;
7323     NewDmask |= 1 << Comp;
7324   }
7325 
7326   // Abort if there's no change
7327   if (NewDmask == OldDmask)
7328     return Node;
7329 
7330   unsigned BitsSet = countPopulation(NewDmask);
7331 
7332   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7333   int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII,
7334                                           Node->getMachineOpcode(), BitsSet);
7335   assert(NewOpcode != -1 &&
7336          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7337          "failed to find equivalent MIMG op");
7338 
7339   // Adjust the writemask in the node
7340   SmallVector<SDValue, 12> Ops;
7341   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
7342   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
7343   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
7344 
7345   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
7346 
7347   MVT ResultVT = BitsSet == 1 ?
7348     SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
7349   SDVTList NewVTList = HasChain ?
7350     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
7351 
7352 
7353   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
7354                                               NewVTList, Ops);
7355 
7356   if (HasChain) {
7357     // Update chain.
7358     NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
7359     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
7360   }
7361 
7362   if (BitsSet == 1) {
7363     assert(Node->hasNUsesOfValue(1, 0));
7364     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
7365                                       SDLoc(Node), Users[Lane]->getValueType(0),
7366                                       SDValue(NewNode, 0));
7367     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
7368     return nullptr;
7369   }
7370 
7371   // Update the users of the node with the new indices
7372   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
7373     SDNode *User = Users[i];
7374     if (!User)
7375       continue;
7376 
7377     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
7378     DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
7379 
7380     switch (Idx) {
7381     default: break;
7382     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
7383     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
7384     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
7385     }
7386   }
7387 
7388   DAG.RemoveDeadNode(Node);
7389   return nullptr;
7390 }
7391 
7392 static bool isFrameIndexOp(SDValue Op) {
7393   if (Op.getOpcode() == ISD::AssertZext)
7394     Op = Op.getOperand(0);
7395 
7396   return isa<FrameIndexSDNode>(Op);
7397 }
7398 
7399 /// \brief Legalize target independent instructions (e.g. INSERT_SUBREG)
7400 /// with frame index operands.
7401 /// LLVM assumes that inputs are to these instructions are registers.
7402 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
7403                                                         SelectionDAG &DAG) const {
7404   if (Node->getOpcode() == ISD::CopyToReg) {
7405     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
7406     SDValue SrcVal = Node->getOperand(2);
7407 
7408     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
7409     // to try understanding copies to physical registers.
7410     if (SrcVal.getValueType() == MVT::i1 &&
7411         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
7412       SDLoc SL(Node);
7413       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7414       SDValue VReg = DAG.getRegister(
7415         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
7416 
7417       SDNode *Glued = Node->getGluedNode();
7418       SDValue ToVReg
7419         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
7420                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
7421       SDValue ToResultReg
7422         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
7423                            VReg, ToVReg.getValue(1));
7424       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
7425       DAG.RemoveDeadNode(Node);
7426       return ToResultReg.getNode();
7427     }
7428   }
7429 
7430   SmallVector<SDValue, 8> Ops;
7431   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
7432     if (!isFrameIndexOp(Node->getOperand(i))) {
7433       Ops.push_back(Node->getOperand(i));
7434       continue;
7435     }
7436 
7437     SDLoc DL(Node);
7438     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
7439                                      Node->getOperand(i).getValueType(),
7440                                      Node->getOperand(i)), 0));
7441   }
7442 
7443   return DAG.UpdateNodeOperands(Node, Ops);
7444 }
7445 
7446 /// \brief Fold the instructions after selecting them.
7447 /// Returns null if users were already updated.
7448 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
7449                                           SelectionDAG &DAG) const {
7450   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7451   unsigned Opcode = Node->getMachineOpcode();
7452 
7453   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
7454       !TII->isGather4(Opcode) && !TII->isD16(Opcode)) {
7455     return adjustWritemask(Node, DAG);
7456   }
7457 
7458   if (Opcode == AMDGPU::INSERT_SUBREG ||
7459       Opcode == AMDGPU::REG_SEQUENCE) {
7460     legalizeTargetIndependentNode(Node, DAG);
7461     return Node;
7462   }
7463 
7464   switch (Opcode) {
7465   case AMDGPU::V_DIV_SCALE_F32:
7466   case AMDGPU::V_DIV_SCALE_F64: {
7467     // Satisfy the operand register constraint when one of the inputs is
7468     // undefined. Ordinarily each undef value will have its own implicit_def of
7469     // a vreg, so force these to use a single register.
7470     SDValue Src0 = Node->getOperand(0);
7471     SDValue Src1 = Node->getOperand(1);
7472     SDValue Src2 = Node->getOperand(2);
7473 
7474     if ((Src0.isMachineOpcode() &&
7475          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
7476         (Src0 == Src1 || Src0 == Src2))
7477       break;
7478 
7479     MVT VT = Src0.getValueType().getSimpleVT();
7480     const TargetRegisterClass *RC = getRegClassFor(VT);
7481 
7482     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7483     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
7484 
7485     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
7486                                       UndefReg, Src0, SDValue());
7487 
7488     // src0 must be the same register as src1 or src2, even if the value is
7489     // undefined, so make sure we don't violate this constraint.
7490     if (Src0.isMachineOpcode() &&
7491         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
7492       if (Src1.isMachineOpcode() &&
7493           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7494         Src0 = Src1;
7495       else if (Src2.isMachineOpcode() &&
7496                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7497         Src0 = Src2;
7498       else {
7499         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
7500         Src0 = UndefReg;
7501         Src1 = UndefReg;
7502       }
7503     } else
7504       break;
7505 
7506     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
7507     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
7508       Ops.push_back(Node->getOperand(I));
7509 
7510     Ops.push_back(ImpDef.getValue(1));
7511     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
7512   }
7513   default:
7514     break;
7515   }
7516 
7517   return Node;
7518 }
7519 
7520 /// \brief Assign the register class depending on the number of
7521 /// bits set in the writemask
7522 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
7523                                                      SDNode *Node) const {
7524   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7525 
7526   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7527 
7528   if (TII->isVOP3(MI.getOpcode())) {
7529     // Make sure constant bus requirements are respected.
7530     TII->legalizeOperandsVOP3(MRI, MI);
7531     return;
7532   }
7533 
7534   // Replace unused atomics with the no return version.
7535   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
7536   if (NoRetAtomicOp != -1) {
7537     if (!Node->hasAnyUseOfValue(0)) {
7538       MI.setDesc(TII->get(NoRetAtomicOp));
7539       MI.RemoveOperand(0);
7540       return;
7541     }
7542 
7543     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
7544     // instruction, because the return type of these instructions is a vec2 of
7545     // the memory type, so it can be tied to the input operand.
7546     // This means these instructions always have a use, so we need to add a
7547     // special case to check if the atomic has only one extract_subreg use,
7548     // which itself has no uses.
7549     if ((Node->hasNUsesOfValue(1, 0) &&
7550          Node->use_begin()->isMachineOpcode() &&
7551          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
7552          !Node->use_begin()->hasAnyUseOfValue(0))) {
7553       unsigned Def = MI.getOperand(0).getReg();
7554 
7555       // Change this into a noret atomic.
7556       MI.setDesc(TII->get(NoRetAtomicOp));
7557       MI.RemoveOperand(0);
7558 
7559       // If we only remove the def operand from the atomic instruction, the
7560       // extract_subreg will be left with a use of a vreg without a def.
7561       // So we need to insert an implicit_def to avoid machine verifier
7562       // errors.
7563       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
7564               TII->get(AMDGPU::IMPLICIT_DEF), Def);
7565     }
7566     return;
7567   }
7568 }
7569 
7570 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
7571                               uint64_t Val) {
7572   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
7573   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
7574 }
7575 
7576 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
7577                                                 const SDLoc &DL,
7578                                                 SDValue Ptr) const {
7579   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7580 
7581   // Build the half of the subregister with the constants before building the
7582   // full 128-bit register. If we are building multiple resource descriptors,
7583   // this will allow CSEing of the 2-component register.
7584   const SDValue Ops0[] = {
7585     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
7586     buildSMovImm32(DAG, DL, 0),
7587     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7588     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
7589     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
7590   };
7591 
7592   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
7593                                                 MVT::v2i32, Ops0), 0);
7594 
7595   // Combine the constants and the pointer.
7596   const SDValue Ops1[] = {
7597     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7598     Ptr,
7599     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
7600     SubRegHi,
7601     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
7602   };
7603 
7604   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
7605 }
7606 
7607 /// \brief Return a resource descriptor with the 'Add TID' bit enabled
7608 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
7609 ///        of the resource descriptor) to create an offset, which is added to
7610 ///        the resource pointer.
7611 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
7612                                            SDValue Ptr, uint32_t RsrcDword1,
7613                                            uint64_t RsrcDword2And3) const {
7614   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
7615   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
7616   if (RsrcDword1) {
7617     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
7618                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
7619                     0);
7620   }
7621 
7622   SDValue DataLo = buildSMovImm32(DAG, DL,
7623                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
7624   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
7625 
7626   const SDValue Ops[] = {
7627     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
7628     PtrLo,
7629     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
7630     PtrHi,
7631     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
7632     DataLo,
7633     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
7634     DataHi,
7635     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
7636   };
7637 
7638   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
7639 }
7640 
7641 //===----------------------------------------------------------------------===//
7642 //                         SI Inline Assembly Support
7643 //===----------------------------------------------------------------------===//
7644 
7645 std::pair<unsigned, const TargetRegisterClass *>
7646 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
7647                                                StringRef Constraint,
7648                                                MVT VT) const {
7649   if (!isTypeLegal(VT))
7650     return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7651 
7652   if (Constraint.size() == 1) {
7653     switch (Constraint[0]) {
7654     case 's':
7655     case 'r':
7656       switch (VT.getSizeInBits()) {
7657       default:
7658         return std::make_pair(0U, nullptr);
7659       case 32:
7660       case 16:
7661         return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass);
7662       case 64:
7663         return std::make_pair(0U, &AMDGPU::SGPR_64RegClass);
7664       case 128:
7665         return std::make_pair(0U, &AMDGPU::SReg_128RegClass);
7666       case 256:
7667         return std::make_pair(0U, &AMDGPU::SReg_256RegClass);
7668       case 512:
7669         return std::make_pair(0U, &AMDGPU::SReg_512RegClass);
7670       }
7671 
7672     case 'v':
7673       switch (VT.getSizeInBits()) {
7674       default:
7675         return std::make_pair(0U, nullptr);
7676       case 32:
7677       case 16:
7678         return std::make_pair(0U, &AMDGPU::VGPR_32RegClass);
7679       case 64:
7680         return std::make_pair(0U, &AMDGPU::VReg_64RegClass);
7681       case 96:
7682         return std::make_pair(0U, &AMDGPU::VReg_96RegClass);
7683       case 128:
7684         return std::make_pair(0U, &AMDGPU::VReg_128RegClass);
7685       case 256:
7686         return std::make_pair(0U, &AMDGPU::VReg_256RegClass);
7687       case 512:
7688         return std::make_pair(0U, &AMDGPU::VReg_512RegClass);
7689       }
7690     }
7691   }
7692 
7693   if (Constraint.size() > 1) {
7694     const TargetRegisterClass *RC = nullptr;
7695     if (Constraint[1] == 'v') {
7696       RC = &AMDGPU::VGPR_32RegClass;
7697     } else if (Constraint[1] == 's') {
7698       RC = &AMDGPU::SGPR_32RegClass;
7699     }
7700 
7701     if (RC) {
7702       uint32_t Idx;
7703       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
7704       if (!Failed && Idx < RC->getNumRegs())
7705         return std::make_pair(RC->getRegister(Idx), RC);
7706     }
7707   }
7708   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
7709 }
7710 
7711 SITargetLowering::ConstraintType
7712 SITargetLowering::getConstraintType(StringRef Constraint) const {
7713   if (Constraint.size() == 1) {
7714     switch (Constraint[0]) {
7715     default: break;
7716     case 's':
7717     case 'v':
7718       return C_RegisterClass;
7719     }
7720   }
7721   return TargetLowering::getConstraintType(Constraint);
7722 }
7723 
7724 // Figure out which registers should be reserved for stack access. Only after
7725 // the function is legalized do we know all of the non-spill stack objects or if
7726 // calls are present.
7727 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
7728   MachineRegisterInfo &MRI = MF.getRegInfo();
7729   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
7730   const MachineFrameInfo &MFI = MF.getFrameInfo();
7731   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
7732   const SIRegisterInfo *TRI = ST.getRegisterInfo();
7733 
7734   if (Info->isEntryFunction()) {
7735     // Callable functions have fixed registers used for stack access.
7736     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
7737   }
7738 
7739   // We have to assume the SP is needed in case there are calls in the function
7740   // during lowering. Calls are only detected after the function is
7741   // lowered. We're about to reserve registers, so don't bother using it if we
7742   // aren't really going to use it.
7743   bool NeedSP = !Info->isEntryFunction() ||
7744     MFI.hasVarSizedObjects() ||
7745     MFI.hasCalls();
7746 
7747   if (NeedSP) {
7748     unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
7749     Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
7750 
7751     assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
7752     assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
7753                                Info->getStackPtrOffsetReg()));
7754     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
7755   }
7756 
7757   MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
7758   MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
7759   MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
7760                      Info->getScratchWaveOffsetReg());
7761 
7762   TargetLoweringBase::finalizeLowering(MF);
7763 }
7764 
7765 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
7766                                                      KnownBits &Known,
7767                                                      const APInt &DemandedElts,
7768                                                      const SelectionDAG &DAG,
7769                                                      unsigned Depth) const {
7770   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
7771                                                 DAG, Depth);
7772 
7773   if (getSubtarget()->enableHugePrivateBuffer())
7774     return;
7775 
7776   // Technically it may be possible to have a dispatch with a single workitem
7777   // that uses the full private memory size, but that's not really useful. We
7778   // can't use vaddr in MUBUF instructions if we don't know the address
7779   // calculation won't overflow, so assume the sign bit is never set.
7780   Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
7781 }
7782