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