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