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