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