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