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