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<bool> DisableLoopAlignment(
97   "amdgpu-disable-loop-alignment",
98   cl::desc("Do not align and prefetch loops"),
99   cl::init(false));
100 
101 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
102   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
103   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
104     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
105       return AMDGPU::SGPR0 + Reg;
106     }
107   }
108   llvm_unreachable("Cannot allocate sgpr");
109 }
110 
111 SITargetLowering::SITargetLowering(const TargetMachine &TM,
112                                    const GCNSubtarget &STI)
113     : AMDGPUTargetLowering(TM, STI),
114       Subtarget(&STI) {
115   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
116   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
117 
118   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
119   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
120 
121   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
122   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
123   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
124 
125   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
126   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
127 
128   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130 
131   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
133 
134   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
135   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
136 
137   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
138   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
139 
140   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
141   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
142 
143   if (Subtarget->has16BitInsts()) {
144     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
146 
147     // Unless there are also VOP3P operations, not operations are really legal.
148     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
149     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
150     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
151     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
152   }
153 
154   if (Subtarget->hasMAIInsts()) {
155     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
156     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
157   }
158 
159   computeRegisterProperties(Subtarget->getRegisterInfo());
160 
161   // We need to custom lower vector stores from local memory
162   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
165   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
166   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
167   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
168   setOperationAction(ISD::LOAD, MVT::i1, Custom);
169   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
170 
171   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
175   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
176   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
177   setOperationAction(ISD::STORE, MVT::i1, Custom);
178   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
179 
180   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
181   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
182   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
183   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
184   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
185   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
186   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
187   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
188   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
189   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
190   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
191 
192   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
193   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
194 
195   setOperationAction(ISD::SELECT, MVT::i1, Promote);
196   setOperationAction(ISD::SELECT, MVT::i64, Custom);
197   setOperationAction(ISD::SELECT, MVT::f64, Promote);
198   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
199 
200   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
201   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
202   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
203   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
204   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
205 
206   setOperationAction(ISD::SETCC, MVT::i1, Promote);
207   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
208   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
209   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
210 
211   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
212   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
213 
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
221   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
222 
223   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
224   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
225   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
226   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
227   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
228   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
229 
230   setOperationAction(ISD::UADDO, MVT::i32, Legal);
231   setOperationAction(ISD::USUBO, MVT::i32, Legal);
232 
233   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
234   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
235 
236   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
237   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
238   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
239 
240 #if 0
241   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
242   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
243 #endif
244 
245   // We only support LOAD/STORE and vector manipulation ops for vectors
246   // with > 4 elements.
247   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
248                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
249                   MVT::v32i32, MVT::v32f32 }) {
250     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
251       switch (Op) {
252       case ISD::LOAD:
253       case ISD::STORE:
254       case ISD::BUILD_VECTOR:
255       case ISD::BITCAST:
256       case ISD::EXTRACT_VECTOR_ELT:
257       case ISD::INSERT_VECTOR_ELT:
258       case ISD::INSERT_SUBVECTOR:
259       case ISD::EXTRACT_SUBVECTOR:
260       case ISD::SCALAR_TO_VECTOR:
261         break;
262       case ISD::CONCAT_VECTORS:
263         setOperationAction(Op, VT, Custom);
264         break;
265       default:
266         setOperationAction(Op, VT, Expand);
267         break;
268       }
269     }
270   }
271 
272   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
273 
274   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
275   // is expanded to avoid having two separate loops in case the index is a VGPR.
276 
277   // Most operations are naturally 32-bit vector operations. We only support
278   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
279   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
280     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
281     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
284     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
285 
286     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
287     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
288 
289     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
290     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
291   }
292 
293   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
294   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
295   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
296   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
297 
298   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
299   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
300 
301   // Avoid stack access for these.
302   // TODO: Generalize to more vector types.
303   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
304   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
305   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
306   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
307 
308   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
309   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
310   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
311   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
312   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
313 
314   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
315   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
316   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
317 
318   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
319   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
321   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
322 
323   // Deal with vec3 vector operations when widened to vec4.
324   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
325   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
326   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
327   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
328 
329   // Deal with vec5 vector operations when widened to vec8.
330   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
331   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
332   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
333   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
334 
335   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
336   // and output demarshalling
337   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
338   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
339 
340   // We can't return success/failure, only the old value,
341   // let LLVM add the comparison
342   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
343   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
344 
345   if (Subtarget->hasFlatAddressSpace()) {
346     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
347     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
348   }
349 
350   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
351   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
352 
353   // On SI this is s_memtime and s_memrealtime on VI.
354   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
355   setOperationAction(ISD::TRAP, MVT::Other, Custom);
356   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
357 
358   if (Subtarget->has16BitInsts()) {
359     setOperationAction(ISD::FLOG, MVT::f16, Custom);
360     setOperationAction(ISD::FEXP, MVT::f16, Custom);
361     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
362   }
363 
364   // v_mad_f32 does not support denormals according to some sources.
365   if (!Subtarget->hasFP32Denormals())
366     setOperationAction(ISD::FMAD, MVT::f32, Legal);
367 
368   if (!Subtarget->hasBFI()) {
369     // fcopysign can be done in a single instruction with BFI.
370     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
371     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
372   }
373 
374   if (!Subtarget->hasBCNT(32))
375     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
376 
377   if (!Subtarget->hasBCNT(64))
378     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
379 
380   if (Subtarget->hasFFBH())
381     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
382 
383   if (Subtarget->hasFFBL())
384     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
385 
386   // We only really have 32-bit BFE instructions (and 16-bit on VI).
387   //
388   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
389   // effort to match them now. We want this to be false for i64 cases when the
390   // extraction isn't restricted to the upper or lower half. Ideally we would
391   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
392   // span the midpoint are probably relatively rare, so don't worry about them
393   // for now.
394   if (Subtarget->hasBFE())
395     setHasExtractBitsInsn(true);
396 
397   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
398   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
399   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
400   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
401 
402 
403   // These are really only legal for ieee_mode functions. We should be avoiding
404   // them for functions that don't have ieee_mode enabled, so just say they are
405   // legal.
406   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
407   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
408   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
409   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
410 
411 
412   if (Subtarget->haveRoundOpsF64()) {
413     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
414     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
415     setOperationAction(ISD::FRINT, MVT::f64, Legal);
416   } else {
417     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
418     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
419     setOperationAction(ISD::FRINT, MVT::f64, Custom);
420     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
421   }
422 
423   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
424 
425   setOperationAction(ISD::FSIN, MVT::f32, Custom);
426   setOperationAction(ISD::FCOS, MVT::f32, Custom);
427   setOperationAction(ISD::FDIV, MVT::f32, Custom);
428   setOperationAction(ISD::FDIV, MVT::f64, Custom);
429 
430   if (Subtarget->has16BitInsts()) {
431     setOperationAction(ISD::Constant, MVT::i16, Legal);
432 
433     setOperationAction(ISD::SMIN, MVT::i16, Legal);
434     setOperationAction(ISD::SMAX, MVT::i16, Legal);
435 
436     setOperationAction(ISD::UMIN, MVT::i16, Legal);
437     setOperationAction(ISD::UMAX, MVT::i16, Legal);
438 
439     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
440     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
441 
442     setOperationAction(ISD::ROTR, MVT::i16, Promote);
443     setOperationAction(ISD::ROTL, MVT::i16, Promote);
444 
445     setOperationAction(ISD::SDIV, MVT::i16, Promote);
446     setOperationAction(ISD::UDIV, MVT::i16, Promote);
447     setOperationAction(ISD::SREM, MVT::i16, Promote);
448     setOperationAction(ISD::UREM, MVT::i16, Promote);
449 
450     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
451     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
452 
453     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
454     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
455     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
456     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
457     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
458 
459     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
460 
461     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
462 
463     setOperationAction(ISD::LOAD, MVT::i16, Custom);
464 
465     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
466 
467     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
468     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
469     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
470     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
471 
472     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
473     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
474     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
475     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
476 
477     // F16 - Constant Actions.
478     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
479 
480     // F16 - Load/Store Actions.
481     setOperationAction(ISD::LOAD, MVT::f16, Promote);
482     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
483     setOperationAction(ISD::STORE, MVT::f16, Promote);
484     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
485 
486     // F16 - VOP1 Actions.
487     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
488     setOperationAction(ISD::FCOS, MVT::f16, Promote);
489     setOperationAction(ISD::FSIN, MVT::f16, Promote);
490     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
491     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
492     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
493     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
494     setOperationAction(ISD::FROUND, MVT::f16, Custom);
495 
496     // F16 - VOP2 Actions.
497     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
498     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
499 
500     setOperationAction(ISD::FDIV, MVT::f16, Custom);
501 
502     // F16 - VOP3 Actions.
503     setOperationAction(ISD::FMA, MVT::f16, Legal);
504     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
505       setOperationAction(ISD::FMAD, MVT::f16, Legal);
506 
507     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
508       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
509         switch (Op) {
510         case ISD::LOAD:
511         case ISD::STORE:
512         case ISD::BUILD_VECTOR:
513         case ISD::BITCAST:
514         case ISD::EXTRACT_VECTOR_ELT:
515         case ISD::INSERT_VECTOR_ELT:
516         case ISD::INSERT_SUBVECTOR:
517         case ISD::EXTRACT_SUBVECTOR:
518         case ISD::SCALAR_TO_VECTOR:
519           break;
520         case ISD::CONCAT_VECTORS:
521           setOperationAction(Op, VT, Custom);
522           break;
523         default:
524           setOperationAction(Op, VT, Expand);
525           break;
526         }
527       }
528     }
529 
530     // XXX - Do these do anything? Vector constants turn into build_vector.
531     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
532     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
533 
534     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
535     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
536 
537     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
538     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
539     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
540     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
541 
542     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
543     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
544     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
545     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
546 
547     setOperationAction(ISD::AND, MVT::v2i16, Promote);
548     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
549     setOperationAction(ISD::OR, MVT::v2i16, Promote);
550     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
551     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
552     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
553 
554     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
555     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
556     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
557     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
558 
559     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
560     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
561     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
562     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
563 
564     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
565     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
566     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
567     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
568 
569     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
570     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
571     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
572 
573     if (!Subtarget->hasVOP3PInsts()) {
574       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
575       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
576     }
577 
578     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
579     // This isn't really legal, but this avoids the legalizer unrolling it (and
580     // allows matching fneg (fabs x) patterns)
581     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
582 
583     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
584     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
585     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
586     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
587 
588     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
589     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
590 
591     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
592     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
593   }
594 
595   if (Subtarget->hasVOP3PInsts()) {
596     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
597     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
598     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
599     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
600     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
601     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
602     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
603     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
604     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
605     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
606 
607     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
608     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
609     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
610 
611     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
612     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
613 
614     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
615 
616     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
617     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
618 
619     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
620     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
621 
622     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
623     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
624     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
625     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
626     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
627     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
628 
629     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
630     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
631     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
632     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
633 
634     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
635     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
636     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
637 
638     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
639     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
640 
641     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
642     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
643     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
644 
645     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
646     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
647     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
648   }
649 
650   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
651   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
652 
653   if (Subtarget->has16BitInsts()) {
654     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
655     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
656     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
657     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
658   } else {
659     // Legalization hack.
660     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
661     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
662 
663     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
664     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
665   }
666 
667   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
668     setOperationAction(ISD::SELECT, VT, Custom);
669   }
670 
671   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
672   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
673   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
674   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
675   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
676   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
677   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
678 
679   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
680   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
681   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
682   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
683   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
684   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
685   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
686   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
687   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
688 
689   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
690   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
691   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
692   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
693   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
694   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
695   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
696   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
697 
698   setTargetDAGCombine(ISD::ADD);
699   setTargetDAGCombine(ISD::ADDCARRY);
700   setTargetDAGCombine(ISD::SUB);
701   setTargetDAGCombine(ISD::SUBCARRY);
702   setTargetDAGCombine(ISD::FADD);
703   setTargetDAGCombine(ISD::FSUB);
704   setTargetDAGCombine(ISD::FMINNUM);
705   setTargetDAGCombine(ISD::FMAXNUM);
706   setTargetDAGCombine(ISD::FMINNUM_IEEE);
707   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
708   setTargetDAGCombine(ISD::FMA);
709   setTargetDAGCombine(ISD::SMIN);
710   setTargetDAGCombine(ISD::SMAX);
711   setTargetDAGCombine(ISD::UMIN);
712   setTargetDAGCombine(ISD::UMAX);
713   setTargetDAGCombine(ISD::SETCC);
714   setTargetDAGCombine(ISD::AND);
715   setTargetDAGCombine(ISD::OR);
716   setTargetDAGCombine(ISD::XOR);
717   setTargetDAGCombine(ISD::SINT_TO_FP);
718   setTargetDAGCombine(ISD::UINT_TO_FP);
719   setTargetDAGCombine(ISD::FCANONICALIZE);
720   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
721   setTargetDAGCombine(ISD::ZERO_EXTEND);
722   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
723   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
724   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
725 
726   // All memory operations. Some folding on the pointer operand is done to help
727   // matching the constant offsets in the addressing modes.
728   setTargetDAGCombine(ISD::LOAD);
729   setTargetDAGCombine(ISD::STORE);
730   setTargetDAGCombine(ISD::ATOMIC_LOAD);
731   setTargetDAGCombine(ISD::ATOMIC_STORE);
732   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
733   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
734   setTargetDAGCombine(ISD::ATOMIC_SWAP);
735   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
736   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
737   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
738   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
739   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
740   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
741   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
742   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
743   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
744   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
745   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
746 
747   setSchedulingPreference(Sched::RegPressure);
748 }
749 
750 const GCNSubtarget *SITargetLowering::getSubtarget() const {
751   return Subtarget;
752 }
753 
754 //===----------------------------------------------------------------------===//
755 // TargetLowering queries
756 //===----------------------------------------------------------------------===//
757 
758 // v_mad_mix* support a conversion from f16 to f32.
759 //
760 // There is only one special case when denormals are enabled we don't currently,
761 // where this is OK to use.
762 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
763                                            EVT DestVT, EVT SrcVT) const {
764   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
765           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
766          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
767          SrcVT.getScalarType() == MVT::f16;
768 }
769 
770 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
771   // SI has some legal vector types, but no legal vector operations. Say no
772   // shuffles are legal in order to prefer scalarizing some vector operations.
773   return false;
774 }
775 
776 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
777                                                     CallingConv::ID CC,
778                                                     EVT VT) const {
779   if (CC == CallingConv::AMDGPU_KERNEL)
780     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
781 
782   if (VT.isVector()) {
783     EVT ScalarVT = VT.getScalarType();
784     unsigned Size = ScalarVT.getSizeInBits();
785     if (Size == 32)
786       return ScalarVT.getSimpleVT();
787 
788     if (Size > 32)
789       return MVT::i32;
790 
791     if (Size == 16 && Subtarget->has16BitInsts())
792       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
793   } else if (VT.getSizeInBits() > 32)
794     return MVT::i32;
795 
796   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
797 }
798 
799 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
800                                                          CallingConv::ID CC,
801                                                          EVT VT) const {
802   if (CC == CallingConv::AMDGPU_KERNEL)
803     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
804 
805   if (VT.isVector()) {
806     unsigned NumElts = VT.getVectorNumElements();
807     EVT ScalarVT = VT.getScalarType();
808     unsigned Size = ScalarVT.getSizeInBits();
809 
810     if (Size == 32)
811       return NumElts;
812 
813     if (Size > 32)
814       return NumElts * ((Size + 31) / 32);
815 
816     if (Size == 16 && Subtarget->has16BitInsts())
817       return (NumElts + 1) / 2;
818   } else if (VT.getSizeInBits() > 32)
819     return (VT.getSizeInBits() + 31) / 32;
820 
821   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
822 }
823 
824 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
825   LLVMContext &Context, CallingConv::ID CC,
826   EVT VT, EVT &IntermediateVT,
827   unsigned &NumIntermediates, MVT &RegisterVT) const {
828   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
829     unsigned NumElts = VT.getVectorNumElements();
830     EVT ScalarVT = VT.getScalarType();
831     unsigned Size = ScalarVT.getSizeInBits();
832     if (Size == 32) {
833       RegisterVT = ScalarVT.getSimpleVT();
834       IntermediateVT = RegisterVT;
835       NumIntermediates = NumElts;
836       return NumIntermediates;
837     }
838 
839     if (Size > 32) {
840       RegisterVT = MVT::i32;
841       IntermediateVT = RegisterVT;
842       NumIntermediates = NumElts * ((Size + 31) / 32);
843       return NumIntermediates;
844     }
845 
846     // FIXME: We should fix the ABI to be the same on targets without 16-bit
847     // support, but unless we can properly handle 3-vectors, it will be still be
848     // inconsistent.
849     if (Size == 16 && Subtarget->has16BitInsts()) {
850       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
851       IntermediateVT = RegisterVT;
852       NumIntermediates = (NumElts + 1) / 2;
853       return NumIntermediates;
854     }
855   }
856 
857   return TargetLowering::getVectorTypeBreakdownForCallingConv(
858     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
859 }
860 
861 static MVT memVTFromAggregate(Type *Ty) {
862   // Only limited forms of aggregate type currently expected.
863   assert(Ty->isStructTy() && "Expected struct type");
864 
865 
866   Type *ElementType = nullptr;
867   unsigned NumElts;
868   if (Ty->getContainedType(0)->isVectorTy()) {
869     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
870     ElementType = VecComponent->getElementType();
871     NumElts = VecComponent->getNumElements();
872   } else {
873     ElementType = Ty->getContainedType(0);
874     NumElts = 1;
875   }
876 
877   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
878 
879   // Calculate the size of the memVT type from the aggregate
880   unsigned Pow2Elts = 0;
881   unsigned ElementSize;
882   switch (ElementType->getTypeID()) {
883     default:
884       llvm_unreachable("Unknown type!");
885     case Type::IntegerTyID:
886       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
887       break;
888     case Type::HalfTyID:
889       ElementSize = 16;
890       break;
891     case Type::FloatTyID:
892       ElementSize = 32;
893       break;
894   }
895   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
896   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
897 
898   return MVT::getVectorVT(MVT::getVT(ElementType, false),
899                           Pow2Elts);
900 }
901 
902 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
903                                           const CallInst &CI,
904                                           MachineFunction &MF,
905                                           unsigned IntrID) const {
906   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
907           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
908     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
909                                                   (Intrinsic::ID)IntrID);
910     if (Attr.hasFnAttribute(Attribute::ReadNone))
911       return false;
912 
913     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
914 
915     if (RsrcIntr->IsImage) {
916       Info.ptrVal = MFI->getImagePSV(
917         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
918         CI.getArgOperand(RsrcIntr->RsrcArg));
919       Info.align.reset();
920     } else {
921       Info.ptrVal = MFI->getBufferPSV(
922         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
923         CI.getArgOperand(RsrcIntr->RsrcArg));
924     }
925 
926     Info.flags = MachineMemOperand::MODereferenceable;
927     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
928       Info.opc = ISD::INTRINSIC_W_CHAIN;
929       Info.memVT = MVT::getVT(CI.getType(), true);
930       if (Info.memVT == MVT::Other) {
931         // Some intrinsics return an aggregate type - special case to work out
932         // the correct memVT
933         Info.memVT = memVTFromAggregate(CI.getType());
934       }
935       Info.flags |= MachineMemOperand::MOLoad;
936     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
937       Info.opc = ISD::INTRINSIC_VOID;
938       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
939       Info.flags |= MachineMemOperand::MOStore;
940     } else {
941       // Atomic
942       Info.opc = ISD::INTRINSIC_W_CHAIN;
943       Info.memVT = MVT::getVT(CI.getType());
944       Info.flags = MachineMemOperand::MOLoad |
945                    MachineMemOperand::MOStore |
946                    MachineMemOperand::MODereferenceable;
947 
948       // XXX - Should this be volatile without known ordering?
949       Info.flags |= MachineMemOperand::MOVolatile;
950     }
951     return true;
952   }
953 
954   switch (IntrID) {
955   case Intrinsic::amdgcn_atomic_inc:
956   case Intrinsic::amdgcn_atomic_dec:
957   case Intrinsic::amdgcn_ds_ordered_add:
958   case Intrinsic::amdgcn_ds_ordered_swap:
959   case Intrinsic::amdgcn_ds_fadd:
960   case Intrinsic::amdgcn_ds_fmin:
961   case Intrinsic::amdgcn_ds_fmax: {
962     Info.opc = ISD::INTRINSIC_W_CHAIN;
963     Info.memVT = MVT::getVT(CI.getType());
964     Info.ptrVal = CI.getOperand(0);
965     Info.align.reset();
966     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
967 
968     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
969     if (!Vol->isZero())
970       Info.flags |= MachineMemOperand::MOVolatile;
971 
972     return true;
973   }
974   case Intrinsic::amdgcn_buffer_atomic_fadd: {
975     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
976 
977     Info.opc = ISD::INTRINSIC_VOID;
978     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
979     Info.ptrVal = MFI->getBufferPSV(
980       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
981       CI.getArgOperand(1));
982     Info.align.reset();
983     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
984 
985     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
986     if (!Vol || !Vol->isZero())
987       Info.flags |= MachineMemOperand::MOVolatile;
988 
989     return true;
990   }
991   case Intrinsic::amdgcn_global_atomic_fadd: {
992     Info.opc = ISD::INTRINSIC_VOID;
993     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
994                             ->getPointerElementType());
995     Info.ptrVal = CI.getOperand(0);
996     Info.align.reset();
997     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
998 
999     return true;
1000   }
1001   case Intrinsic::amdgcn_ds_append:
1002   case Intrinsic::amdgcn_ds_consume: {
1003     Info.opc = ISD::INTRINSIC_W_CHAIN;
1004     Info.memVT = MVT::getVT(CI.getType());
1005     Info.ptrVal = CI.getOperand(0);
1006     Info.align.reset();
1007     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1008 
1009     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1010     if (!Vol->isZero())
1011       Info.flags |= MachineMemOperand::MOVolatile;
1012 
1013     return true;
1014   }
1015   case Intrinsic::amdgcn_ds_gws_init:
1016   case Intrinsic::amdgcn_ds_gws_barrier:
1017   case Intrinsic::amdgcn_ds_gws_sema_v:
1018   case Intrinsic::amdgcn_ds_gws_sema_br:
1019   case Intrinsic::amdgcn_ds_gws_sema_p:
1020   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1021     Info.opc = ISD::INTRINSIC_VOID;
1022 
1023     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1024     Info.ptrVal =
1025         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1026 
1027     // This is an abstract access, but we need to specify a type and size.
1028     Info.memVT = MVT::i32;
1029     Info.size = 4;
1030     Info.align = Align(4);
1031 
1032     Info.flags = MachineMemOperand::MOStore;
1033     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1034       Info.flags = MachineMemOperand::MOLoad;
1035     return true;
1036   }
1037   default:
1038     return false;
1039   }
1040 }
1041 
1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1043                                             SmallVectorImpl<Value*> &Ops,
1044                                             Type *&AccessTy) const {
1045   switch (II->getIntrinsicID()) {
1046   case Intrinsic::amdgcn_atomic_inc:
1047   case Intrinsic::amdgcn_atomic_dec:
1048   case Intrinsic::amdgcn_ds_ordered_add:
1049   case Intrinsic::amdgcn_ds_ordered_swap:
1050   case Intrinsic::amdgcn_ds_fadd:
1051   case Intrinsic::amdgcn_ds_fmin:
1052   case Intrinsic::amdgcn_ds_fmax: {
1053     Value *Ptr = II->getArgOperand(0);
1054     AccessTy = II->getType();
1055     Ops.push_back(Ptr);
1056     return true;
1057   }
1058   default:
1059     return false;
1060   }
1061 }
1062 
1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1064   if (!Subtarget->hasFlatInstOffsets()) {
1065     // Flat instructions do not have offsets, and only have the register
1066     // address.
1067     return AM.BaseOffs == 0 && AM.Scale == 0;
1068   }
1069 
1070   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1071   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1072 
1073   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1074   // instructions, the sign bit is also ignored and is treated as 11-bit
1075   // unsigned offset.
1076 
1077   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1078     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1079 
1080   // Just r + i
1081   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1082 }
1083 
1084 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1085   if (Subtarget->hasFlatGlobalInsts())
1086     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1087 
1088   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1089       // Assume the we will use FLAT for all global memory accesses
1090       // on VI.
1091       // FIXME: This assumption is currently wrong.  On VI we still use
1092       // MUBUF instructions for the r + i addressing mode.  As currently
1093       // implemented, the MUBUF instructions only work on buffer < 4GB.
1094       // It may be possible to support > 4GB buffers with MUBUF instructions,
1095       // by setting the stride value in the resource descriptor which would
1096       // increase the size limit to (stride * 4GB).  However, this is risky,
1097       // because it has never been validated.
1098     return isLegalFlatAddressingMode(AM);
1099   }
1100 
1101   return isLegalMUBUFAddressingMode(AM);
1102 }
1103 
1104 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1105   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1106   // additionally can do r + r + i with addr64. 32-bit has more addressing
1107   // mode options. Depending on the resource constant, it can also do
1108   // (i64 r0) + (i32 r1) * (i14 i).
1109   //
1110   // Private arrays end up using a scratch buffer most of the time, so also
1111   // assume those use MUBUF instructions. Scratch loads / stores are currently
1112   // implemented as mubuf instructions with offen bit set, so slightly
1113   // different than the normal addr64.
1114   if (!isUInt<12>(AM.BaseOffs))
1115     return false;
1116 
1117   // FIXME: Since we can split immediate into soffset and immediate offset,
1118   // would it make sense to allow any immediate?
1119 
1120   switch (AM.Scale) {
1121   case 0: // r + i or just i, depending on HasBaseReg.
1122     return true;
1123   case 1:
1124     return true; // We have r + r or r + i.
1125   case 2:
1126     if (AM.HasBaseReg) {
1127       // Reject 2 * r + r.
1128       return false;
1129     }
1130 
1131     // Allow 2 * r as r + r
1132     // Or  2 * r + i is allowed as r + r + i.
1133     return true;
1134   default: // Don't allow n * r
1135     return false;
1136   }
1137 }
1138 
1139 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1140                                              const AddrMode &AM, Type *Ty,
1141                                              unsigned AS, Instruction *I) const {
1142   // No global is ever allowed as a base.
1143   if (AM.BaseGV)
1144     return false;
1145 
1146   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1147     return isLegalGlobalAddressingMode(AM);
1148 
1149   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1150       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1151       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1152     // If the offset isn't a multiple of 4, it probably isn't going to be
1153     // correctly aligned.
1154     // FIXME: Can we get the real alignment here?
1155     if (AM.BaseOffs % 4 != 0)
1156       return isLegalMUBUFAddressingMode(AM);
1157 
1158     // There are no SMRD extloads, so if we have to do a small type access we
1159     // will use a MUBUF load.
1160     // FIXME?: We also need to do this if unaligned, but we don't know the
1161     // alignment here.
1162     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1163       return isLegalGlobalAddressingMode(AM);
1164 
1165     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1166       // SMRD instructions have an 8-bit, dword offset on SI.
1167       if (!isUInt<8>(AM.BaseOffs / 4))
1168         return false;
1169     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1170       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1171       // in 8-bits, it can use a smaller encoding.
1172       if (!isUInt<32>(AM.BaseOffs / 4))
1173         return false;
1174     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1175       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1176       if (!isUInt<20>(AM.BaseOffs))
1177         return false;
1178     } else
1179       llvm_unreachable("unhandled generation");
1180 
1181     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1182       return true;
1183 
1184     if (AM.Scale == 1 && AM.HasBaseReg)
1185       return true;
1186 
1187     return false;
1188 
1189   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1190     return isLegalMUBUFAddressingMode(AM);
1191   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1192              AS == AMDGPUAS::REGION_ADDRESS) {
1193     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1194     // field.
1195     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1196     // an 8-bit dword offset but we don't know the alignment here.
1197     if (!isUInt<16>(AM.BaseOffs))
1198       return false;
1199 
1200     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1201       return true;
1202 
1203     if (AM.Scale == 1 && AM.HasBaseReg)
1204       return true;
1205 
1206     return false;
1207   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1208              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1209     // For an unknown address space, this usually means that this is for some
1210     // reason being used for pure arithmetic, and not based on some addressing
1211     // computation. We don't have instructions that compute pointers with any
1212     // addressing modes, so treat them as having no offset like flat
1213     // instructions.
1214     return isLegalFlatAddressingMode(AM);
1215   } else {
1216     llvm_unreachable("unhandled address space");
1217   }
1218 }
1219 
1220 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1221                                         const SelectionDAG &DAG) const {
1222   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1223     return (MemVT.getSizeInBits() <= 4 * 32);
1224   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1225     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1226     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1227   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1228     return (MemVT.getSizeInBits() <= 2 * 32);
1229   }
1230   return true;
1231 }
1232 
1233 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1234     unsigned Size, unsigned AddrSpace, unsigned Align,
1235     MachineMemOperand::Flags Flags, bool *IsFast) const {
1236   if (IsFast)
1237     *IsFast = false;
1238 
1239   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1240       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1241     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1242     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1243     // with adjacent offsets.
1244     bool AlignedBy4 = (Align % 4 == 0);
1245     if (IsFast)
1246       *IsFast = AlignedBy4;
1247 
1248     return AlignedBy4;
1249   }
1250 
1251   // FIXME: We have to be conservative here and assume that flat operations
1252   // will access scratch.  If we had access to the IR function, then we
1253   // could determine if any private memory was used in the function.
1254   if (!Subtarget->hasUnalignedScratchAccess() &&
1255       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1256        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1257     bool AlignedBy4 = Align >= 4;
1258     if (IsFast)
1259       *IsFast = AlignedBy4;
1260 
1261     return AlignedBy4;
1262   }
1263 
1264   if (Subtarget->hasUnalignedBufferAccess()) {
1265     // If we have an uniform constant load, it still requires using a slow
1266     // buffer instruction if unaligned.
1267     if (IsFast) {
1268       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1269                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1270         (Align % 4 == 0) : true;
1271     }
1272 
1273     return true;
1274   }
1275 
1276   // Smaller than dword value must be aligned.
1277   if (Size < 32)
1278     return false;
1279 
1280   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1281   // byte-address are ignored, thus forcing Dword alignment.
1282   // This applies to private, global, and constant memory.
1283   if (IsFast)
1284     *IsFast = true;
1285 
1286   return Size >= 32 && Align >= 4;
1287 }
1288 
1289 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1290     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1291     bool *IsFast) const {
1292   if (IsFast)
1293     *IsFast = false;
1294 
1295   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1296   // which isn't a simple VT.
1297   // Until MVT is extended to handle this, simply check for the size and
1298   // rely on the condition below: allow accesses if the size is a multiple of 4.
1299   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1300                            VT.getStoreSize() > 16)) {
1301     return false;
1302   }
1303 
1304   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1305                                             Align, Flags, IsFast);
1306 }
1307 
1308 EVT SITargetLowering::getOptimalMemOpType(
1309     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1310     bool ZeroMemset, bool MemcpyStrSrc,
1311     const AttributeList &FuncAttributes) const {
1312   // FIXME: Should account for address space here.
1313 
1314   // The default fallback uses the private pointer size as a guess for a type to
1315   // use. Make sure we switch these to 64-bit accesses.
1316 
1317   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1318     return MVT::v4i32;
1319 
1320   if (Size >= 8 && DstAlign >= 4)
1321     return MVT::v2i32;
1322 
1323   // Use the default.
1324   return MVT::Other;
1325 }
1326 
1327 static bool isFlatGlobalAddrSpace(unsigned AS) {
1328   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1329          AS == AMDGPUAS::FLAT_ADDRESS ||
1330          AS == AMDGPUAS::CONSTANT_ADDRESS ||
1331          AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
1332 }
1333 
1334 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1335                                            unsigned DestAS) const {
1336   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1337 }
1338 
1339 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1340   const MemSDNode *MemNode = cast<MemSDNode>(N);
1341   const Value *Ptr = MemNode->getMemOperand()->getValue();
1342   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1343   return I && I->getMetadata("amdgpu.noclobber");
1344 }
1345 
1346 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1347                                            unsigned DestAS) const {
1348   // Flat -> private/local is a simple truncate.
1349   // Flat -> global is no-op
1350   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1351     return true;
1352 
1353   return isNoopAddrSpaceCast(SrcAS, DestAS);
1354 }
1355 
1356 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1357   const MemSDNode *MemNode = cast<MemSDNode>(N);
1358 
1359   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1360 }
1361 
1362 TargetLoweringBase::LegalizeTypeAction
1363 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1364   int NumElts = VT.getVectorNumElements();
1365   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1366     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1367   return TargetLoweringBase::getPreferredVectorAction(VT);
1368 }
1369 
1370 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1371                                                          Type *Ty) const {
1372   // FIXME: Could be smarter if called for vector constants.
1373   return true;
1374 }
1375 
1376 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1377   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1378     switch (Op) {
1379     case ISD::LOAD:
1380     case ISD::STORE:
1381 
1382     // These operations are done with 32-bit instructions anyway.
1383     case ISD::AND:
1384     case ISD::OR:
1385     case ISD::XOR:
1386     case ISD::SELECT:
1387       // TODO: Extensions?
1388       return true;
1389     default:
1390       return false;
1391     }
1392   }
1393 
1394   // SimplifySetCC uses this function to determine whether or not it should
1395   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1396   if (VT == MVT::i1 && Op == ISD::SETCC)
1397     return false;
1398 
1399   return TargetLowering::isTypeDesirableForOp(Op, VT);
1400 }
1401 
1402 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1403                                                    const SDLoc &SL,
1404                                                    SDValue Chain,
1405                                                    uint64_t Offset) const {
1406   const DataLayout &DL = DAG.getDataLayout();
1407   MachineFunction &MF = DAG.getMachineFunction();
1408   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1409 
1410   const ArgDescriptor *InputPtrReg;
1411   const TargetRegisterClass *RC;
1412 
1413   std::tie(InputPtrReg, RC)
1414     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1415 
1416   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1417   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1418   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1419     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1420 
1421   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1422 }
1423 
1424 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1425                                             const SDLoc &SL) const {
1426   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1427                                                FIRST_IMPLICIT);
1428   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1429 }
1430 
1431 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1432                                          const SDLoc &SL, SDValue Val,
1433                                          bool Signed,
1434                                          const ISD::InputArg *Arg) const {
1435   // First, if it is a widened vector, narrow it.
1436   if (VT.isVector() &&
1437       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1438     EVT NarrowedVT =
1439         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1440                          VT.getVectorNumElements());
1441     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1442                       DAG.getConstant(0, SL, MVT::i32));
1443   }
1444 
1445   // Then convert the vector elements or scalar value.
1446   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1447       VT.bitsLT(MemVT)) {
1448     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1449     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1450   }
1451 
1452   if (MemVT.isFloatingPoint())
1453     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1454   else if (Signed)
1455     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1456   else
1457     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1458 
1459   return Val;
1460 }
1461 
1462 SDValue SITargetLowering::lowerKernargMemParameter(
1463   SelectionDAG &DAG, EVT VT, EVT MemVT,
1464   const SDLoc &SL, SDValue Chain,
1465   uint64_t Offset, unsigned Align, bool Signed,
1466   const ISD::InputArg *Arg) const {
1467   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1468   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1469   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1470 
1471   // Try to avoid using an extload by loading earlier than the argument address,
1472   // and extracting the relevant bits. The load should hopefully be merged with
1473   // the previous argument.
1474   if (MemVT.getStoreSize() < 4 && Align < 4) {
1475     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1476     int64_t AlignDownOffset = alignDown(Offset, 4);
1477     int64_t OffsetDiff = Offset - AlignDownOffset;
1478 
1479     EVT IntVT = MemVT.changeTypeToInteger();
1480 
1481     // TODO: If we passed in the base kernel offset we could have a better
1482     // alignment than 4, but we don't really need it.
1483     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1484     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1485                                MachineMemOperand::MODereferenceable |
1486                                MachineMemOperand::MOInvariant);
1487 
1488     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1489     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1490 
1491     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1492     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1493     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1494 
1495 
1496     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1497   }
1498 
1499   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1500   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1501                              MachineMemOperand::MODereferenceable |
1502                              MachineMemOperand::MOInvariant);
1503 
1504   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1505   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1506 }
1507 
1508 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1509                                               const SDLoc &SL, SDValue Chain,
1510                                               const ISD::InputArg &Arg) const {
1511   MachineFunction &MF = DAG.getMachineFunction();
1512   MachineFrameInfo &MFI = MF.getFrameInfo();
1513 
1514   if (Arg.Flags.isByVal()) {
1515     unsigned Size = Arg.Flags.getByValSize();
1516     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1517     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1518   }
1519 
1520   unsigned ArgOffset = VA.getLocMemOffset();
1521   unsigned ArgSize = VA.getValVT().getStoreSize();
1522 
1523   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1524 
1525   // Create load nodes to retrieve arguments from the stack.
1526   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1527   SDValue ArgValue;
1528 
1529   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1530   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1531   MVT MemVT = VA.getValVT();
1532 
1533   switch (VA.getLocInfo()) {
1534   default:
1535     break;
1536   case CCValAssign::BCvt:
1537     MemVT = VA.getLocVT();
1538     break;
1539   case CCValAssign::SExt:
1540     ExtType = ISD::SEXTLOAD;
1541     break;
1542   case CCValAssign::ZExt:
1543     ExtType = ISD::ZEXTLOAD;
1544     break;
1545   case CCValAssign::AExt:
1546     ExtType = ISD::EXTLOAD;
1547     break;
1548   }
1549 
1550   ArgValue = DAG.getExtLoad(
1551     ExtType, SL, VA.getLocVT(), Chain, FIN,
1552     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1553     MemVT);
1554   return ArgValue;
1555 }
1556 
1557 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1558   const SIMachineFunctionInfo &MFI,
1559   EVT VT,
1560   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1561   const ArgDescriptor *Reg;
1562   const TargetRegisterClass *RC;
1563 
1564   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1565   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1566 }
1567 
1568 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1569                                    CallingConv::ID CallConv,
1570                                    ArrayRef<ISD::InputArg> Ins,
1571                                    BitVector &Skipped,
1572                                    FunctionType *FType,
1573                                    SIMachineFunctionInfo *Info) {
1574   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1575     const ISD::InputArg *Arg = &Ins[I];
1576 
1577     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1578            "vector type argument should have been split");
1579 
1580     // First check if it's a PS input addr.
1581     if (CallConv == CallingConv::AMDGPU_PS &&
1582         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1583       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1584 
1585       // Inconveniently only the first part of the split is marked as isSplit,
1586       // so skip to the end. We only want to increment PSInputNum once for the
1587       // entire split argument.
1588       if (Arg->Flags.isSplit()) {
1589         while (!Arg->Flags.isSplitEnd()) {
1590           assert((!Arg->VT.isVector() ||
1591                   Arg->VT.getScalarSizeInBits() == 16) &&
1592                  "unexpected vector split in ps argument type");
1593           if (!SkipArg)
1594             Splits.push_back(*Arg);
1595           Arg = &Ins[++I];
1596         }
1597       }
1598 
1599       if (SkipArg) {
1600         // We can safely skip PS inputs.
1601         Skipped.set(Arg->getOrigArgIndex());
1602         ++PSInputNum;
1603         continue;
1604       }
1605 
1606       Info->markPSInputAllocated(PSInputNum);
1607       if (Arg->Used)
1608         Info->markPSInputEnabled(PSInputNum);
1609 
1610       ++PSInputNum;
1611     }
1612 
1613     Splits.push_back(*Arg);
1614   }
1615 }
1616 
1617 // Allocate special inputs passed in VGPRs.
1618 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1619                                                       MachineFunction &MF,
1620                                                       const SIRegisterInfo &TRI,
1621                                                       SIMachineFunctionInfo &Info) const {
1622   const LLT S32 = LLT::scalar(32);
1623   MachineRegisterInfo &MRI = MF.getRegInfo();
1624 
1625   if (Info.hasWorkItemIDX()) {
1626     Register Reg = AMDGPU::VGPR0;
1627     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1628 
1629     CCInfo.AllocateReg(Reg);
1630     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1631   }
1632 
1633   if (Info.hasWorkItemIDY()) {
1634     Register Reg = AMDGPU::VGPR1;
1635     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1636 
1637     CCInfo.AllocateReg(Reg);
1638     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1639   }
1640 
1641   if (Info.hasWorkItemIDZ()) {
1642     Register Reg = AMDGPU::VGPR2;
1643     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1644 
1645     CCInfo.AllocateReg(Reg);
1646     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1647   }
1648 }
1649 
1650 // Try to allocate a VGPR at the end of the argument list, or if no argument
1651 // VGPRs are left allocating a stack slot.
1652 // If \p Mask is is given it indicates bitfield position in the register.
1653 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1654 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1655                                          ArgDescriptor Arg = ArgDescriptor()) {
1656   if (Arg.isSet())
1657     return ArgDescriptor::createArg(Arg, Mask);
1658 
1659   ArrayRef<MCPhysReg> ArgVGPRs
1660     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1661   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1662   if (RegIdx == ArgVGPRs.size()) {
1663     // Spill to stack required.
1664     int64_t Offset = CCInfo.AllocateStack(4, 4);
1665 
1666     return ArgDescriptor::createStack(Offset, Mask);
1667   }
1668 
1669   unsigned Reg = ArgVGPRs[RegIdx];
1670   Reg = CCInfo.AllocateReg(Reg);
1671   assert(Reg != AMDGPU::NoRegister);
1672 
1673   MachineFunction &MF = CCInfo.getMachineFunction();
1674   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1675   return ArgDescriptor::createRegister(Reg, Mask);
1676 }
1677 
1678 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1679                                              const TargetRegisterClass *RC,
1680                                              unsigned NumArgRegs) {
1681   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1682   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1683   if (RegIdx == ArgSGPRs.size())
1684     report_fatal_error("ran out of SGPRs for arguments");
1685 
1686   unsigned Reg = ArgSGPRs[RegIdx];
1687   Reg = CCInfo.AllocateReg(Reg);
1688   assert(Reg != AMDGPU::NoRegister);
1689 
1690   MachineFunction &MF = CCInfo.getMachineFunction();
1691   MF.addLiveIn(Reg, RC);
1692   return ArgDescriptor::createRegister(Reg);
1693 }
1694 
1695 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1696   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1697 }
1698 
1699 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1700   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1701 }
1702 
1703 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1704                                                  MachineFunction &MF,
1705                                                  const SIRegisterInfo &TRI,
1706                                                  SIMachineFunctionInfo &Info) const {
1707   const unsigned Mask = 0x3ff;
1708   ArgDescriptor Arg;
1709 
1710   if (Info.hasWorkItemIDX()) {
1711     Arg = allocateVGPR32Input(CCInfo, Mask);
1712     Info.setWorkItemIDX(Arg);
1713   }
1714 
1715   if (Info.hasWorkItemIDY()) {
1716     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1717     Info.setWorkItemIDY(Arg);
1718   }
1719 
1720   if (Info.hasWorkItemIDZ())
1721     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1722 }
1723 
1724 void SITargetLowering::allocateSpecialInputSGPRs(
1725   CCState &CCInfo,
1726   MachineFunction &MF,
1727   const SIRegisterInfo &TRI,
1728   SIMachineFunctionInfo &Info) const {
1729   auto &ArgInfo = Info.getArgInfo();
1730 
1731   // TODO: Unify handling with private memory pointers.
1732 
1733   if (Info.hasDispatchPtr())
1734     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1735 
1736   if (Info.hasQueuePtr())
1737     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1738 
1739   if (Info.hasKernargSegmentPtr())
1740     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1741 
1742   if (Info.hasDispatchID())
1743     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1744 
1745   // flat_scratch_init is not applicable for non-kernel functions.
1746 
1747   if (Info.hasWorkGroupIDX())
1748     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1749 
1750   if (Info.hasWorkGroupIDY())
1751     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1752 
1753   if (Info.hasWorkGroupIDZ())
1754     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1755 
1756   if (Info.hasImplicitArgPtr())
1757     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1758 }
1759 
1760 // Allocate special inputs passed in user SGPRs.
1761 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1762                                             MachineFunction &MF,
1763                                             const SIRegisterInfo &TRI,
1764                                             SIMachineFunctionInfo &Info) const {
1765   if (Info.hasImplicitBufferPtr()) {
1766     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1767     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1768     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1769   }
1770 
1771   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1772   if (Info.hasPrivateSegmentBuffer()) {
1773     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1774     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1775     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1776   }
1777 
1778   if (Info.hasDispatchPtr()) {
1779     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1780     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1781     CCInfo.AllocateReg(DispatchPtrReg);
1782   }
1783 
1784   if (Info.hasQueuePtr()) {
1785     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1786     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1787     CCInfo.AllocateReg(QueuePtrReg);
1788   }
1789 
1790   if (Info.hasKernargSegmentPtr()) {
1791     MachineRegisterInfo &MRI = MF.getRegInfo();
1792     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1793     CCInfo.AllocateReg(InputPtrReg);
1794 
1795     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1796     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1797   }
1798 
1799   if (Info.hasDispatchID()) {
1800     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1801     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1802     CCInfo.AllocateReg(DispatchIDReg);
1803   }
1804 
1805   if (Info.hasFlatScratchInit()) {
1806     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1807     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1808     CCInfo.AllocateReg(FlatScratchInitReg);
1809   }
1810 
1811   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1812   // these from the dispatch pointer.
1813 }
1814 
1815 // Allocate special input registers that are initialized per-wave.
1816 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1817                                            MachineFunction &MF,
1818                                            SIMachineFunctionInfo &Info,
1819                                            CallingConv::ID CallConv,
1820                                            bool IsShader) const {
1821   if (Info.hasWorkGroupIDX()) {
1822     unsigned Reg = Info.addWorkGroupIDX();
1823     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1824     CCInfo.AllocateReg(Reg);
1825   }
1826 
1827   if (Info.hasWorkGroupIDY()) {
1828     unsigned Reg = Info.addWorkGroupIDY();
1829     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1830     CCInfo.AllocateReg(Reg);
1831   }
1832 
1833   if (Info.hasWorkGroupIDZ()) {
1834     unsigned Reg = Info.addWorkGroupIDZ();
1835     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1836     CCInfo.AllocateReg(Reg);
1837   }
1838 
1839   if (Info.hasWorkGroupInfo()) {
1840     unsigned Reg = Info.addWorkGroupInfo();
1841     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1842     CCInfo.AllocateReg(Reg);
1843   }
1844 
1845   if (Info.hasPrivateSegmentWaveByteOffset()) {
1846     // Scratch wave offset passed in system SGPR.
1847     unsigned PrivateSegmentWaveByteOffsetReg;
1848 
1849     if (IsShader) {
1850       PrivateSegmentWaveByteOffsetReg =
1851         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1852 
1853       // This is true if the scratch wave byte offset doesn't have a fixed
1854       // location.
1855       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1856         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1857         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1858       }
1859     } else
1860       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1861 
1862     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1863     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1864   }
1865 }
1866 
1867 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1868                                      MachineFunction &MF,
1869                                      const SIRegisterInfo &TRI,
1870                                      SIMachineFunctionInfo &Info) {
1871   // Now that we've figured out where the scratch register inputs are, see if
1872   // should reserve the arguments and use them directly.
1873   MachineFrameInfo &MFI = MF.getFrameInfo();
1874   bool HasStackObjects = MFI.hasStackObjects();
1875   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1876 
1877   // Record that we know we have non-spill stack objects so we don't need to
1878   // check all stack objects later.
1879   if (HasStackObjects)
1880     Info.setHasNonSpillStackObjects(true);
1881 
1882   // Everything live out of a block is spilled with fast regalloc, so it's
1883   // almost certain that spilling will be required.
1884   if (TM.getOptLevel() == CodeGenOpt::None)
1885     HasStackObjects = true;
1886 
1887   // For now assume stack access is needed in any callee functions, so we need
1888   // the scratch registers to pass in.
1889   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1890 
1891   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1892     // If we have stack objects, we unquestionably need the private buffer
1893     // resource. For the Code Object V2 ABI, this will be the first 4 user
1894     // SGPR inputs. We can reserve those and use them directly.
1895 
1896     Register PrivateSegmentBufferReg =
1897         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1898     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1899   } else {
1900     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1901     // We tentatively reserve the last registers (skipping the last registers
1902     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1903     // we'll replace these with the ones immediately after those which were
1904     // really allocated. In the prologue copies will be inserted from the
1905     // argument to these reserved registers.
1906 
1907     // Without HSA, relocations are used for the scratch pointer and the
1908     // buffer resource setup is always inserted in the prologue. Scratch wave
1909     // offset is still in an input SGPR.
1910     Info.setScratchRSrcReg(ReservedBufferReg);
1911   }
1912 
1913   // hasFP should be accurate for kernels even before the frame is finalized.
1914   if (ST.getFrameLowering()->hasFP(MF)) {
1915     MachineRegisterInfo &MRI = MF.getRegInfo();
1916 
1917     // Try to use s32 as the SP, but move it if it would interfere with input
1918     // arguments. This won't work with calls though.
1919     //
1920     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1921     // registers.
1922     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1923       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1924     } else {
1925       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1926 
1927       if (MFI.hasCalls())
1928         report_fatal_error("call in graphics shader with too many input SGPRs");
1929 
1930       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1931         if (!MRI.isLiveIn(Reg)) {
1932           Info.setStackPtrOffsetReg(Reg);
1933           break;
1934         }
1935       }
1936 
1937       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1938         report_fatal_error("failed to find register for SP");
1939     }
1940 
1941     if (MFI.hasCalls()) {
1942       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1943       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1944     } else {
1945       unsigned ReservedOffsetReg =
1946         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1947       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1948       Info.setFrameOffsetReg(ReservedOffsetReg);
1949     }
1950   } else if (RequiresStackAccess) {
1951     assert(!MFI.hasCalls());
1952     // We know there are accesses and they will be done relative to SP, so just
1953     // pin it to the input.
1954     //
1955     // FIXME: Should not do this if inline asm is reading/writing these
1956     // registers.
1957     Register PreloadedSP = Info.getPreloadedReg(
1958         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1959 
1960     Info.setStackPtrOffsetReg(PreloadedSP);
1961     Info.setScratchWaveOffsetReg(PreloadedSP);
1962     Info.setFrameOffsetReg(PreloadedSP);
1963   } else {
1964     assert(!MFI.hasCalls());
1965 
1966     // There may not be stack access at all. There may still be spills, or
1967     // access of a constant pointer (in which cases an extra copy will be
1968     // emitted in the prolog).
1969     unsigned ReservedOffsetReg
1970       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1971     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1972     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1973     Info.setFrameOffsetReg(ReservedOffsetReg);
1974   }
1975 }
1976 
1977 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1978   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1979   return !Info->isEntryFunction();
1980 }
1981 
1982 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1983 
1984 }
1985 
1986 void SITargetLowering::insertCopiesSplitCSR(
1987   MachineBasicBlock *Entry,
1988   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1989   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1990 
1991   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1992   if (!IStart)
1993     return;
1994 
1995   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1996   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1997   MachineBasicBlock::iterator MBBI = Entry->begin();
1998   for (const MCPhysReg *I = IStart; *I; ++I) {
1999     const TargetRegisterClass *RC = nullptr;
2000     if (AMDGPU::SReg_64RegClass.contains(*I))
2001       RC = &AMDGPU::SGPR_64RegClass;
2002     else if (AMDGPU::SReg_32RegClass.contains(*I))
2003       RC = &AMDGPU::SGPR_32RegClass;
2004     else
2005       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2006 
2007     Register NewVR = MRI->createVirtualRegister(RC);
2008     // Create copy from CSR to a virtual register.
2009     Entry->addLiveIn(*I);
2010     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2011       .addReg(*I);
2012 
2013     // Insert the copy-back instructions right before the terminator.
2014     for (auto *Exit : Exits)
2015       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2016               TII->get(TargetOpcode::COPY), *I)
2017         .addReg(NewVR);
2018   }
2019 }
2020 
2021 SDValue SITargetLowering::LowerFormalArguments(
2022     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2023     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2024     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2025   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2026 
2027   MachineFunction &MF = DAG.getMachineFunction();
2028   const Function &Fn = MF.getFunction();
2029   FunctionType *FType = MF.getFunction().getFunctionType();
2030   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2031 
2032   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2033     DiagnosticInfoUnsupported NoGraphicsHSA(
2034         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2035     DAG.getContext()->diagnose(NoGraphicsHSA);
2036     return DAG.getEntryNode();
2037   }
2038 
2039   SmallVector<ISD::InputArg, 16> Splits;
2040   SmallVector<CCValAssign, 16> ArgLocs;
2041   BitVector Skipped(Ins.size());
2042   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2043                  *DAG.getContext());
2044 
2045   bool IsShader = AMDGPU::isShader(CallConv);
2046   bool IsKernel = AMDGPU::isKernel(CallConv);
2047   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2048 
2049   if (IsShader) {
2050     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2051 
2052     // At least one interpolation mode must be enabled or else the GPU will
2053     // hang.
2054     //
2055     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2056     // set PSInputAddr, the user wants to enable some bits after the compilation
2057     // based on run-time states. Since we can't know what the final PSInputEna
2058     // will look like, so we shouldn't do anything here and the user should take
2059     // responsibility for the correct programming.
2060     //
2061     // Otherwise, the following restrictions apply:
2062     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2063     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2064     //   enabled too.
2065     if (CallConv == CallingConv::AMDGPU_PS) {
2066       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2067            ((Info->getPSInputAddr() & 0xF) == 0 &&
2068             Info->isPSInputAllocated(11))) {
2069         CCInfo.AllocateReg(AMDGPU::VGPR0);
2070         CCInfo.AllocateReg(AMDGPU::VGPR1);
2071         Info->markPSInputAllocated(0);
2072         Info->markPSInputEnabled(0);
2073       }
2074       if (Subtarget->isAmdPalOS()) {
2075         // For isAmdPalOS, the user does not enable some bits after compilation
2076         // based on run-time states; the register values being generated here are
2077         // the final ones set in hardware. Therefore we need to apply the
2078         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2079         // a bit is set in PSInputAddr but not PSInputEnable is where the
2080         // frontend set up an input arg for a particular interpolation mode, but
2081         // nothing uses that input arg. Really we should have an earlier pass
2082         // that removes such an arg.)
2083         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2084         if ((PsInputBits & 0x7F) == 0 ||
2085             ((PsInputBits & 0xF) == 0 &&
2086              (PsInputBits >> 11 & 1)))
2087           Info->markPSInputEnabled(
2088               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2089       }
2090     }
2091 
2092     assert(!Info->hasDispatchPtr() &&
2093            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2094            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2095            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2096            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2097            !Info->hasWorkItemIDZ());
2098   } else if (IsKernel) {
2099     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2100   } else {
2101     Splits.append(Ins.begin(), Ins.end());
2102   }
2103 
2104   if (IsEntryFunc) {
2105     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2106     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2107   }
2108 
2109   if (IsKernel) {
2110     analyzeFormalArgumentsCompute(CCInfo, Ins);
2111   } else {
2112     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2113     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2114   }
2115 
2116   SmallVector<SDValue, 16> Chains;
2117 
2118   // FIXME: This is the minimum kernel argument alignment. We should improve
2119   // this to the maximum alignment of the arguments.
2120   //
2121   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2122   // kern arg offset.
2123   const unsigned KernelArgBaseAlign = 16;
2124 
2125    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2126     const ISD::InputArg &Arg = Ins[i];
2127     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2128       InVals.push_back(DAG.getUNDEF(Arg.VT));
2129       continue;
2130     }
2131 
2132     CCValAssign &VA = ArgLocs[ArgIdx++];
2133     MVT VT = VA.getLocVT();
2134 
2135     if (IsEntryFunc && VA.isMemLoc()) {
2136       VT = Ins[i].VT;
2137       EVT MemVT = VA.getLocVT();
2138 
2139       const uint64_t Offset = VA.getLocMemOffset();
2140       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2141 
2142       SDValue Arg = lowerKernargMemParameter(
2143         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2144       Chains.push_back(Arg.getValue(1));
2145 
2146       auto *ParamTy =
2147         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2148       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2149           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2150                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2151         // On SI local pointers are just offsets into LDS, so they are always
2152         // less than 16-bits.  On CI and newer they could potentially be
2153         // real pointers, so we can't guarantee their size.
2154         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2155                           DAG.getValueType(MVT::i16));
2156       }
2157 
2158       InVals.push_back(Arg);
2159       continue;
2160     } else if (!IsEntryFunc && VA.isMemLoc()) {
2161       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2162       InVals.push_back(Val);
2163       if (!Arg.Flags.isByVal())
2164         Chains.push_back(Val.getValue(1));
2165       continue;
2166     }
2167 
2168     assert(VA.isRegLoc() && "Parameter must be in a register!");
2169 
2170     Register Reg = VA.getLocReg();
2171     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2172     EVT ValVT = VA.getValVT();
2173 
2174     Reg = MF.addLiveIn(Reg, RC);
2175     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2176 
2177     if (Arg.Flags.isSRet()) {
2178       // The return object should be reasonably addressable.
2179 
2180       // FIXME: This helps when the return is a real sret. If it is a
2181       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2182       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2183       unsigned NumBits
2184         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2185       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2186         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2187     }
2188 
2189     // If this is an 8 or 16-bit value, it is really passed promoted
2190     // to 32 bits. Insert an assert[sz]ext to capture this, then
2191     // truncate to the right size.
2192     switch (VA.getLocInfo()) {
2193     case CCValAssign::Full:
2194       break;
2195     case CCValAssign::BCvt:
2196       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2197       break;
2198     case CCValAssign::SExt:
2199       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2200                         DAG.getValueType(ValVT));
2201       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2202       break;
2203     case CCValAssign::ZExt:
2204       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2205                         DAG.getValueType(ValVT));
2206       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2207       break;
2208     case CCValAssign::AExt:
2209       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2210       break;
2211     default:
2212       llvm_unreachable("Unknown loc info!");
2213     }
2214 
2215     InVals.push_back(Val);
2216   }
2217 
2218   if (!IsEntryFunc) {
2219     // Special inputs come after user arguments.
2220     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2221   }
2222 
2223   // Start adding system SGPRs.
2224   if (IsEntryFunc) {
2225     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2226   } else {
2227     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2228     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2229     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2230     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2231   }
2232 
2233   auto &ArgUsageInfo =
2234     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2235   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2236 
2237   unsigned StackArgSize = CCInfo.getNextStackOffset();
2238   Info->setBytesInStackArgArea(StackArgSize);
2239 
2240   return Chains.empty() ? Chain :
2241     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2242 }
2243 
2244 // TODO: If return values can't fit in registers, we should return as many as
2245 // possible in registers before passing on stack.
2246 bool SITargetLowering::CanLowerReturn(
2247   CallingConv::ID CallConv,
2248   MachineFunction &MF, bool IsVarArg,
2249   const SmallVectorImpl<ISD::OutputArg> &Outs,
2250   LLVMContext &Context) const {
2251   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2252   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2253   // for shaders. Vector types should be explicitly handled by CC.
2254   if (AMDGPU::isEntryFunctionCC(CallConv))
2255     return true;
2256 
2257   SmallVector<CCValAssign, 16> RVLocs;
2258   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2259   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2260 }
2261 
2262 SDValue
2263 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2264                               bool isVarArg,
2265                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2266                               const SmallVectorImpl<SDValue> &OutVals,
2267                               const SDLoc &DL, SelectionDAG &DAG) const {
2268   MachineFunction &MF = DAG.getMachineFunction();
2269   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2270 
2271   if (AMDGPU::isKernel(CallConv)) {
2272     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2273                                              OutVals, DL, DAG);
2274   }
2275 
2276   bool IsShader = AMDGPU::isShader(CallConv);
2277 
2278   Info->setIfReturnsVoid(Outs.empty());
2279   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2280 
2281   // CCValAssign - represent the assignment of the return value to a location.
2282   SmallVector<CCValAssign, 48> RVLocs;
2283   SmallVector<ISD::OutputArg, 48> Splits;
2284 
2285   // CCState - Info about the registers and stack slots.
2286   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2287                  *DAG.getContext());
2288 
2289   // Analyze outgoing return values.
2290   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2291 
2292   SDValue Flag;
2293   SmallVector<SDValue, 48> RetOps;
2294   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2295 
2296   // Add return address for callable functions.
2297   if (!Info->isEntryFunction()) {
2298     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2299     SDValue ReturnAddrReg = CreateLiveInRegister(
2300       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2301 
2302     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2303         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2304         MVT::i64);
2305     Chain =
2306         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2307     Flag = Chain.getValue(1);
2308     RetOps.push_back(ReturnAddrVirtualReg);
2309   }
2310 
2311   // Copy the result values into the output registers.
2312   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2313        ++I, ++RealRVLocIdx) {
2314     CCValAssign &VA = RVLocs[I];
2315     assert(VA.isRegLoc() && "Can only return in registers!");
2316     // TODO: Partially return in registers if return values don't fit.
2317     SDValue Arg = OutVals[RealRVLocIdx];
2318 
2319     // Copied from other backends.
2320     switch (VA.getLocInfo()) {
2321     case CCValAssign::Full:
2322       break;
2323     case CCValAssign::BCvt:
2324       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2325       break;
2326     case CCValAssign::SExt:
2327       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2328       break;
2329     case CCValAssign::ZExt:
2330       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2331       break;
2332     case CCValAssign::AExt:
2333       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2334       break;
2335     default:
2336       llvm_unreachable("Unknown loc info!");
2337     }
2338 
2339     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2340     Flag = Chain.getValue(1);
2341     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2342   }
2343 
2344   // FIXME: Does sret work properly?
2345   if (!Info->isEntryFunction()) {
2346     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2347     const MCPhysReg *I =
2348       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2349     if (I) {
2350       for (; *I; ++I) {
2351         if (AMDGPU::SReg_64RegClass.contains(*I))
2352           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2353         else if (AMDGPU::SReg_32RegClass.contains(*I))
2354           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2355         else
2356           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2357       }
2358     }
2359   }
2360 
2361   // Update chain and glue.
2362   RetOps[0] = Chain;
2363   if (Flag.getNode())
2364     RetOps.push_back(Flag);
2365 
2366   unsigned Opc = AMDGPUISD::ENDPGM;
2367   if (!IsWaveEnd)
2368     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2369   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2370 }
2371 
2372 SDValue SITargetLowering::LowerCallResult(
2373     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2374     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2375     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2376     SDValue ThisVal) const {
2377   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2378 
2379   // Assign locations to each value returned by this call.
2380   SmallVector<CCValAssign, 16> RVLocs;
2381   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2382                  *DAG.getContext());
2383   CCInfo.AnalyzeCallResult(Ins, RetCC);
2384 
2385   // Copy all of the result registers out of their specified physreg.
2386   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2387     CCValAssign VA = RVLocs[i];
2388     SDValue Val;
2389 
2390     if (VA.isRegLoc()) {
2391       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2392       Chain = Val.getValue(1);
2393       InFlag = Val.getValue(2);
2394     } else if (VA.isMemLoc()) {
2395       report_fatal_error("TODO: return values in memory");
2396     } else
2397       llvm_unreachable("unknown argument location type");
2398 
2399     switch (VA.getLocInfo()) {
2400     case CCValAssign::Full:
2401       break;
2402     case CCValAssign::BCvt:
2403       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2404       break;
2405     case CCValAssign::ZExt:
2406       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2407                         DAG.getValueType(VA.getValVT()));
2408       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2409       break;
2410     case CCValAssign::SExt:
2411       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2412                         DAG.getValueType(VA.getValVT()));
2413       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2414       break;
2415     case CCValAssign::AExt:
2416       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2417       break;
2418     default:
2419       llvm_unreachable("Unknown loc info!");
2420     }
2421 
2422     InVals.push_back(Val);
2423   }
2424 
2425   return Chain;
2426 }
2427 
2428 // Add code to pass special inputs required depending on used features separate
2429 // from the explicit user arguments present in the IR.
2430 void SITargetLowering::passSpecialInputs(
2431     CallLoweringInfo &CLI,
2432     CCState &CCInfo,
2433     const SIMachineFunctionInfo &Info,
2434     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2435     SmallVectorImpl<SDValue> &MemOpChains,
2436     SDValue Chain) const {
2437   // If we don't have a call site, this was a call inserted by
2438   // legalization. These can never use special inputs.
2439   if (!CLI.CS)
2440     return;
2441 
2442   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2443   assert(CalleeFunc);
2444 
2445   SelectionDAG &DAG = CLI.DAG;
2446   const SDLoc &DL = CLI.DL;
2447 
2448   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2449 
2450   auto &ArgUsageInfo =
2451     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2452   const AMDGPUFunctionArgInfo &CalleeArgInfo
2453     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2454 
2455   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2456 
2457   // TODO: Unify with private memory register handling. This is complicated by
2458   // the fact that at least in kernels, the input argument is not necessarily
2459   // in the same location as the input.
2460   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2461     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2462     AMDGPUFunctionArgInfo::QUEUE_PTR,
2463     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2464     AMDGPUFunctionArgInfo::DISPATCH_ID,
2465     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2466     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2467     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2468     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2469   };
2470 
2471   for (auto InputID : InputRegs) {
2472     const ArgDescriptor *OutgoingArg;
2473     const TargetRegisterClass *ArgRC;
2474 
2475     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2476     if (!OutgoingArg)
2477       continue;
2478 
2479     const ArgDescriptor *IncomingArg;
2480     const TargetRegisterClass *IncomingArgRC;
2481     std::tie(IncomingArg, IncomingArgRC)
2482       = CallerArgInfo.getPreloadedValue(InputID);
2483     assert(IncomingArgRC == ArgRC);
2484 
2485     // All special arguments are ints for now.
2486     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2487     SDValue InputReg;
2488 
2489     if (IncomingArg) {
2490       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2491     } else {
2492       // The implicit arg ptr is special because it doesn't have a corresponding
2493       // input for kernels, and is computed from the kernarg segment pointer.
2494       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2495       InputReg = getImplicitArgPtr(DAG, DL);
2496     }
2497 
2498     if (OutgoingArg->isRegister()) {
2499       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2500     } else {
2501       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2502       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2503                                               SpecialArgOffset);
2504       MemOpChains.push_back(ArgStore);
2505     }
2506   }
2507 
2508   // Pack workitem IDs into a single register or pass it as is if already
2509   // packed.
2510   const ArgDescriptor *OutgoingArg;
2511   const TargetRegisterClass *ArgRC;
2512 
2513   std::tie(OutgoingArg, ArgRC) =
2514     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2515   if (!OutgoingArg)
2516     std::tie(OutgoingArg, ArgRC) =
2517       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2518   if (!OutgoingArg)
2519     std::tie(OutgoingArg, ArgRC) =
2520       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2521   if (!OutgoingArg)
2522     return;
2523 
2524   const ArgDescriptor *IncomingArgX
2525     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2526   const ArgDescriptor *IncomingArgY
2527     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2528   const ArgDescriptor *IncomingArgZ
2529     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2530 
2531   SDValue InputReg;
2532   SDLoc SL;
2533 
2534   // If incoming ids are not packed we need to pack them.
2535   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2536     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2537 
2538   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2539     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2540     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2541                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2542     InputReg = InputReg.getNode() ?
2543                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2544   }
2545 
2546   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2547     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2548     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2549                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2550     InputReg = InputReg.getNode() ?
2551                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2552   }
2553 
2554   if (!InputReg.getNode()) {
2555     // Workitem ids are already packed, any of present incoming arguments
2556     // will carry all required fields.
2557     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2558       IncomingArgX ? *IncomingArgX :
2559       IncomingArgY ? *IncomingArgY :
2560                      *IncomingArgZ, ~0u);
2561     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2562   }
2563 
2564   if (OutgoingArg->isRegister()) {
2565     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2566   } else {
2567     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2568     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2569                                             SpecialArgOffset);
2570     MemOpChains.push_back(ArgStore);
2571   }
2572 }
2573 
2574 static bool canGuaranteeTCO(CallingConv::ID CC) {
2575   return CC == CallingConv::Fast;
2576 }
2577 
2578 /// Return true if we might ever do TCO for calls with this calling convention.
2579 static bool mayTailCallThisCC(CallingConv::ID CC) {
2580   switch (CC) {
2581   case CallingConv::C:
2582     return true;
2583   default:
2584     return canGuaranteeTCO(CC);
2585   }
2586 }
2587 
2588 bool SITargetLowering::isEligibleForTailCallOptimization(
2589     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2590     const SmallVectorImpl<ISD::OutputArg> &Outs,
2591     const SmallVectorImpl<SDValue> &OutVals,
2592     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2593   if (!mayTailCallThisCC(CalleeCC))
2594     return false;
2595 
2596   MachineFunction &MF = DAG.getMachineFunction();
2597   const Function &CallerF = MF.getFunction();
2598   CallingConv::ID CallerCC = CallerF.getCallingConv();
2599   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2600   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2601 
2602   // Kernels aren't callable, and don't have a live in return address so it
2603   // doesn't make sense to do a tail call with entry functions.
2604   if (!CallerPreserved)
2605     return false;
2606 
2607   bool CCMatch = CallerCC == CalleeCC;
2608 
2609   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2610     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2611       return true;
2612     return false;
2613   }
2614 
2615   // TODO: Can we handle var args?
2616   if (IsVarArg)
2617     return false;
2618 
2619   for (const Argument &Arg : CallerF.args()) {
2620     if (Arg.hasByValAttr())
2621       return false;
2622   }
2623 
2624   LLVMContext &Ctx = *DAG.getContext();
2625 
2626   // Check that the call results are passed in the same way.
2627   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2628                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2629                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2630     return false;
2631 
2632   // The callee has to preserve all registers the caller needs to preserve.
2633   if (!CCMatch) {
2634     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2635     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2636       return false;
2637   }
2638 
2639   // Nothing more to check if the callee is taking no arguments.
2640   if (Outs.empty())
2641     return true;
2642 
2643   SmallVector<CCValAssign, 16> ArgLocs;
2644   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2645 
2646   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2647 
2648   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2649   // If the stack arguments for this call do not fit into our own save area then
2650   // the call cannot be made tail.
2651   // TODO: Is this really necessary?
2652   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2653     return false;
2654 
2655   const MachineRegisterInfo &MRI = MF.getRegInfo();
2656   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2657 }
2658 
2659 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2660   if (!CI->isTailCall())
2661     return false;
2662 
2663   const Function *ParentFn = CI->getParent()->getParent();
2664   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2665     return false;
2666 
2667   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2668   return (Attr.getValueAsString() != "true");
2669 }
2670 
2671 // The wave scratch offset register is used as the global base pointer.
2672 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2673                                     SmallVectorImpl<SDValue> &InVals) const {
2674   SelectionDAG &DAG = CLI.DAG;
2675   const SDLoc &DL = CLI.DL;
2676   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2677   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2678   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2679   SDValue Chain = CLI.Chain;
2680   SDValue Callee = CLI.Callee;
2681   bool &IsTailCall = CLI.IsTailCall;
2682   CallingConv::ID CallConv = CLI.CallConv;
2683   bool IsVarArg = CLI.IsVarArg;
2684   bool IsSibCall = false;
2685   bool IsThisReturn = false;
2686   MachineFunction &MF = DAG.getMachineFunction();
2687 
2688   if (IsVarArg) {
2689     return lowerUnhandledCall(CLI, InVals,
2690                               "unsupported call to variadic function ");
2691   }
2692 
2693   if (!CLI.CS.getInstruction())
2694     report_fatal_error("unsupported libcall legalization");
2695 
2696   if (!CLI.CS.getCalledFunction()) {
2697     return lowerUnhandledCall(CLI, InVals,
2698                               "unsupported indirect call to function ");
2699   }
2700 
2701   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2702     return lowerUnhandledCall(CLI, InVals,
2703                               "unsupported required tail call to function ");
2704   }
2705 
2706   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2707     // Note the issue is with the CC of the calling function, not of the call
2708     // itself.
2709     return lowerUnhandledCall(CLI, InVals,
2710                           "unsupported call from graphics shader of function ");
2711   }
2712 
2713   if (IsTailCall) {
2714     IsTailCall = isEligibleForTailCallOptimization(
2715       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2716     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2717       report_fatal_error("failed to perform tail call elimination on a call "
2718                          "site marked musttail");
2719     }
2720 
2721     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2722 
2723     // A sibling call is one where we're under the usual C ABI and not planning
2724     // to change that but can still do a tail call:
2725     if (!TailCallOpt && IsTailCall)
2726       IsSibCall = true;
2727 
2728     if (IsTailCall)
2729       ++NumTailCalls;
2730   }
2731 
2732   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2733 
2734   // Analyze operands of the call, assigning locations to each operand.
2735   SmallVector<CCValAssign, 16> ArgLocs;
2736   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2737   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2738 
2739   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2740 
2741   // Get a count of how many bytes are to be pushed on the stack.
2742   unsigned NumBytes = CCInfo.getNextStackOffset();
2743 
2744   if (IsSibCall) {
2745     // Since we're not changing the ABI to make this a tail call, the memory
2746     // operands are already available in the caller's incoming argument space.
2747     NumBytes = 0;
2748   }
2749 
2750   // FPDiff is the byte offset of the call's argument area from the callee's.
2751   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2752   // by this amount for a tail call. In a sibling call it must be 0 because the
2753   // caller will deallocate the entire stack and the callee still expects its
2754   // arguments to begin at SP+0. Completely unused for non-tail calls.
2755   int32_t FPDiff = 0;
2756   MachineFrameInfo &MFI = MF.getFrameInfo();
2757   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2758 
2759   // Adjust the stack pointer for the new arguments...
2760   // These operations are automatically eliminated by the prolog/epilog pass
2761   if (!IsSibCall) {
2762     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2763 
2764     SmallVector<SDValue, 4> CopyFromChains;
2765 
2766     // In the HSA case, this should be an identity copy.
2767     SDValue ScratchRSrcReg
2768       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2769     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2770     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2771     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2772   }
2773 
2774   SmallVector<SDValue, 8> MemOpChains;
2775   MVT PtrVT = MVT::i32;
2776 
2777   // Walk the register/memloc assignments, inserting copies/loads.
2778   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2779        ++i, ++realArgIdx) {
2780     CCValAssign &VA = ArgLocs[i];
2781     SDValue Arg = OutVals[realArgIdx];
2782 
2783     // Promote the value if needed.
2784     switch (VA.getLocInfo()) {
2785     case CCValAssign::Full:
2786       break;
2787     case CCValAssign::BCvt:
2788       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2789       break;
2790     case CCValAssign::ZExt:
2791       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2792       break;
2793     case CCValAssign::SExt:
2794       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2795       break;
2796     case CCValAssign::AExt:
2797       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2798       break;
2799     case CCValAssign::FPExt:
2800       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2801       break;
2802     default:
2803       llvm_unreachable("Unknown loc info!");
2804     }
2805 
2806     if (VA.isRegLoc()) {
2807       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2808     } else {
2809       assert(VA.isMemLoc());
2810 
2811       SDValue DstAddr;
2812       MachinePointerInfo DstInfo;
2813 
2814       unsigned LocMemOffset = VA.getLocMemOffset();
2815       int32_t Offset = LocMemOffset;
2816 
2817       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2818       unsigned Align = 0;
2819 
2820       if (IsTailCall) {
2821         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2822         unsigned OpSize = Flags.isByVal() ?
2823           Flags.getByValSize() : VA.getValVT().getStoreSize();
2824 
2825         // FIXME: We can have better than the minimum byval required alignment.
2826         Align = Flags.isByVal() ? Flags.getByValAlign() :
2827           MinAlign(Subtarget->getStackAlignment(), Offset);
2828 
2829         Offset = Offset + FPDiff;
2830         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2831 
2832         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2833         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2834 
2835         // Make sure any stack arguments overlapping with where we're storing
2836         // are loaded before this eventual operation. Otherwise they'll be
2837         // clobbered.
2838 
2839         // FIXME: Why is this really necessary? This seems to just result in a
2840         // lot of code to copy the stack and write them back to the same
2841         // locations, which are supposed to be immutable?
2842         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2843       } else {
2844         DstAddr = PtrOff;
2845         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2846         Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2847       }
2848 
2849       if (Outs[i].Flags.isByVal()) {
2850         SDValue SizeNode =
2851             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2852         SDValue Cpy = DAG.getMemcpy(
2853             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2854             /*isVol = */ false, /*AlwaysInline = */ true,
2855             /*isTailCall = */ false, DstInfo,
2856             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2857                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2858 
2859         MemOpChains.push_back(Cpy);
2860       } else {
2861         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2862         MemOpChains.push_back(Store);
2863       }
2864     }
2865   }
2866 
2867   // Copy special input registers after user input arguments.
2868   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2869 
2870   if (!MemOpChains.empty())
2871     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2872 
2873   // Build a sequence of copy-to-reg nodes chained together with token chain
2874   // and flag operands which copy the outgoing args into the appropriate regs.
2875   SDValue InFlag;
2876   for (auto &RegToPass : RegsToPass) {
2877     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2878                              RegToPass.second, InFlag);
2879     InFlag = Chain.getValue(1);
2880   }
2881 
2882 
2883   SDValue PhysReturnAddrReg;
2884   if (IsTailCall) {
2885     // Since the return is being combined with the call, we need to pass on the
2886     // return address.
2887 
2888     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2889     SDValue ReturnAddrReg = CreateLiveInRegister(
2890       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2891 
2892     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2893                                         MVT::i64);
2894     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2895     InFlag = Chain.getValue(1);
2896   }
2897 
2898   // We don't usually want to end the call-sequence here because we would tidy
2899   // the frame up *after* the call, however in the ABI-changing tail-call case
2900   // we've carefully laid out the parameters so that when sp is reset they'll be
2901   // in the correct location.
2902   if (IsTailCall && !IsSibCall) {
2903     Chain = DAG.getCALLSEQ_END(Chain,
2904                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2905                                DAG.getTargetConstant(0, DL, MVT::i32),
2906                                InFlag, DL);
2907     InFlag = Chain.getValue(1);
2908   }
2909 
2910   std::vector<SDValue> Ops;
2911   Ops.push_back(Chain);
2912   Ops.push_back(Callee);
2913   // Add a redundant copy of the callee global which will not be legalized, as
2914   // we need direct access to the callee later.
2915   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2916   const GlobalValue *GV = GSD->getGlobal();
2917   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2918 
2919   if (IsTailCall) {
2920     // Each tail call may have to adjust the stack by a different amount, so
2921     // this information must travel along with the operation for eventual
2922     // consumption by emitEpilogue.
2923     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2924 
2925     Ops.push_back(PhysReturnAddrReg);
2926   }
2927 
2928   // Add argument registers to the end of the list so that they are known live
2929   // into the call.
2930   for (auto &RegToPass : RegsToPass) {
2931     Ops.push_back(DAG.getRegister(RegToPass.first,
2932                                   RegToPass.second.getValueType()));
2933   }
2934 
2935   // Add a register mask operand representing the call-preserved registers.
2936 
2937   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2938   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2939   assert(Mask && "Missing call preserved mask for calling convention");
2940   Ops.push_back(DAG.getRegisterMask(Mask));
2941 
2942   if (InFlag.getNode())
2943     Ops.push_back(InFlag);
2944 
2945   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2946 
2947   // If we're doing a tall call, use a TC_RETURN here rather than an
2948   // actual call instruction.
2949   if (IsTailCall) {
2950     MFI.setHasTailCall();
2951     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2952   }
2953 
2954   // Returns a chain and a flag for retval copy to use.
2955   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2956   Chain = Call.getValue(0);
2957   InFlag = Call.getValue(1);
2958 
2959   uint64_t CalleePopBytes = NumBytes;
2960   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2961                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2962                              InFlag, DL);
2963   if (!Ins.empty())
2964     InFlag = Chain.getValue(1);
2965 
2966   // Handle result values, copying them out of physregs into vregs that we
2967   // return.
2968   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2969                          InVals, IsThisReturn,
2970                          IsThisReturn ? OutVals[0] : SDValue());
2971 }
2972 
2973 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2974                                              SelectionDAG &DAG) const {
2975   unsigned Reg = StringSwitch<unsigned>(RegName)
2976     .Case("m0", AMDGPU::M0)
2977     .Case("exec", AMDGPU::EXEC)
2978     .Case("exec_lo", AMDGPU::EXEC_LO)
2979     .Case("exec_hi", AMDGPU::EXEC_HI)
2980     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2981     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2982     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2983     .Default(AMDGPU::NoRegister);
2984 
2985   if (Reg == AMDGPU::NoRegister) {
2986     report_fatal_error(Twine("invalid register name \""
2987                              + StringRef(RegName)  + "\"."));
2988 
2989   }
2990 
2991   if (!Subtarget->hasFlatScrRegister() &&
2992        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2993     report_fatal_error(Twine("invalid register \""
2994                              + StringRef(RegName)  + "\" for subtarget."));
2995   }
2996 
2997   switch (Reg) {
2998   case AMDGPU::M0:
2999   case AMDGPU::EXEC_LO:
3000   case AMDGPU::EXEC_HI:
3001   case AMDGPU::FLAT_SCR_LO:
3002   case AMDGPU::FLAT_SCR_HI:
3003     if (VT.getSizeInBits() == 32)
3004       return Reg;
3005     break;
3006   case AMDGPU::EXEC:
3007   case AMDGPU::FLAT_SCR:
3008     if (VT.getSizeInBits() == 64)
3009       return Reg;
3010     break;
3011   default:
3012     llvm_unreachable("missing register type checking");
3013   }
3014 
3015   report_fatal_error(Twine("invalid type for register \""
3016                            + StringRef(RegName) + "\"."));
3017 }
3018 
3019 // If kill is not the last instruction, split the block so kill is always a
3020 // proper terminator.
3021 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3022                                                     MachineBasicBlock *BB) const {
3023   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3024 
3025   MachineBasicBlock::iterator SplitPoint(&MI);
3026   ++SplitPoint;
3027 
3028   if (SplitPoint == BB->end()) {
3029     // Don't bother with a new block.
3030     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3031     return BB;
3032   }
3033 
3034   MachineFunction *MF = BB->getParent();
3035   MachineBasicBlock *SplitBB
3036     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3037 
3038   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3039   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3040 
3041   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3042   BB->addSuccessor(SplitBB);
3043 
3044   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3045   return SplitBB;
3046 }
3047 
3048 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3049 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3050 // be the first instruction in the remainder block.
3051 //
3052 /// \returns { LoopBody, Remainder }
3053 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3054 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3055   MachineFunction *MF = MBB.getParent();
3056   MachineBasicBlock::iterator I(&MI);
3057 
3058   // To insert the loop we need to split the block. Move everything after this
3059   // point to a new block, and insert a new empty block between the two.
3060   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3061   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3062   MachineFunction::iterator MBBI(MBB);
3063   ++MBBI;
3064 
3065   MF->insert(MBBI, LoopBB);
3066   MF->insert(MBBI, RemainderBB);
3067 
3068   LoopBB->addSuccessor(LoopBB);
3069   LoopBB->addSuccessor(RemainderBB);
3070 
3071   // Move the rest of the block into a new block.
3072   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3073 
3074   if (InstInLoop) {
3075     auto Next = std::next(I);
3076 
3077     // Move instruction to loop body.
3078     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3079 
3080     // Move the rest of the block.
3081     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3082   } else {
3083     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3084   }
3085 
3086   MBB.addSuccessor(LoopBB);
3087 
3088   return std::make_pair(LoopBB, RemainderBB);
3089 }
3090 
3091 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3092 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3093   MachineBasicBlock *MBB = MI.getParent();
3094   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3095   auto I = MI.getIterator();
3096   auto E = std::next(I);
3097 
3098   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3099     .addImm(0);
3100 
3101   MIBundleBuilder Bundler(*MBB, I, E);
3102   finalizeBundle(*MBB, Bundler.begin());
3103 }
3104 
3105 MachineBasicBlock *
3106 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3107                                          MachineBasicBlock *BB) const {
3108   const DebugLoc &DL = MI.getDebugLoc();
3109 
3110   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3111 
3112   MachineBasicBlock *LoopBB;
3113   MachineBasicBlock *RemainderBB;
3114   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3115 
3116   // Apparently kill flags are only valid if the def is in the same block?
3117   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3118     Src->setIsKill(false);
3119 
3120   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3121 
3122   MachineBasicBlock::iterator I = LoopBB->end();
3123 
3124   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3125     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3126 
3127   // Clear TRAP_STS.MEM_VIOL
3128   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3129     .addImm(0)
3130     .addImm(EncodedReg);
3131 
3132   bundleInstWithWaitcnt(MI);
3133 
3134   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3135 
3136   // Load and check TRAP_STS.MEM_VIOL
3137   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3138     .addImm(EncodedReg);
3139 
3140   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3141   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3142     .addReg(Reg, RegState::Kill)
3143     .addImm(0);
3144   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3145     .addMBB(LoopBB);
3146 
3147   return RemainderBB;
3148 }
3149 
3150 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3151 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3152 // will only do one iteration. In the worst case, this will loop 64 times.
3153 //
3154 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3155 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3156   const SIInstrInfo *TII,
3157   MachineRegisterInfo &MRI,
3158   MachineBasicBlock &OrigBB,
3159   MachineBasicBlock &LoopBB,
3160   const DebugLoc &DL,
3161   const MachineOperand &IdxReg,
3162   unsigned InitReg,
3163   unsigned ResultReg,
3164   unsigned PhiReg,
3165   unsigned InitSaveExecReg,
3166   int Offset,
3167   bool UseGPRIdxMode,
3168   bool IsIndirectSrc) {
3169   MachineFunction *MF = OrigBB.getParent();
3170   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3171   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3172   MachineBasicBlock::iterator I = LoopBB.begin();
3173 
3174   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3175   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3176   Register NewExec = MRI.createVirtualRegister(BoolRC);
3177   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3178   Register CondReg = MRI.createVirtualRegister(BoolRC);
3179 
3180   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3181     .addReg(InitReg)
3182     .addMBB(&OrigBB)
3183     .addReg(ResultReg)
3184     .addMBB(&LoopBB);
3185 
3186   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3187     .addReg(InitSaveExecReg)
3188     .addMBB(&OrigBB)
3189     .addReg(NewExec)
3190     .addMBB(&LoopBB);
3191 
3192   // Read the next variant <- also loop target.
3193   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3194     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3195 
3196   // Compare the just read M0 value to all possible Idx values.
3197   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3198     .addReg(CurrentIdxReg)
3199     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3200 
3201   // Update EXEC, save the original EXEC value to VCC.
3202   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3203                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3204           NewExec)
3205     .addReg(CondReg, RegState::Kill);
3206 
3207   MRI.setSimpleHint(NewExec, CondReg);
3208 
3209   if (UseGPRIdxMode) {
3210     unsigned IdxReg;
3211     if (Offset == 0) {
3212       IdxReg = CurrentIdxReg;
3213     } else {
3214       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3215       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3216         .addReg(CurrentIdxReg, RegState::Kill)
3217         .addImm(Offset);
3218     }
3219     unsigned IdxMode = IsIndirectSrc ?
3220       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3221     MachineInstr *SetOn =
3222       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3223       .addReg(IdxReg, RegState::Kill)
3224       .addImm(IdxMode);
3225     SetOn->getOperand(3).setIsUndef();
3226   } else {
3227     // Move index from VCC into M0
3228     if (Offset == 0) {
3229       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3230         .addReg(CurrentIdxReg, RegState::Kill);
3231     } else {
3232       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3233         .addReg(CurrentIdxReg, RegState::Kill)
3234         .addImm(Offset);
3235     }
3236   }
3237 
3238   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3239   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3240   MachineInstr *InsertPt =
3241     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3242                                                   : AMDGPU::S_XOR_B64_term), Exec)
3243       .addReg(Exec)
3244       .addReg(NewExec);
3245 
3246   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3247   // s_cbranch_scc0?
3248 
3249   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3250   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3251     .addMBB(&LoopBB);
3252 
3253   return InsertPt->getIterator();
3254 }
3255 
3256 // This has slightly sub-optimal regalloc when the source vector is killed by
3257 // the read. The register allocator does not understand that the kill is
3258 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3259 // subregister from it, using 1 more VGPR than necessary. This was saved when
3260 // this was expanded after register allocation.
3261 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3262                                                   MachineBasicBlock &MBB,
3263                                                   MachineInstr &MI,
3264                                                   unsigned InitResultReg,
3265                                                   unsigned PhiReg,
3266                                                   int Offset,
3267                                                   bool UseGPRIdxMode,
3268                                                   bool IsIndirectSrc) {
3269   MachineFunction *MF = MBB.getParent();
3270   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3271   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3272   MachineRegisterInfo &MRI = MF->getRegInfo();
3273   const DebugLoc &DL = MI.getDebugLoc();
3274   MachineBasicBlock::iterator I(&MI);
3275 
3276   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3277   Register DstReg = MI.getOperand(0).getReg();
3278   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3279   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3280   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3281   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3282 
3283   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3284 
3285   // Save the EXEC mask
3286   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3287     .addReg(Exec);
3288 
3289   MachineBasicBlock *LoopBB;
3290   MachineBasicBlock *RemainderBB;
3291   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3292 
3293   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3294 
3295   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3296                                       InitResultReg, DstReg, PhiReg, TmpExec,
3297                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3298 
3299   MachineBasicBlock::iterator First = RemainderBB->begin();
3300   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3301     .addReg(SaveExec);
3302 
3303   return InsPt;
3304 }
3305 
3306 // Returns subreg index, offset
3307 static std::pair<unsigned, int>
3308 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3309                             const TargetRegisterClass *SuperRC,
3310                             unsigned VecReg,
3311                             int Offset) {
3312   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3313 
3314   // Skip out of bounds offsets, or else we would end up using an undefined
3315   // register.
3316   if (Offset >= NumElts || Offset < 0)
3317     return std::make_pair(AMDGPU::sub0, Offset);
3318 
3319   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3320 }
3321 
3322 // Return true if the index is an SGPR and was set.
3323 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3324                                  MachineRegisterInfo &MRI,
3325                                  MachineInstr &MI,
3326                                  int Offset,
3327                                  bool UseGPRIdxMode,
3328                                  bool IsIndirectSrc) {
3329   MachineBasicBlock *MBB = MI.getParent();
3330   const DebugLoc &DL = MI.getDebugLoc();
3331   MachineBasicBlock::iterator I(&MI);
3332 
3333   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3334   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3335 
3336   assert(Idx->getReg() != AMDGPU::NoRegister);
3337 
3338   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3339     return false;
3340 
3341   if (UseGPRIdxMode) {
3342     unsigned IdxMode = IsIndirectSrc ?
3343       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3344     if (Offset == 0) {
3345       MachineInstr *SetOn =
3346           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3347               .add(*Idx)
3348               .addImm(IdxMode);
3349 
3350       SetOn->getOperand(3).setIsUndef();
3351     } else {
3352       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3353       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3354           .add(*Idx)
3355           .addImm(Offset);
3356       MachineInstr *SetOn =
3357         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3358         .addReg(Tmp, RegState::Kill)
3359         .addImm(IdxMode);
3360 
3361       SetOn->getOperand(3).setIsUndef();
3362     }
3363 
3364     return true;
3365   }
3366 
3367   if (Offset == 0) {
3368     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3369       .add(*Idx);
3370   } else {
3371     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3372       .add(*Idx)
3373       .addImm(Offset);
3374   }
3375 
3376   return true;
3377 }
3378 
3379 // Control flow needs to be inserted if indexing with a VGPR.
3380 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3381                                           MachineBasicBlock &MBB,
3382                                           const GCNSubtarget &ST) {
3383   const SIInstrInfo *TII = ST.getInstrInfo();
3384   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3385   MachineFunction *MF = MBB.getParent();
3386   MachineRegisterInfo &MRI = MF->getRegInfo();
3387 
3388   Register Dst = MI.getOperand(0).getReg();
3389   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3390   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3391 
3392   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3393 
3394   unsigned SubReg;
3395   std::tie(SubReg, Offset)
3396     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3397 
3398   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3399 
3400   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3401     MachineBasicBlock::iterator I(&MI);
3402     const DebugLoc &DL = MI.getDebugLoc();
3403 
3404     if (UseGPRIdxMode) {
3405       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3406       // to avoid interfering with other uses, so probably requires a new
3407       // optimization pass.
3408       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3409         .addReg(SrcReg, RegState::Undef, SubReg)
3410         .addReg(SrcReg, RegState::Implicit)
3411         .addReg(AMDGPU::M0, RegState::Implicit);
3412       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3413     } else {
3414       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3415         .addReg(SrcReg, RegState::Undef, SubReg)
3416         .addReg(SrcReg, RegState::Implicit);
3417     }
3418 
3419     MI.eraseFromParent();
3420 
3421     return &MBB;
3422   }
3423 
3424   const DebugLoc &DL = MI.getDebugLoc();
3425   MachineBasicBlock::iterator I(&MI);
3426 
3427   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3428   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3429 
3430   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3431 
3432   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3433                               Offset, UseGPRIdxMode, true);
3434   MachineBasicBlock *LoopBB = InsPt->getParent();
3435 
3436   if (UseGPRIdxMode) {
3437     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3438       .addReg(SrcReg, RegState::Undef, SubReg)
3439       .addReg(SrcReg, RegState::Implicit)
3440       .addReg(AMDGPU::M0, RegState::Implicit);
3441     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3442   } else {
3443     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3444       .addReg(SrcReg, RegState::Undef, SubReg)
3445       .addReg(SrcReg, RegState::Implicit);
3446   }
3447 
3448   MI.eraseFromParent();
3449 
3450   return LoopBB;
3451 }
3452 
3453 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3454                                  const TargetRegisterClass *VecRC) {
3455   switch (TRI.getRegSizeInBits(*VecRC)) {
3456   case 32: // 4 bytes
3457     return AMDGPU::V_MOVRELD_B32_V1;
3458   case 64: // 8 bytes
3459     return AMDGPU::V_MOVRELD_B32_V2;
3460   case 128: // 16 bytes
3461     return AMDGPU::V_MOVRELD_B32_V4;
3462   case 256: // 32 bytes
3463     return AMDGPU::V_MOVRELD_B32_V8;
3464   case 512: // 64 bytes
3465     return AMDGPU::V_MOVRELD_B32_V16;
3466   default:
3467     llvm_unreachable("unsupported size for MOVRELD pseudos");
3468   }
3469 }
3470 
3471 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3472                                           MachineBasicBlock &MBB,
3473                                           const GCNSubtarget &ST) {
3474   const SIInstrInfo *TII = ST.getInstrInfo();
3475   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3476   MachineFunction *MF = MBB.getParent();
3477   MachineRegisterInfo &MRI = MF->getRegInfo();
3478 
3479   Register Dst = MI.getOperand(0).getReg();
3480   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3481   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3482   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3483   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3484   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3485 
3486   // This can be an immediate, but will be folded later.
3487   assert(Val->getReg());
3488 
3489   unsigned SubReg;
3490   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3491                                                          SrcVec->getReg(),
3492                                                          Offset);
3493   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3494 
3495   if (Idx->getReg() == AMDGPU::NoRegister) {
3496     MachineBasicBlock::iterator I(&MI);
3497     const DebugLoc &DL = MI.getDebugLoc();
3498 
3499     assert(Offset == 0);
3500 
3501     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3502         .add(*SrcVec)
3503         .add(*Val)
3504         .addImm(SubReg);
3505 
3506     MI.eraseFromParent();
3507     return &MBB;
3508   }
3509 
3510   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3511     MachineBasicBlock::iterator I(&MI);
3512     const DebugLoc &DL = MI.getDebugLoc();
3513 
3514     if (UseGPRIdxMode) {
3515       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3516           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3517           .add(*Val)
3518           .addReg(Dst, RegState::ImplicitDefine)
3519           .addReg(SrcVec->getReg(), RegState::Implicit)
3520           .addReg(AMDGPU::M0, RegState::Implicit);
3521 
3522       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3523     } else {
3524       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3525 
3526       BuildMI(MBB, I, DL, MovRelDesc)
3527           .addReg(Dst, RegState::Define)
3528           .addReg(SrcVec->getReg())
3529           .add(*Val)
3530           .addImm(SubReg - AMDGPU::sub0);
3531     }
3532 
3533     MI.eraseFromParent();
3534     return &MBB;
3535   }
3536 
3537   if (Val->isReg())
3538     MRI.clearKillFlags(Val->getReg());
3539 
3540   const DebugLoc &DL = MI.getDebugLoc();
3541 
3542   Register PhiReg = MRI.createVirtualRegister(VecRC);
3543 
3544   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3545                               Offset, UseGPRIdxMode, false);
3546   MachineBasicBlock *LoopBB = InsPt->getParent();
3547 
3548   if (UseGPRIdxMode) {
3549     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3550         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3551         .add(*Val)                               // src0
3552         .addReg(Dst, RegState::ImplicitDefine)
3553         .addReg(PhiReg, RegState::Implicit)
3554         .addReg(AMDGPU::M0, RegState::Implicit);
3555     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3556   } else {
3557     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3558 
3559     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3560         .addReg(Dst, RegState::Define)
3561         .addReg(PhiReg)
3562         .add(*Val)
3563         .addImm(SubReg - AMDGPU::sub0);
3564   }
3565 
3566   MI.eraseFromParent();
3567 
3568   return LoopBB;
3569 }
3570 
3571 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3572   MachineInstr &MI, MachineBasicBlock *BB) const {
3573 
3574   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3575   MachineFunction *MF = BB->getParent();
3576   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3577 
3578   if (TII->isMIMG(MI)) {
3579     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3580       report_fatal_error("missing mem operand from MIMG instruction");
3581     }
3582     // Add a memoperand for mimg instructions so that they aren't assumed to
3583     // be ordered memory instuctions.
3584 
3585     return BB;
3586   }
3587 
3588   switch (MI.getOpcode()) {
3589   case AMDGPU::S_ADD_U64_PSEUDO:
3590   case AMDGPU::S_SUB_U64_PSEUDO: {
3591     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3592     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3593     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3594     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3595     const DebugLoc &DL = MI.getDebugLoc();
3596 
3597     MachineOperand &Dest = MI.getOperand(0);
3598     MachineOperand &Src0 = MI.getOperand(1);
3599     MachineOperand &Src1 = MI.getOperand(2);
3600 
3601     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3602     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3603 
3604     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3605      Src0, BoolRC, AMDGPU::sub0,
3606      &AMDGPU::SReg_32_XM0RegClass);
3607     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3608       Src0, BoolRC, AMDGPU::sub1,
3609       &AMDGPU::SReg_32_XM0RegClass);
3610 
3611     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3612       Src1, BoolRC, AMDGPU::sub0,
3613       &AMDGPU::SReg_32_XM0RegClass);
3614     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3615       Src1, BoolRC, AMDGPU::sub1,
3616       &AMDGPU::SReg_32_XM0RegClass);
3617 
3618     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3619 
3620     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3621     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3622     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3623       .add(Src0Sub0)
3624       .add(Src1Sub0);
3625     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3626       .add(Src0Sub1)
3627       .add(Src1Sub1);
3628     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3629       .addReg(DestSub0)
3630       .addImm(AMDGPU::sub0)
3631       .addReg(DestSub1)
3632       .addImm(AMDGPU::sub1);
3633     MI.eraseFromParent();
3634     return BB;
3635   }
3636   case AMDGPU::SI_INIT_M0: {
3637     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3638             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3639         .add(MI.getOperand(0));
3640     MI.eraseFromParent();
3641     return BB;
3642   }
3643   case AMDGPU::SI_INIT_EXEC:
3644     // This should be before all vector instructions.
3645     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3646             AMDGPU::EXEC)
3647         .addImm(MI.getOperand(0).getImm());
3648     MI.eraseFromParent();
3649     return BB;
3650 
3651   case AMDGPU::SI_INIT_EXEC_LO:
3652     // This should be before all vector instructions.
3653     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3654             AMDGPU::EXEC_LO)
3655         .addImm(MI.getOperand(0).getImm());
3656     MI.eraseFromParent();
3657     return BB;
3658 
3659   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3660     // Extract the thread count from an SGPR input and set EXEC accordingly.
3661     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3662     //
3663     // S_BFE_U32 count, input, {shift, 7}
3664     // S_BFM_B64 exec, count, 0
3665     // S_CMP_EQ_U32 count, 64
3666     // S_CMOV_B64 exec, -1
3667     MachineInstr *FirstMI = &*BB->begin();
3668     MachineRegisterInfo &MRI = MF->getRegInfo();
3669     Register InputReg = MI.getOperand(0).getReg();
3670     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3671     bool Found = false;
3672 
3673     // Move the COPY of the input reg to the beginning, so that we can use it.
3674     for (auto I = BB->begin(); I != &MI; I++) {
3675       if (I->getOpcode() != TargetOpcode::COPY ||
3676           I->getOperand(0).getReg() != InputReg)
3677         continue;
3678 
3679       if (I == FirstMI) {
3680         FirstMI = &*++BB->begin();
3681       } else {
3682         I->removeFromParent();
3683         BB->insert(FirstMI, &*I);
3684       }
3685       Found = true;
3686       break;
3687     }
3688     assert(Found);
3689     (void)Found;
3690 
3691     // This should be before all vector instructions.
3692     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3693     bool isWave32 = getSubtarget()->isWave32();
3694     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3695     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3696         .addReg(InputReg)
3697         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3698     BuildMI(*BB, FirstMI, DebugLoc(),
3699             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3700             Exec)
3701         .addReg(CountReg)
3702         .addImm(0);
3703     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3704         .addReg(CountReg, RegState::Kill)
3705         .addImm(getSubtarget()->getWavefrontSize());
3706     BuildMI(*BB, FirstMI, DebugLoc(),
3707             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3708             Exec)
3709         .addImm(-1);
3710     MI.eraseFromParent();
3711     return BB;
3712   }
3713 
3714   case AMDGPU::GET_GROUPSTATICSIZE: {
3715     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3716            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3717     DebugLoc DL = MI.getDebugLoc();
3718     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3719         .add(MI.getOperand(0))
3720         .addImm(MFI->getLDSSize());
3721     MI.eraseFromParent();
3722     return BB;
3723   }
3724   case AMDGPU::SI_INDIRECT_SRC_V1:
3725   case AMDGPU::SI_INDIRECT_SRC_V2:
3726   case AMDGPU::SI_INDIRECT_SRC_V4:
3727   case AMDGPU::SI_INDIRECT_SRC_V8:
3728   case AMDGPU::SI_INDIRECT_SRC_V16:
3729     return emitIndirectSrc(MI, *BB, *getSubtarget());
3730   case AMDGPU::SI_INDIRECT_DST_V1:
3731   case AMDGPU::SI_INDIRECT_DST_V2:
3732   case AMDGPU::SI_INDIRECT_DST_V4:
3733   case AMDGPU::SI_INDIRECT_DST_V8:
3734   case AMDGPU::SI_INDIRECT_DST_V16:
3735     return emitIndirectDst(MI, *BB, *getSubtarget());
3736   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3737   case AMDGPU::SI_KILL_I1_PSEUDO:
3738     return splitKillBlock(MI, BB);
3739   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3740     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3741     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3742     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3743 
3744     Register Dst = MI.getOperand(0).getReg();
3745     Register Src0 = MI.getOperand(1).getReg();
3746     Register Src1 = MI.getOperand(2).getReg();
3747     const DebugLoc &DL = MI.getDebugLoc();
3748     Register SrcCond = MI.getOperand(3).getReg();
3749 
3750     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3751     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3752     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3753     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3754 
3755     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3756       .addReg(SrcCond);
3757     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3758       .addImm(0)
3759       .addReg(Src0, 0, AMDGPU::sub0)
3760       .addImm(0)
3761       .addReg(Src1, 0, AMDGPU::sub0)
3762       .addReg(SrcCondCopy);
3763     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3764       .addImm(0)
3765       .addReg(Src0, 0, AMDGPU::sub1)
3766       .addImm(0)
3767       .addReg(Src1, 0, AMDGPU::sub1)
3768       .addReg(SrcCondCopy);
3769 
3770     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3771       .addReg(DstLo)
3772       .addImm(AMDGPU::sub0)
3773       .addReg(DstHi)
3774       .addImm(AMDGPU::sub1);
3775     MI.eraseFromParent();
3776     return BB;
3777   }
3778   case AMDGPU::SI_BR_UNDEF: {
3779     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3780     const DebugLoc &DL = MI.getDebugLoc();
3781     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3782                            .add(MI.getOperand(0));
3783     Br->getOperand(1).setIsUndef(true); // read undef SCC
3784     MI.eraseFromParent();
3785     return BB;
3786   }
3787   case AMDGPU::ADJCALLSTACKUP:
3788   case AMDGPU::ADJCALLSTACKDOWN: {
3789     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3790     MachineInstrBuilder MIB(*MF, &MI);
3791 
3792     // Add an implicit use of the frame offset reg to prevent the restore copy
3793     // inserted after the call from being reorderd after stack operations in the
3794     // the caller's frame.
3795     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3796         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3797         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3798     return BB;
3799   }
3800   case AMDGPU::SI_CALL_ISEL: {
3801     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3802     const DebugLoc &DL = MI.getDebugLoc();
3803 
3804     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3805 
3806     MachineInstrBuilder MIB;
3807     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3808 
3809     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3810       MIB.add(MI.getOperand(I));
3811 
3812     MIB.cloneMemRefs(MI);
3813     MI.eraseFromParent();
3814     return BB;
3815   }
3816   case AMDGPU::V_ADD_I32_e32:
3817   case AMDGPU::V_SUB_I32_e32:
3818   case AMDGPU::V_SUBREV_I32_e32: {
3819     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3820     const DebugLoc &DL = MI.getDebugLoc();
3821     unsigned Opc = MI.getOpcode();
3822 
3823     bool NeedClampOperand = false;
3824     if (TII->pseudoToMCOpcode(Opc) == -1) {
3825       Opc = AMDGPU::getVOPe64(Opc);
3826       NeedClampOperand = true;
3827     }
3828 
3829     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3830     if (TII->isVOP3(*I)) {
3831       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3832       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3833       I.addReg(TRI->getVCC(), RegState::Define);
3834     }
3835     I.add(MI.getOperand(1))
3836      .add(MI.getOperand(2));
3837     if (NeedClampOperand)
3838       I.addImm(0); // clamp bit for e64 encoding
3839 
3840     TII->legalizeOperands(*I);
3841 
3842     MI.eraseFromParent();
3843     return BB;
3844   }
3845   case AMDGPU::DS_GWS_INIT:
3846   case AMDGPU::DS_GWS_SEMA_V:
3847   case AMDGPU::DS_GWS_SEMA_BR:
3848   case AMDGPU::DS_GWS_SEMA_P:
3849   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3850   case AMDGPU::DS_GWS_BARRIER:
3851     // A s_waitcnt 0 is required to be the instruction immediately following.
3852     if (getSubtarget()->hasGWSAutoReplay()) {
3853       bundleInstWithWaitcnt(MI);
3854       return BB;
3855     }
3856 
3857     return emitGWSMemViolTestLoop(MI, BB);
3858   default:
3859     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3860   }
3861 }
3862 
3863 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3864   return isTypeLegal(VT.getScalarType());
3865 }
3866 
3867 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3868   // This currently forces unfolding various combinations of fsub into fma with
3869   // free fneg'd operands. As long as we have fast FMA (controlled by
3870   // isFMAFasterThanFMulAndFAdd), we should perform these.
3871 
3872   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3873   // most of these combines appear to be cycle neutral but save on instruction
3874   // count / code size.
3875   return true;
3876 }
3877 
3878 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3879                                          EVT VT) const {
3880   if (!VT.isVector()) {
3881     return MVT::i1;
3882   }
3883   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3884 }
3885 
3886 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3887   // TODO: Should i16 be used always if legal? For now it would force VALU
3888   // shifts.
3889   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3890 }
3891 
3892 // Answering this is somewhat tricky and depends on the specific device which
3893 // have different rates for fma or all f64 operations.
3894 //
3895 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3896 // regardless of which device (although the number of cycles differs between
3897 // devices), so it is always profitable for f64.
3898 //
3899 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3900 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3901 // which we can always do even without fused FP ops since it returns the same
3902 // result as the separate operations and since it is always full
3903 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3904 // however does not support denormals, so we do report fma as faster if we have
3905 // a fast fma device and require denormals.
3906 //
3907 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3908   VT = VT.getScalarType();
3909 
3910   switch (VT.getSimpleVT().SimpleTy) {
3911   case MVT::f32: {
3912     // This is as fast on some subtargets. However, we always have full rate f32
3913     // mad available which returns the same result as the separate operations
3914     // which we should prefer over fma. We can't use this if we want to support
3915     // denormals, so only report this in these cases.
3916     if (Subtarget->hasFP32Denormals())
3917       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3918 
3919     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3920     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3921   }
3922   case MVT::f64:
3923     return true;
3924   case MVT::f16:
3925     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3926   default:
3927     break;
3928   }
3929 
3930   return false;
3931 }
3932 
3933 //===----------------------------------------------------------------------===//
3934 // Custom DAG Lowering Operations
3935 //===----------------------------------------------------------------------===//
3936 
3937 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3938 // wider vector type is legal.
3939 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3940                                              SelectionDAG &DAG) const {
3941   unsigned Opc = Op.getOpcode();
3942   EVT VT = Op.getValueType();
3943   assert(VT == MVT::v4f16);
3944 
3945   SDValue Lo, Hi;
3946   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3947 
3948   SDLoc SL(Op);
3949   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3950                              Op->getFlags());
3951   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3952                              Op->getFlags());
3953 
3954   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3955 }
3956 
3957 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3958 // wider vector type is legal.
3959 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3960                                               SelectionDAG &DAG) const {
3961   unsigned Opc = Op.getOpcode();
3962   EVT VT = Op.getValueType();
3963   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3964 
3965   SDValue Lo0, Hi0;
3966   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3967   SDValue Lo1, Hi1;
3968   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3969 
3970   SDLoc SL(Op);
3971 
3972   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3973                              Op->getFlags());
3974   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3975                              Op->getFlags());
3976 
3977   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3978 }
3979 
3980 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
3981                                               SelectionDAG &DAG) const {
3982   unsigned Opc = Op.getOpcode();
3983   EVT VT = Op.getValueType();
3984   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3985 
3986   SDValue Lo0, Hi0;
3987   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3988   SDValue Lo1, Hi1;
3989   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3990   SDValue Lo2, Hi2;
3991   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
3992 
3993   SDLoc SL(Op);
3994 
3995   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
3996                              Op->getFlags());
3997   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
3998                              Op->getFlags());
3999 
4000   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4001 }
4002 
4003 
4004 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4005   switch (Op.getOpcode()) {
4006   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4007   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4008   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4009   case ISD::LOAD: {
4010     SDValue Result = LowerLOAD(Op, DAG);
4011     assert((!Result.getNode() ||
4012             Result.getNode()->getNumValues() == 2) &&
4013            "Load should return a value and a chain");
4014     return Result;
4015   }
4016 
4017   case ISD::FSIN:
4018   case ISD::FCOS:
4019     return LowerTrig(Op, DAG);
4020   case ISD::SELECT: return LowerSELECT(Op, DAG);
4021   case ISD::FDIV: return LowerFDIV(Op, DAG);
4022   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4023   case ISD::STORE: return LowerSTORE(Op, DAG);
4024   case ISD::GlobalAddress: {
4025     MachineFunction &MF = DAG.getMachineFunction();
4026     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4027     return LowerGlobalAddress(MFI, Op, DAG);
4028   }
4029   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4030   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4031   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4032   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4033   case ISD::INSERT_SUBVECTOR:
4034     return lowerINSERT_SUBVECTOR(Op, DAG);
4035   case ISD::INSERT_VECTOR_ELT:
4036     return lowerINSERT_VECTOR_ELT(Op, DAG);
4037   case ISD::EXTRACT_VECTOR_ELT:
4038     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4039   case ISD::VECTOR_SHUFFLE:
4040     return lowerVECTOR_SHUFFLE(Op, DAG);
4041   case ISD::BUILD_VECTOR:
4042     return lowerBUILD_VECTOR(Op, DAG);
4043   case ISD::FP_ROUND:
4044     return lowerFP_ROUND(Op, DAG);
4045   case ISD::TRAP:
4046     return lowerTRAP(Op, DAG);
4047   case ISD::DEBUGTRAP:
4048     return lowerDEBUGTRAP(Op, DAG);
4049   case ISD::FABS:
4050   case ISD::FNEG:
4051   case ISD::FCANONICALIZE:
4052     return splitUnaryVectorOp(Op, DAG);
4053   case ISD::FMINNUM:
4054   case ISD::FMAXNUM:
4055     return lowerFMINNUM_FMAXNUM(Op, DAG);
4056   case ISD::FMA:
4057     return splitTernaryVectorOp(Op, DAG);
4058   case ISD::SHL:
4059   case ISD::SRA:
4060   case ISD::SRL:
4061   case ISD::ADD:
4062   case ISD::SUB:
4063   case ISD::MUL:
4064   case ISD::SMIN:
4065   case ISD::SMAX:
4066   case ISD::UMIN:
4067   case ISD::UMAX:
4068   case ISD::FADD:
4069   case ISD::FMUL:
4070   case ISD::FMINNUM_IEEE:
4071   case ISD::FMAXNUM_IEEE:
4072     return splitBinaryVectorOp(Op, DAG);
4073   }
4074   return SDValue();
4075 }
4076 
4077 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4078                                        const SDLoc &DL,
4079                                        SelectionDAG &DAG, bool Unpacked) {
4080   if (!LoadVT.isVector())
4081     return Result;
4082 
4083   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4084     // Truncate to v2i16/v4i16.
4085     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4086 
4087     // Workaround legalizer not scalarizing truncate after vector op
4088     // legalization byt not creating intermediate vector trunc.
4089     SmallVector<SDValue, 4> Elts;
4090     DAG.ExtractVectorElements(Result, Elts);
4091     for (SDValue &Elt : Elts)
4092       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4093 
4094     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4095 
4096     // Bitcast to original type (v2f16/v4f16).
4097     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4098   }
4099 
4100   // Cast back to the original packed type.
4101   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4102 }
4103 
4104 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4105                                               MemSDNode *M,
4106                                               SelectionDAG &DAG,
4107                                               ArrayRef<SDValue> Ops,
4108                                               bool IsIntrinsic) const {
4109   SDLoc DL(M);
4110 
4111   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4112   EVT LoadVT = M->getValueType(0);
4113 
4114   EVT EquivLoadVT = LoadVT;
4115   if (Unpacked && LoadVT.isVector()) {
4116     EquivLoadVT = LoadVT.isVector() ?
4117       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4118                        LoadVT.getVectorNumElements()) : LoadVT;
4119   }
4120 
4121   // Change from v4f16/v2f16 to EquivLoadVT.
4122   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4123 
4124   SDValue Load
4125     = DAG.getMemIntrinsicNode(
4126       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4127       VTList, Ops, M->getMemoryVT(),
4128       M->getMemOperand());
4129   if (!Unpacked) // Just adjusted the opcode.
4130     return Load;
4131 
4132   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4133 
4134   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4135 }
4136 
4137 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4138                                              SelectionDAG &DAG,
4139                                              ArrayRef<SDValue> Ops) const {
4140   SDLoc DL(M);
4141   EVT LoadVT = M->getValueType(0);
4142   EVT EltType = LoadVT.getScalarType();
4143   EVT IntVT = LoadVT.changeTypeToInteger();
4144 
4145   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4146 
4147   unsigned Opc =
4148       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4149 
4150   if (IsD16) {
4151     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4152   }
4153 
4154   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4155   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4156     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4157 
4158   if (isTypeLegal(LoadVT)) {
4159     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4160                                M->getMemOperand(), DAG);
4161   }
4162 
4163   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4164   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4165   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4166                                         M->getMemOperand(), DAG);
4167   return DAG.getMergeValues(
4168       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4169       DL);
4170 }
4171 
4172 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4173                                   SDNode *N, SelectionDAG &DAG) {
4174   EVT VT = N->getValueType(0);
4175   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4176   int CondCode = CD->getSExtValue();
4177   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4178       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4179     return DAG.getUNDEF(VT);
4180 
4181   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4182 
4183   SDValue LHS = N->getOperand(1);
4184   SDValue RHS = N->getOperand(2);
4185 
4186   SDLoc DL(N);
4187 
4188   EVT CmpVT = LHS.getValueType();
4189   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4190     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4191       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4192     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4193     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4194   }
4195 
4196   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4197 
4198   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4199   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4200 
4201   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4202                               DAG.getCondCode(CCOpcode));
4203   if (VT.bitsEq(CCVT))
4204     return SetCC;
4205   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4206 }
4207 
4208 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4209                                   SDNode *N, SelectionDAG &DAG) {
4210   EVT VT = N->getValueType(0);
4211   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4212 
4213   int CondCode = CD->getSExtValue();
4214   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4215       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4216     return DAG.getUNDEF(VT);
4217   }
4218 
4219   SDValue Src0 = N->getOperand(1);
4220   SDValue Src1 = N->getOperand(2);
4221   EVT CmpVT = Src0.getValueType();
4222   SDLoc SL(N);
4223 
4224   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4225     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4226     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4227   }
4228 
4229   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4230   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4231   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4232   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4233   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4234                               Src1, DAG.getCondCode(CCOpcode));
4235   if (VT.bitsEq(CCVT))
4236     return SetCC;
4237   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4238 }
4239 
4240 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4241                                           SmallVectorImpl<SDValue> &Results,
4242                                           SelectionDAG &DAG) const {
4243   switch (N->getOpcode()) {
4244   case ISD::INSERT_VECTOR_ELT: {
4245     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4246       Results.push_back(Res);
4247     return;
4248   }
4249   case ISD::EXTRACT_VECTOR_ELT: {
4250     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4251       Results.push_back(Res);
4252     return;
4253   }
4254   case ISD::INTRINSIC_WO_CHAIN: {
4255     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4256     switch (IID) {
4257     case Intrinsic::amdgcn_cvt_pkrtz: {
4258       SDValue Src0 = N->getOperand(1);
4259       SDValue Src1 = N->getOperand(2);
4260       SDLoc SL(N);
4261       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4262                                 Src0, Src1);
4263       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4264       return;
4265     }
4266     case Intrinsic::amdgcn_cvt_pknorm_i16:
4267     case Intrinsic::amdgcn_cvt_pknorm_u16:
4268     case Intrinsic::amdgcn_cvt_pk_i16:
4269     case Intrinsic::amdgcn_cvt_pk_u16: {
4270       SDValue Src0 = N->getOperand(1);
4271       SDValue Src1 = N->getOperand(2);
4272       SDLoc SL(N);
4273       unsigned Opcode;
4274 
4275       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4276         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4277       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4278         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4279       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4280         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4281       else
4282         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4283 
4284       EVT VT = N->getValueType(0);
4285       if (isTypeLegal(VT))
4286         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4287       else {
4288         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4289         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4290       }
4291       return;
4292     }
4293     }
4294     break;
4295   }
4296   case ISD::INTRINSIC_W_CHAIN: {
4297     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4298       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4299         // FIXME: Hacky
4300         Results.push_back(Res.getOperand(0));
4301         Results.push_back(Res.getOperand(1));
4302       } else {
4303         Results.push_back(Res);
4304         Results.push_back(Res.getValue(1));
4305       }
4306       return;
4307     }
4308 
4309     break;
4310   }
4311   case ISD::SELECT: {
4312     SDLoc SL(N);
4313     EVT VT = N->getValueType(0);
4314     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4315     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4316     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4317 
4318     EVT SelectVT = NewVT;
4319     if (NewVT.bitsLT(MVT::i32)) {
4320       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4321       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4322       SelectVT = MVT::i32;
4323     }
4324 
4325     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4326                                     N->getOperand(0), LHS, RHS);
4327 
4328     if (NewVT != SelectVT)
4329       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4330     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4331     return;
4332   }
4333   case ISD::FNEG: {
4334     if (N->getValueType(0) != MVT::v2f16)
4335       break;
4336 
4337     SDLoc SL(N);
4338     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4339 
4340     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4341                              BC,
4342                              DAG.getConstant(0x80008000, SL, MVT::i32));
4343     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4344     return;
4345   }
4346   case ISD::FABS: {
4347     if (N->getValueType(0) != MVT::v2f16)
4348       break;
4349 
4350     SDLoc SL(N);
4351     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4352 
4353     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4354                              BC,
4355                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4356     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4357     return;
4358   }
4359   default:
4360     break;
4361   }
4362 }
4363 
4364 /// Helper function for LowerBRCOND
4365 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4366 
4367   SDNode *Parent = Value.getNode();
4368   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4369        I != E; ++I) {
4370 
4371     if (I.getUse().get() != Value)
4372       continue;
4373 
4374     if (I->getOpcode() == Opcode)
4375       return *I;
4376   }
4377   return nullptr;
4378 }
4379 
4380 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4381   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4382     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4383     case Intrinsic::amdgcn_if:
4384       return AMDGPUISD::IF;
4385     case Intrinsic::amdgcn_else:
4386       return AMDGPUISD::ELSE;
4387     case Intrinsic::amdgcn_loop:
4388       return AMDGPUISD::LOOP;
4389     case Intrinsic::amdgcn_end_cf:
4390       llvm_unreachable("should not occur");
4391     default:
4392       return 0;
4393     }
4394   }
4395 
4396   // break, if_break, else_break are all only used as inputs to loop, not
4397   // directly as branch conditions.
4398   return 0;
4399 }
4400 
4401 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4402   const Triple &TT = getTargetMachine().getTargetTriple();
4403   return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4404           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4405          AMDGPU::shouldEmitConstantsToTextSection(TT);
4406 }
4407 
4408 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4409   // FIXME: Either avoid relying on address space here or change the default
4410   // address space for functions to avoid the explicit check.
4411   return (GV->getValueType()->isFunctionTy() ||
4412           GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4413           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4414           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4415          !shouldEmitFixup(GV) &&
4416          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4417 }
4418 
4419 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4420   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4421 }
4422 
4423 /// This transforms the control flow intrinsics to get the branch destination as
4424 /// last parameter, also switches branch target with BR if the need arise
4425 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4426                                       SelectionDAG &DAG) const {
4427   SDLoc DL(BRCOND);
4428 
4429   SDNode *Intr = BRCOND.getOperand(1).getNode();
4430   SDValue Target = BRCOND.getOperand(2);
4431   SDNode *BR = nullptr;
4432   SDNode *SetCC = nullptr;
4433 
4434   if (Intr->getOpcode() == ISD::SETCC) {
4435     // As long as we negate the condition everything is fine
4436     SetCC = Intr;
4437     Intr = SetCC->getOperand(0).getNode();
4438 
4439   } else {
4440     // Get the target from BR if we don't negate the condition
4441     BR = findUser(BRCOND, ISD::BR);
4442     Target = BR->getOperand(1);
4443   }
4444 
4445   // FIXME: This changes the types of the intrinsics instead of introducing new
4446   // nodes with the correct types.
4447   // e.g. llvm.amdgcn.loop
4448 
4449   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4450   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4451 
4452   unsigned CFNode = isCFIntrinsic(Intr);
4453   if (CFNode == 0) {
4454     // This is a uniform branch so we don't need to legalize.
4455     return BRCOND;
4456   }
4457 
4458   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4459                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4460 
4461   assert(!SetCC ||
4462         (SetCC->getConstantOperandVal(1) == 1 &&
4463          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4464                                                              ISD::SETNE));
4465 
4466   // operands of the new intrinsic call
4467   SmallVector<SDValue, 4> Ops;
4468   if (HaveChain)
4469     Ops.push_back(BRCOND.getOperand(0));
4470 
4471   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4472   Ops.push_back(Target);
4473 
4474   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4475 
4476   // build the new intrinsic call
4477   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4478 
4479   if (!HaveChain) {
4480     SDValue Ops[] =  {
4481       SDValue(Result, 0),
4482       BRCOND.getOperand(0)
4483     };
4484 
4485     Result = DAG.getMergeValues(Ops, DL).getNode();
4486   }
4487 
4488   if (BR) {
4489     // Give the branch instruction our target
4490     SDValue Ops[] = {
4491       BR->getOperand(0),
4492       BRCOND.getOperand(2)
4493     };
4494     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4495     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4496     BR = NewBR.getNode();
4497   }
4498 
4499   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4500 
4501   // Copy the intrinsic results to registers
4502   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4503     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4504     if (!CopyToReg)
4505       continue;
4506 
4507     Chain = DAG.getCopyToReg(
4508       Chain, DL,
4509       CopyToReg->getOperand(1),
4510       SDValue(Result, i - 1),
4511       SDValue());
4512 
4513     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4514   }
4515 
4516   // Remove the old intrinsic from the chain
4517   DAG.ReplaceAllUsesOfValueWith(
4518     SDValue(Intr, Intr->getNumValues() - 1),
4519     Intr->getOperand(0));
4520 
4521   return Chain;
4522 }
4523 
4524 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4525                                           SelectionDAG &DAG) const {
4526   MVT VT = Op.getSimpleValueType();
4527   SDLoc DL(Op);
4528   // Checking the depth
4529   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4530     return DAG.getConstant(0, DL, VT);
4531 
4532   MachineFunction &MF = DAG.getMachineFunction();
4533   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4534   // Check for kernel and shader functions
4535   if (Info->isEntryFunction())
4536     return DAG.getConstant(0, DL, VT);
4537 
4538   MachineFrameInfo &MFI = MF.getFrameInfo();
4539   // There is a call to @llvm.returnaddress in this function
4540   MFI.setReturnAddressIsTaken(true);
4541 
4542   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4543   // Get the return address reg and mark it as an implicit live-in
4544   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4545 
4546   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4547 }
4548 
4549 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4550                                             SDValue Op,
4551                                             const SDLoc &DL,
4552                                             EVT VT) const {
4553   return Op.getValueType().bitsLE(VT) ?
4554       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4555       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4556 }
4557 
4558 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4559   assert(Op.getValueType() == MVT::f16 &&
4560          "Do not know how to custom lower FP_ROUND for non-f16 type");
4561 
4562   SDValue Src = Op.getOperand(0);
4563   EVT SrcVT = Src.getValueType();
4564   if (SrcVT != MVT::f64)
4565     return Op;
4566 
4567   SDLoc DL(Op);
4568 
4569   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4570   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4571   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4572 }
4573 
4574 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4575                                                SelectionDAG &DAG) const {
4576   EVT VT = Op.getValueType();
4577   const MachineFunction &MF = DAG.getMachineFunction();
4578   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4579   bool IsIEEEMode = Info->getMode().IEEE;
4580 
4581   // FIXME: Assert during eslection that this is only selected for
4582   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4583   // mode functions, but this happens to be OK since it's only done in cases
4584   // where there is known no sNaN.
4585   if (IsIEEEMode)
4586     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4587 
4588   if (VT == MVT::v4f16)
4589     return splitBinaryVectorOp(Op, DAG);
4590   return Op;
4591 }
4592 
4593 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4594   SDLoc SL(Op);
4595   SDValue Chain = Op.getOperand(0);
4596 
4597   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4598       !Subtarget->isTrapHandlerEnabled())
4599     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4600 
4601   MachineFunction &MF = DAG.getMachineFunction();
4602   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4603   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4604   assert(UserSGPR != AMDGPU::NoRegister);
4605   SDValue QueuePtr = CreateLiveInRegister(
4606     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4607   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4608   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4609                                    QueuePtr, SDValue());
4610   SDValue Ops[] = {
4611     ToReg,
4612     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4613     SGPR01,
4614     ToReg.getValue(1)
4615   };
4616   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4617 }
4618 
4619 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4620   SDLoc SL(Op);
4621   SDValue Chain = Op.getOperand(0);
4622   MachineFunction &MF = DAG.getMachineFunction();
4623 
4624   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4625       !Subtarget->isTrapHandlerEnabled()) {
4626     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4627                                      "debugtrap handler not supported",
4628                                      Op.getDebugLoc(),
4629                                      DS_Warning);
4630     LLVMContext &Ctx = MF.getFunction().getContext();
4631     Ctx.diagnose(NoTrap);
4632     return Chain;
4633   }
4634 
4635   SDValue Ops[] = {
4636     Chain,
4637     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4638   };
4639   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4640 }
4641 
4642 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4643                                              SelectionDAG &DAG) const {
4644   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4645   if (Subtarget->hasApertureRegs()) {
4646     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4647         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4648         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4649     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4650         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4651         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4652     unsigned Encoding =
4653         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4654         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4655         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4656 
4657     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4658     SDValue ApertureReg = SDValue(
4659         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4660     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4661     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4662   }
4663 
4664   MachineFunction &MF = DAG.getMachineFunction();
4665   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4666   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4667   assert(UserSGPR != AMDGPU::NoRegister);
4668 
4669   SDValue QueuePtr = CreateLiveInRegister(
4670     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4671 
4672   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4673   // private_segment_aperture_base_hi.
4674   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4675 
4676   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4677 
4678   // TODO: Use custom target PseudoSourceValue.
4679   // TODO: We should use the value from the IR intrinsic call, but it might not
4680   // be available and how do we get it?
4681   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4682                                               AMDGPUAS::CONSTANT_ADDRESS));
4683 
4684   MachinePointerInfo PtrInfo(V, StructOffset);
4685   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4686                      MinAlign(64, StructOffset),
4687                      MachineMemOperand::MODereferenceable |
4688                          MachineMemOperand::MOInvariant);
4689 }
4690 
4691 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4692                                              SelectionDAG &DAG) const {
4693   SDLoc SL(Op);
4694   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4695 
4696   SDValue Src = ASC->getOperand(0);
4697   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4698 
4699   const AMDGPUTargetMachine &TM =
4700     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4701 
4702   // flat -> local/private
4703   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4704     unsigned DestAS = ASC->getDestAddressSpace();
4705 
4706     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4707         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4708       unsigned NullVal = TM.getNullPointerValue(DestAS);
4709       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4710       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4711       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4712 
4713       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4714                          NonNull, Ptr, SegmentNullPtr);
4715     }
4716   }
4717 
4718   // local/private -> flat
4719   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4720     unsigned SrcAS = ASC->getSrcAddressSpace();
4721 
4722     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4723         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4724       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4725       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4726 
4727       SDValue NonNull
4728         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4729 
4730       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4731       SDValue CvtPtr
4732         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4733 
4734       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4735                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4736                          FlatNullPtr);
4737     }
4738   }
4739 
4740   // global <-> flat are no-ops and never emitted.
4741 
4742   const MachineFunction &MF = DAG.getMachineFunction();
4743   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4744     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4745   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4746 
4747   return DAG.getUNDEF(ASC->getValueType(0));
4748 }
4749 
4750 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4751 // the small vector and inserting them into the big vector. That is better than
4752 // the default expansion of doing it via a stack slot. Even though the use of
4753 // the stack slot would be optimized away afterwards, the stack slot itself
4754 // remains.
4755 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4756                                                 SelectionDAG &DAG) const {
4757   SDValue Vec = Op.getOperand(0);
4758   SDValue Ins = Op.getOperand(1);
4759   SDValue Idx = Op.getOperand(2);
4760   EVT VecVT = Vec.getValueType();
4761   EVT InsVT = Ins.getValueType();
4762   EVT EltVT = VecVT.getVectorElementType();
4763   unsigned InsNumElts = InsVT.getVectorNumElements();
4764   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4765   SDLoc SL(Op);
4766 
4767   for (unsigned I = 0; I != InsNumElts; ++I) {
4768     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4769                               DAG.getConstant(I, SL, MVT::i32));
4770     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4771                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4772   }
4773   return Vec;
4774 }
4775 
4776 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4777                                                  SelectionDAG &DAG) const {
4778   SDValue Vec = Op.getOperand(0);
4779   SDValue InsVal = Op.getOperand(1);
4780   SDValue Idx = Op.getOperand(2);
4781   EVT VecVT = Vec.getValueType();
4782   EVT EltVT = VecVT.getVectorElementType();
4783   unsigned VecSize = VecVT.getSizeInBits();
4784   unsigned EltSize = EltVT.getSizeInBits();
4785 
4786 
4787   assert(VecSize <= 64);
4788 
4789   unsigned NumElts = VecVT.getVectorNumElements();
4790   SDLoc SL(Op);
4791   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4792 
4793   if (NumElts == 4 && EltSize == 16 && KIdx) {
4794     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4795 
4796     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4797                                  DAG.getConstant(0, SL, MVT::i32));
4798     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4799                                  DAG.getConstant(1, SL, MVT::i32));
4800 
4801     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4802     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4803 
4804     unsigned Idx = KIdx->getZExtValue();
4805     bool InsertLo = Idx < 2;
4806     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4807       InsertLo ? LoVec : HiVec,
4808       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4809       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4810 
4811     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4812 
4813     SDValue Concat = InsertLo ?
4814       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4815       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4816 
4817     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4818   }
4819 
4820   if (isa<ConstantSDNode>(Idx))
4821     return SDValue();
4822 
4823   MVT IntVT = MVT::getIntegerVT(VecSize);
4824 
4825   // Avoid stack access for dynamic indexing.
4826   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4827 
4828   // Create a congruent vector with the target value in each element so that
4829   // the required element can be masked and ORed into the target vector.
4830   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4831                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4832 
4833   assert(isPowerOf2_32(EltSize));
4834   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4835 
4836   // Convert vector index to bit-index.
4837   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4838 
4839   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4840   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4841                             DAG.getConstant(0xffff, SL, IntVT),
4842                             ScaledIdx);
4843 
4844   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4845   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4846                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4847 
4848   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4849   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4850 }
4851 
4852 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4853                                                   SelectionDAG &DAG) const {
4854   SDLoc SL(Op);
4855 
4856   EVT ResultVT = Op.getValueType();
4857   SDValue Vec = Op.getOperand(0);
4858   SDValue Idx = Op.getOperand(1);
4859   EVT VecVT = Vec.getValueType();
4860   unsigned VecSize = VecVT.getSizeInBits();
4861   EVT EltVT = VecVT.getVectorElementType();
4862   assert(VecSize <= 64);
4863 
4864   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4865 
4866   // Make sure we do any optimizations that will make it easier to fold
4867   // source modifiers before obscuring it with bit operations.
4868 
4869   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4870   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4871     return Combined;
4872 
4873   unsigned EltSize = EltVT.getSizeInBits();
4874   assert(isPowerOf2_32(EltSize));
4875 
4876   MVT IntVT = MVT::getIntegerVT(VecSize);
4877   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4878 
4879   // Convert vector index to bit-index (* EltSize)
4880   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4881 
4882   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4883   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4884 
4885   if (ResultVT == MVT::f16) {
4886     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4887     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4888   }
4889 
4890   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4891 }
4892 
4893 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4894   assert(Elt % 2 == 0);
4895   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4896 }
4897 
4898 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4899                                               SelectionDAG &DAG) const {
4900   SDLoc SL(Op);
4901   EVT ResultVT = Op.getValueType();
4902   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4903 
4904   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4905   EVT EltVT = PackVT.getVectorElementType();
4906   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4907 
4908   // vector_shuffle <0,1,6,7> lhs, rhs
4909   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4910   //
4911   // vector_shuffle <6,7,2,3> lhs, rhs
4912   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4913   //
4914   // vector_shuffle <6,7,0,1> lhs, rhs
4915   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4916 
4917   // Avoid scalarizing when both halves are reading from consecutive elements.
4918   SmallVector<SDValue, 4> Pieces;
4919   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4920     if (elementPairIsContiguous(SVN->getMask(), I)) {
4921       const int Idx = SVN->getMaskElt(I);
4922       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4923       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4924       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4925                                     PackVT, SVN->getOperand(VecIdx),
4926                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4927       Pieces.push_back(SubVec);
4928     } else {
4929       const int Idx0 = SVN->getMaskElt(I);
4930       const int Idx1 = SVN->getMaskElt(I + 1);
4931       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4932       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4933       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4934       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4935 
4936       SDValue Vec0 = SVN->getOperand(VecIdx0);
4937       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4938                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4939 
4940       SDValue Vec1 = SVN->getOperand(VecIdx1);
4941       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4942                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4943       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4944     }
4945   }
4946 
4947   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4948 }
4949 
4950 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4951                                             SelectionDAG &DAG) const {
4952   SDLoc SL(Op);
4953   EVT VT = Op.getValueType();
4954 
4955   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4956     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4957 
4958     // Turn into pair of packed build_vectors.
4959     // TODO: Special case for constants that can be materialized with s_mov_b64.
4960     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4961                                     { Op.getOperand(0), Op.getOperand(1) });
4962     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4963                                     { Op.getOperand(2), Op.getOperand(3) });
4964 
4965     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4966     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4967 
4968     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4969     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4970   }
4971 
4972   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4973   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4974 
4975   SDValue Lo = Op.getOperand(0);
4976   SDValue Hi = Op.getOperand(1);
4977 
4978   // Avoid adding defined bits with the zero_extend.
4979   if (Hi.isUndef()) {
4980     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4981     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4982     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4983   }
4984 
4985   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4986   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4987 
4988   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4989                               DAG.getConstant(16, SL, MVT::i32));
4990   if (Lo.isUndef())
4991     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4992 
4993   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4994   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4995 
4996   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4997   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4998 }
4999 
5000 bool
5001 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5002   // We can fold offsets for anything that doesn't require a GOT relocation.
5003   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5004           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5005           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5006          !shouldEmitGOTReloc(GA->getGlobal());
5007 }
5008 
5009 static SDValue
5010 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5011                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5012                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5013   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5014   // lowered to the following code sequence:
5015   //
5016   // For constant address space:
5017   //   s_getpc_b64 s[0:1]
5018   //   s_add_u32 s0, s0, $symbol
5019   //   s_addc_u32 s1, s1, 0
5020   //
5021   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5022   //   a fixup or relocation is emitted to replace $symbol with a literal
5023   //   constant, which is a pc-relative offset from the encoding of the $symbol
5024   //   operand to the global variable.
5025   //
5026   // For global address space:
5027   //   s_getpc_b64 s[0:1]
5028   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5029   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5030   //
5031   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5032   //   fixups or relocations are emitted to replace $symbol@*@lo and
5033   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5034   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5035   //   operand to the global variable.
5036   //
5037   // What we want here is an offset from the value returned by s_getpc
5038   // (which is the address of the s_add_u32 instruction) to the global
5039   // variable, but since the encoding of $symbol starts 4 bytes after the start
5040   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5041   // small. This requires us to add 4 to the global variable offset in order to
5042   // compute the correct address.
5043   SDValue PtrLo =
5044       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5045   SDValue PtrHi;
5046   if (GAFlags == SIInstrInfo::MO_NONE) {
5047     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5048   } else {
5049     PtrHi =
5050         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5051   }
5052   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5053 }
5054 
5055 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5056                                              SDValue Op,
5057                                              SelectionDAG &DAG) const {
5058   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5059   const GlobalValue *GV = GSD->getGlobal();
5060   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5061        (!GV->hasExternalLinkage() ||
5062         getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
5063         getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
5064       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5065       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5066     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5067 
5068   SDLoc DL(GSD);
5069   EVT PtrVT = Op.getValueType();
5070 
5071   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5072     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5073                                             SIInstrInfo::MO_ABS32_LO);
5074     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5075   }
5076 
5077   if (shouldEmitFixup(GV))
5078     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5079   else if (shouldEmitPCReloc(GV))
5080     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5081                                    SIInstrInfo::MO_REL32);
5082 
5083   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5084                                             SIInstrInfo::MO_GOTPCREL32);
5085 
5086   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5087   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5088   const DataLayout &DataLayout = DAG.getDataLayout();
5089   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5090   MachinePointerInfo PtrInfo
5091     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5092 
5093   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5094                      MachineMemOperand::MODereferenceable |
5095                          MachineMemOperand::MOInvariant);
5096 }
5097 
5098 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5099                                    const SDLoc &DL, SDValue V) const {
5100   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5101   // the destination register.
5102   //
5103   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5104   // so we will end up with redundant moves to m0.
5105   //
5106   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5107 
5108   // A Null SDValue creates a glue result.
5109   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5110                                   V, Chain);
5111   return SDValue(M0, 0);
5112 }
5113 
5114 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5115                                                  SDValue Op,
5116                                                  MVT VT,
5117                                                  unsigned Offset) const {
5118   SDLoc SL(Op);
5119   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5120                                            DAG.getEntryNode(), Offset, 4, false);
5121   // The local size values will have the hi 16-bits as zero.
5122   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5123                      DAG.getValueType(VT));
5124 }
5125 
5126 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5127                                         EVT VT) {
5128   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5129                                       "non-hsa intrinsic with hsa target",
5130                                       DL.getDebugLoc());
5131   DAG.getContext()->diagnose(BadIntrin);
5132   return DAG.getUNDEF(VT);
5133 }
5134 
5135 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5136                                          EVT VT) {
5137   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5138                                       "intrinsic not supported on subtarget",
5139                                       DL.getDebugLoc());
5140   DAG.getContext()->diagnose(BadIntrin);
5141   return DAG.getUNDEF(VT);
5142 }
5143 
5144 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5145                                     ArrayRef<SDValue> Elts) {
5146   assert(!Elts.empty());
5147   MVT Type;
5148   unsigned NumElts;
5149 
5150   if (Elts.size() == 1) {
5151     Type = MVT::f32;
5152     NumElts = 1;
5153   } else if (Elts.size() == 2) {
5154     Type = MVT::v2f32;
5155     NumElts = 2;
5156   } else if (Elts.size() <= 4) {
5157     Type = MVT::v4f32;
5158     NumElts = 4;
5159   } else if (Elts.size() <= 8) {
5160     Type = MVT::v8f32;
5161     NumElts = 8;
5162   } else {
5163     assert(Elts.size() <= 16);
5164     Type = MVT::v16f32;
5165     NumElts = 16;
5166   }
5167 
5168   SmallVector<SDValue, 16> VecElts(NumElts);
5169   for (unsigned i = 0; i < Elts.size(); ++i) {
5170     SDValue Elt = Elts[i];
5171     if (Elt.getValueType() != MVT::f32)
5172       Elt = DAG.getBitcast(MVT::f32, Elt);
5173     VecElts[i] = Elt;
5174   }
5175   for (unsigned i = Elts.size(); i < NumElts; ++i)
5176     VecElts[i] = DAG.getUNDEF(MVT::f32);
5177 
5178   if (NumElts == 1)
5179     return VecElts[0];
5180   return DAG.getBuildVector(Type, DL, VecElts);
5181 }
5182 
5183 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5184                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5185   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5186 
5187   uint64_t Value = CachePolicyConst->getZExtValue();
5188   SDLoc DL(CachePolicy);
5189   if (GLC) {
5190     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5191     Value &= ~(uint64_t)0x1;
5192   }
5193   if (SLC) {
5194     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5195     Value &= ~(uint64_t)0x2;
5196   }
5197   if (DLC) {
5198     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5199     Value &= ~(uint64_t)0x4;
5200   }
5201 
5202   return Value == 0;
5203 }
5204 
5205 // Re-construct the required return value for a image load intrinsic.
5206 // This is more complicated due to the optional use TexFailCtrl which means the required
5207 // return type is an aggregate
5208 static SDValue constructRetValue(SelectionDAG &DAG,
5209                                  MachineSDNode *Result,
5210                                  ArrayRef<EVT> ResultTypes,
5211                                  bool IsTexFail, bool Unpacked, bool IsD16,
5212                                  int DMaskPop, int NumVDataDwords,
5213                                  const SDLoc &DL, LLVMContext &Context) {
5214   // Determine the required return type. This is the same regardless of IsTexFail flag
5215   EVT ReqRetVT = ResultTypes[0];
5216   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5217   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5218   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5219   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5220                                            : AdjEltVT
5221                        : ReqRetVT;
5222 
5223   // Extract data part of the result
5224   // Bitcast the result to the same type as the required return type
5225   int NumElts;
5226   if (IsD16 && !Unpacked)
5227     NumElts = NumVDataDwords << 1;
5228   else
5229     NumElts = NumVDataDwords;
5230 
5231   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5232                            : AdjEltVT;
5233 
5234   // Special case for v6f16. Rather than add support for this, use v3i32 to
5235   // extract the data elements
5236   bool V6F16Special = false;
5237   if (NumElts == 6) {
5238     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5239     DMaskPop >>= 1;
5240     ReqRetNumElts >>= 1;
5241     V6F16Special = true;
5242     AdjVT = MVT::v2i32;
5243   }
5244 
5245   SDValue N = SDValue(Result, 0);
5246   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5247 
5248   // Iterate over the result
5249   SmallVector<SDValue, 4> BVElts;
5250 
5251   if (CastVT.isVector()) {
5252     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5253   } else {
5254     BVElts.push_back(CastRes);
5255   }
5256   int ExtraElts = ReqRetNumElts - DMaskPop;
5257   while(ExtraElts--)
5258     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5259 
5260   SDValue PreTFCRes;
5261   if (ReqRetNumElts > 1) {
5262     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5263     if (IsD16 && Unpacked)
5264       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5265     else
5266       PreTFCRes = NewVec;
5267   } else {
5268     PreTFCRes = BVElts[0];
5269   }
5270 
5271   if (V6F16Special)
5272     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5273 
5274   if (!IsTexFail) {
5275     if (Result->getNumValues() > 1)
5276       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5277     else
5278       return PreTFCRes;
5279   }
5280 
5281   // Extract the TexFail result and insert into aggregate return
5282   SmallVector<SDValue, 1> TFCElt;
5283   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5284   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5285   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5286 }
5287 
5288 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5289                          SDValue *LWE, bool &IsTexFail) {
5290   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5291 
5292   uint64_t Value = TexFailCtrlConst->getZExtValue();
5293   if (Value) {
5294     IsTexFail = true;
5295   }
5296 
5297   SDLoc DL(TexFailCtrlConst);
5298   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5299   Value &= ~(uint64_t)0x1;
5300   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5301   Value &= ~(uint64_t)0x2;
5302 
5303   return Value == 0;
5304 }
5305 
5306 SDValue SITargetLowering::lowerImage(SDValue Op,
5307                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5308                                      SelectionDAG &DAG) const {
5309   SDLoc DL(Op);
5310   MachineFunction &MF = DAG.getMachineFunction();
5311   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5312   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5313       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5314   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5315   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5316       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5317   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5318       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5319   unsigned IntrOpcode = Intr->BaseOpcode;
5320   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5321 
5322   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5323   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5324   bool IsD16 = false;
5325   bool IsA16 = false;
5326   SDValue VData;
5327   int NumVDataDwords;
5328   bool AdjustRetType = false;
5329 
5330   unsigned AddrIdx; // Index of first address argument
5331   unsigned DMask;
5332   unsigned DMaskLanes = 0;
5333 
5334   if (BaseOpcode->Atomic) {
5335     VData = Op.getOperand(2);
5336 
5337     bool Is64Bit = VData.getValueType() == MVT::i64;
5338     if (BaseOpcode->AtomicX2) {
5339       SDValue VData2 = Op.getOperand(3);
5340       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5341                                  {VData, VData2});
5342       if (Is64Bit)
5343         VData = DAG.getBitcast(MVT::v4i32, VData);
5344 
5345       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5346       DMask = Is64Bit ? 0xf : 0x3;
5347       NumVDataDwords = Is64Bit ? 4 : 2;
5348       AddrIdx = 4;
5349     } else {
5350       DMask = Is64Bit ? 0x3 : 0x1;
5351       NumVDataDwords = Is64Bit ? 2 : 1;
5352       AddrIdx = 3;
5353     }
5354   } else {
5355     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5356     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5357     DMask = DMaskConst->getZExtValue();
5358     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5359 
5360     if (BaseOpcode->Store) {
5361       VData = Op.getOperand(2);
5362 
5363       MVT StoreVT = VData.getSimpleValueType();
5364       if (StoreVT.getScalarType() == MVT::f16) {
5365         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5366           return Op; // D16 is unsupported for this instruction
5367 
5368         IsD16 = true;
5369         VData = handleD16VData(VData, DAG);
5370       }
5371 
5372       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5373     } else {
5374       // Work out the num dwords based on the dmask popcount and underlying type
5375       // and whether packing is supported.
5376       MVT LoadVT = ResultTypes[0].getSimpleVT();
5377       if (LoadVT.getScalarType() == MVT::f16) {
5378         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5379           return Op; // D16 is unsupported for this instruction
5380 
5381         IsD16 = true;
5382       }
5383 
5384       // Confirm that the return type is large enough for the dmask specified
5385       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5386           (!LoadVT.isVector() && DMaskLanes > 1))
5387           return Op;
5388 
5389       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5390         NumVDataDwords = (DMaskLanes + 1) / 2;
5391       else
5392         NumVDataDwords = DMaskLanes;
5393 
5394       AdjustRetType = true;
5395     }
5396 
5397     AddrIdx = DMaskIdx + 1;
5398   }
5399 
5400   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5401   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5402   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5403   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5404                        NumCoords + NumLCM;
5405   unsigned NumMIVAddrs = NumVAddrs;
5406 
5407   SmallVector<SDValue, 4> VAddrs;
5408 
5409   // Optimize _L to _LZ when _L is zero
5410   if (LZMappingInfo) {
5411     if (auto ConstantLod =
5412          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5413       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5414         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5415         NumMIVAddrs--;               // remove 'lod'
5416       }
5417     }
5418   }
5419 
5420   // Optimize _mip away, when 'lod' is zero
5421   if (MIPMappingInfo) {
5422     if (auto ConstantLod =
5423          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5424       if (ConstantLod->isNullValue()) {
5425         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5426         NumMIVAddrs--;               // remove 'lod'
5427       }
5428     }
5429   }
5430 
5431   // Check for 16 bit addresses and pack if true.
5432   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5433   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5434   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5435   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5436       ST->hasFeature(AMDGPU::FeatureR128A16)) {
5437     IsA16 = true;
5438     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5439     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5440       SDValue AddrLo, AddrHi;
5441       // Push back extra arguments.
5442       if (i < DimIdx) {
5443         AddrLo = Op.getOperand(i);
5444       } else {
5445         AddrLo = Op.getOperand(i);
5446         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5447         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5448         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5449             ((NumGradients / 2) % 2 == 1 &&
5450             (i == DimIdx + (NumGradients / 2) - 1 ||
5451              i == DimIdx + NumGradients - 1))) {
5452           AddrHi = DAG.getUNDEF(MVT::f16);
5453         } else {
5454           AddrHi = Op.getOperand(i + 1);
5455           i++;
5456         }
5457         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5458                              {AddrLo, AddrHi});
5459         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5460       }
5461       VAddrs.push_back(AddrLo);
5462     }
5463   } else {
5464     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5465       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5466   }
5467 
5468   // If the register allocator cannot place the address registers contiguously
5469   // without introducing moves, then using the non-sequential address encoding
5470   // is always preferable, since it saves VALU instructions and is usually a
5471   // wash in terms of code size or even better.
5472   //
5473   // However, we currently have no way of hinting to the register allocator that
5474   // MIMG addresses should be placed contiguously when it is possible to do so,
5475   // so force non-NSA for the common 2-address case as a heuristic.
5476   //
5477   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5478   // allocation when possible.
5479   bool UseNSA =
5480       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5481   SDValue VAddr;
5482   if (!UseNSA)
5483     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5484 
5485   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5486   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5487   unsigned CtrlIdx; // Index of texfailctrl argument
5488   SDValue Unorm;
5489   if (!BaseOpcode->Sampler) {
5490     Unorm = True;
5491     CtrlIdx = AddrIdx + NumVAddrs + 1;
5492   } else {
5493     auto UnormConst =
5494         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5495 
5496     Unorm = UnormConst->getZExtValue() ? True : False;
5497     CtrlIdx = AddrIdx + NumVAddrs + 3;
5498   }
5499 
5500   SDValue TFE;
5501   SDValue LWE;
5502   SDValue TexFail = Op.getOperand(CtrlIdx);
5503   bool IsTexFail = false;
5504   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5505     return Op;
5506 
5507   if (IsTexFail) {
5508     if (!DMaskLanes) {
5509       // Expecting to get an error flag since TFC is on - and dmask is 0
5510       // Force dmask to be at least 1 otherwise the instruction will fail
5511       DMask = 0x1;
5512       DMaskLanes = 1;
5513       NumVDataDwords = 1;
5514     }
5515     NumVDataDwords += 1;
5516     AdjustRetType = true;
5517   }
5518 
5519   // Has something earlier tagged that the return type needs adjusting
5520   // This happens if the instruction is a load or has set TexFailCtrl flags
5521   if (AdjustRetType) {
5522     // NumVDataDwords reflects the true number of dwords required in the return type
5523     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5524       // This is a no-op load. This can be eliminated
5525       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5526       if (isa<MemSDNode>(Op))
5527         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5528       return Undef;
5529     }
5530 
5531     EVT NewVT = NumVDataDwords > 1 ?
5532                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5533                 : MVT::f32;
5534 
5535     ResultTypes[0] = NewVT;
5536     if (ResultTypes.size() == 3) {
5537       // Original result was aggregate type used for TexFailCtrl results
5538       // The actual instruction returns as a vector type which has now been
5539       // created. Remove the aggregate result.
5540       ResultTypes.erase(&ResultTypes[1]);
5541     }
5542   }
5543 
5544   SDValue GLC;
5545   SDValue SLC;
5546   SDValue DLC;
5547   if (BaseOpcode->Atomic) {
5548     GLC = True; // TODO no-return optimization
5549     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5550                           IsGFX10 ? &DLC : nullptr))
5551       return Op;
5552   } else {
5553     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5554                           IsGFX10 ? &DLC : nullptr))
5555       return Op;
5556   }
5557 
5558   SmallVector<SDValue, 26> Ops;
5559   if (BaseOpcode->Store || BaseOpcode->Atomic)
5560     Ops.push_back(VData); // vdata
5561   if (UseNSA) {
5562     for (const SDValue &Addr : VAddrs)
5563       Ops.push_back(Addr);
5564   } else {
5565     Ops.push_back(VAddr);
5566   }
5567   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5568   if (BaseOpcode->Sampler)
5569     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5570   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5571   if (IsGFX10)
5572     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5573   Ops.push_back(Unorm);
5574   if (IsGFX10)
5575     Ops.push_back(DLC);
5576   Ops.push_back(GLC);
5577   Ops.push_back(SLC);
5578   Ops.push_back(IsA16 &&  // a16 or r128
5579                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5580   Ops.push_back(TFE); // tfe
5581   Ops.push_back(LWE); // lwe
5582   if (!IsGFX10)
5583     Ops.push_back(DimInfo->DA ? True : False);
5584   if (BaseOpcode->HasD16)
5585     Ops.push_back(IsD16 ? True : False);
5586   if (isa<MemSDNode>(Op))
5587     Ops.push_back(Op.getOperand(0)); // chain
5588 
5589   int NumVAddrDwords =
5590       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5591   int Opcode = -1;
5592 
5593   if (IsGFX10) {
5594     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5595                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5596                                           : AMDGPU::MIMGEncGfx10Default,
5597                                    NumVDataDwords, NumVAddrDwords);
5598   } else {
5599     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5600       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5601                                      NumVDataDwords, NumVAddrDwords);
5602     if (Opcode == -1)
5603       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5604                                      NumVDataDwords, NumVAddrDwords);
5605   }
5606   assert(Opcode != -1);
5607 
5608   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5609   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5610     MachineMemOperand *MemRef = MemOp->getMemOperand();
5611     DAG.setNodeMemRefs(NewNode, {MemRef});
5612   }
5613 
5614   if (BaseOpcode->AtomicX2) {
5615     SmallVector<SDValue, 1> Elt;
5616     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5617     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5618   } else if (!BaseOpcode->Store) {
5619     return constructRetValue(DAG, NewNode,
5620                              OrigResultTypes, IsTexFail,
5621                              Subtarget->hasUnpackedD16VMem(), IsD16,
5622                              DMaskLanes, NumVDataDwords, DL,
5623                              *DAG.getContext());
5624   }
5625 
5626   return SDValue(NewNode, 0);
5627 }
5628 
5629 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5630                                        SDValue Offset, SDValue GLC, SDValue DLC,
5631                                        SelectionDAG &DAG) const {
5632   MachineFunction &MF = DAG.getMachineFunction();
5633   MachineMemOperand *MMO = MF.getMachineMemOperand(
5634       MachinePointerInfo(),
5635       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5636           MachineMemOperand::MOInvariant,
5637       VT.getStoreSize(), VT.getStoreSize());
5638 
5639   if (!Offset->isDivergent()) {
5640     SDValue Ops[] = {
5641         Rsrc,
5642         Offset, // Offset
5643         GLC,
5644         DLC,
5645     };
5646     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5647                                    DAG.getVTList(VT), Ops, VT, MMO);
5648   }
5649 
5650   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5651   // assume that the buffer is unswizzled.
5652   SmallVector<SDValue, 4> Loads;
5653   unsigned NumLoads = 1;
5654   MVT LoadVT = VT.getSimpleVT();
5655   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5656   assert((LoadVT.getScalarType() == MVT::i32 ||
5657           LoadVT.getScalarType() == MVT::f32) &&
5658          isPowerOf2_32(NumElts));
5659 
5660   if (NumElts == 8 || NumElts == 16) {
5661     NumLoads = NumElts == 16 ? 4 : 2;
5662     LoadVT = MVT::v4i32;
5663   }
5664 
5665   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5666   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5667   SDValue Ops[] = {
5668       DAG.getEntryNode(),                         // Chain
5669       Rsrc,                                       // rsrc
5670       DAG.getConstant(0, DL, MVT::i32),           // vindex
5671       {},                                         // voffset
5672       {},                                         // soffset
5673       {},                                         // offset
5674       DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5675       DAG.getConstant(0, DL, MVT::i1),            // idxen
5676   };
5677 
5678   // Use the alignment to ensure that the required offsets will fit into the
5679   // immediate offsets.
5680   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5681 
5682   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5683   for (unsigned i = 0; i < NumLoads; ++i) {
5684     Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5685     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5686                                             Ops, LoadVT, MMO));
5687   }
5688 
5689   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5690     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5691 
5692   return Loads[0];
5693 }
5694 
5695 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5696                                                   SelectionDAG &DAG) const {
5697   MachineFunction &MF = DAG.getMachineFunction();
5698   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5699 
5700   EVT VT = Op.getValueType();
5701   SDLoc DL(Op);
5702   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5703 
5704   // TODO: Should this propagate fast-math-flags?
5705 
5706   switch (IntrinsicID) {
5707   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5708     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5709       return emitNonHSAIntrinsicError(DAG, DL, VT);
5710     return getPreloadedValue(DAG, *MFI, VT,
5711                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5712   }
5713   case Intrinsic::amdgcn_dispatch_ptr:
5714   case Intrinsic::amdgcn_queue_ptr: {
5715     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5716       DiagnosticInfoUnsupported BadIntrin(
5717           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5718           DL.getDebugLoc());
5719       DAG.getContext()->diagnose(BadIntrin);
5720       return DAG.getUNDEF(VT);
5721     }
5722 
5723     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5724       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5725     return getPreloadedValue(DAG, *MFI, VT, RegID);
5726   }
5727   case Intrinsic::amdgcn_implicitarg_ptr: {
5728     if (MFI->isEntryFunction())
5729       return getImplicitArgPtr(DAG, DL);
5730     return getPreloadedValue(DAG, *MFI, VT,
5731                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5732   }
5733   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5734     return getPreloadedValue(DAG, *MFI, VT,
5735                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5736   }
5737   case Intrinsic::amdgcn_dispatch_id: {
5738     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5739   }
5740   case Intrinsic::amdgcn_rcp:
5741     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5742   case Intrinsic::amdgcn_rsq:
5743     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5744   case Intrinsic::amdgcn_rsq_legacy:
5745     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5746       return emitRemovedIntrinsicError(DAG, DL, VT);
5747 
5748     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5749   case Intrinsic::amdgcn_rcp_legacy:
5750     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5751       return emitRemovedIntrinsicError(DAG, DL, VT);
5752     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5753   case Intrinsic::amdgcn_rsq_clamp: {
5754     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5755       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5756 
5757     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5758     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5759     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5760 
5761     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5762     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5763                               DAG.getConstantFP(Max, DL, VT));
5764     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5765                        DAG.getConstantFP(Min, DL, VT));
5766   }
5767   case Intrinsic::r600_read_ngroups_x:
5768     if (Subtarget->isAmdHsaOS())
5769       return emitNonHSAIntrinsicError(DAG, DL, VT);
5770 
5771     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5772                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5773   case Intrinsic::r600_read_ngroups_y:
5774     if (Subtarget->isAmdHsaOS())
5775       return emitNonHSAIntrinsicError(DAG, DL, VT);
5776 
5777     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5778                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5779   case Intrinsic::r600_read_ngroups_z:
5780     if (Subtarget->isAmdHsaOS())
5781       return emitNonHSAIntrinsicError(DAG, DL, VT);
5782 
5783     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5784                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5785   case Intrinsic::r600_read_global_size_x:
5786     if (Subtarget->isAmdHsaOS())
5787       return emitNonHSAIntrinsicError(DAG, DL, VT);
5788 
5789     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5790                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5791   case Intrinsic::r600_read_global_size_y:
5792     if (Subtarget->isAmdHsaOS())
5793       return emitNonHSAIntrinsicError(DAG, DL, VT);
5794 
5795     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5796                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5797   case Intrinsic::r600_read_global_size_z:
5798     if (Subtarget->isAmdHsaOS())
5799       return emitNonHSAIntrinsicError(DAG, DL, VT);
5800 
5801     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5802                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5803   case Intrinsic::r600_read_local_size_x:
5804     if (Subtarget->isAmdHsaOS())
5805       return emitNonHSAIntrinsicError(DAG, DL, VT);
5806 
5807     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5808                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5809   case Intrinsic::r600_read_local_size_y:
5810     if (Subtarget->isAmdHsaOS())
5811       return emitNonHSAIntrinsicError(DAG, DL, VT);
5812 
5813     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5814                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5815   case Intrinsic::r600_read_local_size_z:
5816     if (Subtarget->isAmdHsaOS())
5817       return emitNonHSAIntrinsicError(DAG, DL, VT);
5818 
5819     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5820                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5821   case Intrinsic::amdgcn_workgroup_id_x:
5822   case Intrinsic::r600_read_tgid_x:
5823     return getPreloadedValue(DAG, *MFI, VT,
5824                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5825   case Intrinsic::amdgcn_workgroup_id_y:
5826   case Intrinsic::r600_read_tgid_y:
5827     return getPreloadedValue(DAG, *MFI, VT,
5828                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5829   case Intrinsic::amdgcn_workgroup_id_z:
5830   case Intrinsic::r600_read_tgid_z:
5831     return getPreloadedValue(DAG, *MFI, VT,
5832                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5833   case Intrinsic::amdgcn_workitem_id_x:
5834   case Intrinsic::r600_read_tidig_x:
5835     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5836                           SDLoc(DAG.getEntryNode()),
5837                           MFI->getArgInfo().WorkItemIDX);
5838   case Intrinsic::amdgcn_workitem_id_y:
5839   case Intrinsic::r600_read_tidig_y:
5840     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5841                           SDLoc(DAG.getEntryNode()),
5842                           MFI->getArgInfo().WorkItemIDY);
5843   case Intrinsic::amdgcn_workitem_id_z:
5844   case Intrinsic::r600_read_tidig_z:
5845     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5846                           SDLoc(DAG.getEntryNode()),
5847                           MFI->getArgInfo().WorkItemIDZ);
5848   case Intrinsic::amdgcn_wavefrontsize:
5849     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5850                            SDLoc(Op), MVT::i32);
5851   case Intrinsic::amdgcn_s_buffer_load: {
5852     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5853     SDValue GLC;
5854     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5855     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5856                           IsGFX10 ? &DLC : nullptr))
5857       return Op;
5858     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5859                         DAG);
5860   }
5861   case Intrinsic::amdgcn_fdiv_fast:
5862     return lowerFDIV_FAST(Op, DAG);
5863   case Intrinsic::amdgcn_interp_mov: {
5864     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5865     SDValue Glue = M0.getValue(1);
5866     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5867                        Op.getOperand(2), Op.getOperand(3), Glue);
5868   }
5869   case Intrinsic::amdgcn_interp_p1: {
5870     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5871     SDValue Glue = M0.getValue(1);
5872     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5873                        Op.getOperand(2), Op.getOperand(3), Glue);
5874   }
5875   case Intrinsic::amdgcn_interp_p2: {
5876     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5877     SDValue Glue = SDValue(M0.getNode(), 1);
5878     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5879                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5880                        Glue);
5881   }
5882   case Intrinsic::amdgcn_interp_p1_f16: {
5883     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5884     SDValue Glue = M0.getValue(1);
5885     if (getSubtarget()->getLDSBankCount() == 16) {
5886       // 16 bank LDS
5887       SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5888                               DAG.getConstant(2, DL, MVT::i32), // P0
5889                               Op.getOperand(2), // Attrchan
5890                               Op.getOperand(3), // Attr
5891                               Glue);
5892       SDValue Ops[] = {
5893         Op.getOperand(1), // Src0
5894         Op.getOperand(2), // Attrchan
5895         Op.getOperand(3), // Attr
5896         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5897         S, // Src2 - holds two f16 values selected by high
5898         DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5899         Op.getOperand(4), // high
5900         DAG.getConstant(0, DL, MVT::i1), // $clamp
5901         DAG.getConstant(0, DL, MVT::i32) // $omod
5902       };
5903       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5904     } else {
5905       // 32 bank LDS
5906       SDValue Ops[] = {
5907         Op.getOperand(1), // Src0
5908         Op.getOperand(2), // Attrchan
5909         Op.getOperand(3), // Attr
5910         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5911         Op.getOperand(4), // high
5912         DAG.getConstant(0, DL, MVT::i1), // $clamp
5913         DAG.getConstant(0, DL, MVT::i32), // $omod
5914         Glue
5915       };
5916       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5917     }
5918   }
5919   case Intrinsic::amdgcn_interp_p2_f16: {
5920     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5921     SDValue Glue = SDValue(M0.getNode(), 1);
5922     SDValue Ops[] = {
5923       Op.getOperand(2), // Src0
5924       Op.getOperand(3), // Attrchan
5925       Op.getOperand(4), // Attr
5926       DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5927       Op.getOperand(1), // Src2
5928       DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5929       Op.getOperand(5), // high
5930       DAG.getConstant(0, DL, MVT::i1), // $clamp
5931       Glue
5932     };
5933     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5934   }
5935   case Intrinsic::amdgcn_sin:
5936     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5937 
5938   case Intrinsic::amdgcn_cos:
5939     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5940 
5941   case Intrinsic::amdgcn_mul_u24:
5942     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5943   case Intrinsic::amdgcn_mul_i24:
5944     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5945 
5946   case Intrinsic::amdgcn_log_clamp: {
5947     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5948       return SDValue();
5949 
5950     DiagnosticInfoUnsupported BadIntrin(
5951       MF.getFunction(), "intrinsic not supported on subtarget",
5952       DL.getDebugLoc());
5953       DAG.getContext()->diagnose(BadIntrin);
5954       return DAG.getUNDEF(VT);
5955   }
5956   case Intrinsic::amdgcn_ldexp:
5957     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5958                        Op.getOperand(1), Op.getOperand(2));
5959 
5960   case Intrinsic::amdgcn_fract:
5961     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5962 
5963   case Intrinsic::amdgcn_class:
5964     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5965                        Op.getOperand(1), Op.getOperand(2));
5966   case Intrinsic::amdgcn_div_fmas:
5967     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5968                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5969                        Op.getOperand(4));
5970 
5971   case Intrinsic::amdgcn_div_fixup:
5972     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5973                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5974 
5975   case Intrinsic::amdgcn_trig_preop:
5976     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5977                        Op.getOperand(1), Op.getOperand(2));
5978   case Intrinsic::amdgcn_div_scale: {
5979     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5980 
5981     // Translate to the operands expected by the machine instruction. The
5982     // first parameter must be the same as the first instruction.
5983     SDValue Numerator = Op.getOperand(1);
5984     SDValue Denominator = Op.getOperand(2);
5985 
5986     // Note this order is opposite of the machine instruction's operations,
5987     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5988     // intrinsic has the numerator as the first operand to match a normal
5989     // division operation.
5990 
5991     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5992 
5993     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5994                        Denominator, Numerator);
5995   }
5996   case Intrinsic::amdgcn_icmp: {
5997     // There is a Pat that handles this variant, so return it as-is.
5998     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5999         Op.getConstantOperandVal(2) == 0 &&
6000         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6001       return Op;
6002     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6003   }
6004   case Intrinsic::amdgcn_fcmp: {
6005     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6006   }
6007   case Intrinsic::amdgcn_fmed3:
6008     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6009                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6010   case Intrinsic::amdgcn_fdot2:
6011     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6012                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6013                        Op.getOperand(4));
6014   case Intrinsic::amdgcn_fmul_legacy:
6015     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6016                        Op.getOperand(1), Op.getOperand(2));
6017   case Intrinsic::amdgcn_sffbh:
6018     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6019   case Intrinsic::amdgcn_sbfe:
6020     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6021                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6022   case Intrinsic::amdgcn_ubfe:
6023     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6024                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6025   case Intrinsic::amdgcn_cvt_pkrtz:
6026   case Intrinsic::amdgcn_cvt_pknorm_i16:
6027   case Intrinsic::amdgcn_cvt_pknorm_u16:
6028   case Intrinsic::amdgcn_cvt_pk_i16:
6029   case Intrinsic::amdgcn_cvt_pk_u16: {
6030     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6031     EVT VT = Op.getValueType();
6032     unsigned Opcode;
6033 
6034     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6035       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6036     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6037       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6038     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6039       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6040     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6041       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6042     else
6043       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6044 
6045     if (isTypeLegal(VT))
6046       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6047 
6048     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6049                                Op.getOperand(1), Op.getOperand(2));
6050     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6051   }
6052   case Intrinsic::amdgcn_fmad_ftz:
6053     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6054                        Op.getOperand(2), Op.getOperand(3));
6055 
6056   case Intrinsic::amdgcn_if_break:
6057     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6058                                       Op->getOperand(1), Op->getOperand(2)), 0);
6059 
6060   case Intrinsic::amdgcn_groupstaticsize: {
6061     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6062     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6063       return Op;
6064 
6065     const Module *M = MF.getFunction().getParent();
6066     const GlobalValue *GV =
6067         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6068     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6069                                             SIInstrInfo::MO_ABS32_LO);
6070     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6071   }
6072   case Intrinsic::amdgcn_is_shared:
6073   case Intrinsic::amdgcn_is_private: {
6074     SDLoc SL(Op);
6075     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6076       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6077     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6078     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6079                                  Op.getOperand(1));
6080 
6081     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6082                                 DAG.getConstant(1, SL, MVT::i32));
6083     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6084   }
6085   default:
6086     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6087             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6088       return lowerImage(Op, ImageDimIntr, DAG);
6089 
6090     return Op;
6091   }
6092 }
6093 
6094 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6095                                                  SelectionDAG &DAG) const {
6096   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6097   SDLoc DL(Op);
6098 
6099   switch (IntrID) {
6100   case Intrinsic::amdgcn_ds_ordered_add:
6101   case Intrinsic::amdgcn_ds_ordered_swap: {
6102     MemSDNode *M = cast<MemSDNode>(Op);
6103     SDValue Chain = M->getOperand(0);
6104     SDValue M0 = M->getOperand(2);
6105     SDValue Value = M->getOperand(3);
6106     unsigned IndexOperand = M->getConstantOperandVal(7);
6107     unsigned WaveRelease = M->getConstantOperandVal(8);
6108     unsigned WaveDone = M->getConstantOperandVal(9);
6109     unsigned ShaderType;
6110     unsigned Instruction;
6111 
6112     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6113     IndexOperand &= ~0x3f;
6114     unsigned CountDw = 0;
6115 
6116     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6117       CountDw = (IndexOperand >> 24) & 0xf;
6118       IndexOperand &= ~(0xf << 24);
6119 
6120       if (CountDw < 1 || CountDw > 4) {
6121         report_fatal_error(
6122             "ds_ordered_count: dword count must be between 1 and 4");
6123       }
6124     }
6125 
6126     if (IndexOperand)
6127       report_fatal_error("ds_ordered_count: bad index operand");
6128 
6129     switch (IntrID) {
6130     case Intrinsic::amdgcn_ds_ordered_add:
6131       Instruction = 0;
6132       break;
6133     case Intrinsic::amdgcn_ds_ordered_swap:
6134       Instruction = 1;
6135       break;
6136     }
6137 
6138     if (WaveDone && !WaveRelease)
6139       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6140 
6141     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6142     case CallingConv::AMDGPU_CS:
6143     case CallingConv::AMDGPU_KERNEL:
6144       ShaderType = 0;
6145       break;
6146     case CallingConv::AMDGPU_PS:
6147       ShaderType = 1;
6148       break;
6149     case CallingConv::AMDGPU_VS:
6150       ShaderType = 2;
6151       break;
6152     case CallingConv::AMDGPU_GS:
6153       ShaderType = 3;
6154       break;
6155     default:
6156       report_fatal_error("ds_ordered_count unsupported for this calling conv");
6157     }
6158 
6159     unsigned Offset0 = OrderedCountIndex << 2;
6160     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6161                        (Instruction << 4);
6162 
6163     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6164       Offset1 |= (CountDw - 1) << 6;
6165 
6166     unsigned Offset = Offset0 | (Offset1 << 8);
6167 
6168     SDValue Ops[] = {
6169       Chain,
6170       Value,
6171       DAG.getTargetConstant(Offset, DL, MVT::i16),
6172       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6173     };
6174     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6175                                    M->getVTList(), Ops, M->getMemoryVT(),
6176                                    M->getMemOperand());
6177   }
6178   case Intrinsic::amdgcn_ds_fadd: {
6179     MemSDNode *M = cast<MemSDNode>(Op);
6180     unsigned Opc;
6181     switch (IntrID) {
6182     case Intrinsic::amdgcn_ds_fadd:
6183       Opc = ISD::ATOMIC_LOAD_FADD;
6184       break;
6185     }
6186 
6187     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6188                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6189                          M->getMemOperand());
6190   }
6191   case Intrinsic::amdgcn_atomic_inc:
6192   case Intrinsic::amdgcn_atomic_dec:
6193   case Intrinsic::amdgcn_ds_fmin:
6194   case Intrinsic::amdgcn_ds_fmax: {
6195     MemSDNode *M = cast<MemSDNode>(Op);
6196     unsigned Opc;
6197     switch (IntrID) {
6198     case Intrinsic::amdgcn_atomic_inc:
6199       Opc = AMDGPUISD::ATOMIC_INC;
6200       break;
6201     case Intrinsic::amdgcn_atomic_dec:
6202       Opc = AMDGPUISD::ATOMIC_DEC;
6203       break;
6204     case Intrinsic::amdgcn_ds_fmin:
6205       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6206       break;
6207     case Intrinsic::amdgcn_ds_fmax:
6208       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6209       break;
6210     default:
6211       llvm_unreachable("Unknown intrinsic!");
6212     }
6213     SDValue Ops[] = {
6214       M->getOperand(0), // Chain
6215       M->getOperand(2), // Ptr
6216       M->getOperand(3)  // Value
6217     };
6218 
6219     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6220                                    M->getMemoryVT(), M->getMemOperand());
6221   }
6222   case Intrinsic::amdgcn_buffer_load:
6223   case Intrinsic::amdgcn_buffer_load_format: {
6224     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6225     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6226     unsigned IdxEn = 1;
6227     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6228       IdxEn = Idx->getZExtValue() != 0;
6229     SDValue Ops[] = {
6230       Op.getOperand(0), // Chain
6231       Op.getOperand(2), // rsrc
6232       Op.getOperand(3), // vindex
6233       SDValue(),        // voffset -- will be set by setBufferOffsets
6234       SDValue(),        // soffset -- will be set by setBufferOffsets
6235       SDValue(),        // offset -- will be set by setBufferOffsets
6236       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6237       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6238     };
6239 
6240     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6241     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6242         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6243 
6244     EVT VT = Op.getValueType();
6245     EVT IntVT = VT.changeTypeToInteger();
6246     auto *M = cast<MemSDNode>(Op);
6247     EVT LoadVT = Op.getValueType();
6248 
6249     if (LoadVT.getScalarType() == MVT::f16)
6250       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6251                                  M, DAG, Ops);
6252 
6253     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6254     if (LoadVT.getScalarType() == MVT::i8 ||
6255         LoadVT.getScalarType() == MVT::i16)
6256       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6257 
6258     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6259                                M->getMemOperand(), DAG);
6260   }
6261   case Intrinsic::amdgcn_raw_buffer_load:
6262   case Intrinsic::amdgcn_raw_buffer_load_format: {
6263     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6264 
6265     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6266     SDValue Ops[] = {
6267       Op.getOperand(0), // Chain
6268       Op.getOperand(2), // rsrc
6269       DAG.getConstant(0, DL, MVT::i32), // vindex
6270       Offsets.first,    // voffset
6271       Op.getOperand(4), // soffset
6272       Offsets.second,   // offset
6273       Op.getOperand(5), // cachepolicy
6274       DAG.getConstant(0, DL, MVT::i1), // idxen
6275     };
6276 
6277     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6278   }
6279   case Intrinsic::amdgcn_struct_buffer_load:
6280   case Intrinsic::amdgcn_struct_buffer_load_format: {
6281     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6282 
6283     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6284     SDValue Ops[] = {
6285       Op.getOperand(0), // Chain
6286       Op.getOperand(2), // rsrc
6287       Op.getOperand(3), // vindex
6288       Offsets.first,    // voffset
6289       Op.getOperand(5), // soffset
6290       Offsets.second,   // offset
6291       Op.getOperand(6), // cachepolicy
6292       DAG.getConstant(1, DL, MVT::i1), // idxen
6293     };
6294 
6295     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6296   }
6297   case Intrinsic::amdgcn_tbuffer_load: {
6298     MemSDNode *M = cast<MemSDNode>(Op);
6299     EVT LoadVT = Op.getValueType();
6300 
6301     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6302     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6303     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6304     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6305     unsigned IdxEn = 1;
6306     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6307       IdxEn = Idx->getZExtValue() != 0;
6308     SDValue Ops[] = {
6309       Op.getOperand(0),  // Chain
6310       Op.getOperand(2),  // rsrc
6311       Op.getOperand(3),  // vindex
6312       Op.getOperand(4),  // voffset
6313       Op.getOperand(5),  // soffset
6314       Op.getOperand(6),  // offset
6315       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6316       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6317       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6318     };
6319 
6320     if (LoadVT.getScalarType() == MVT::f16)
6321       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6322                                  M, DAG, Ops);
6323     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6324                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6325                                DAG);
6326   }
6327   case Intrinsic::amdgcn_raw_tbuffer_load: {
6328     MemSDNode *M = cast<MemSDNode>(Op);
6329     EVT LoadVT = Op.getValueType();
6330     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6331 
6332     SDValue Ops[] = {
6333       Op.getOperand(0),  // Chain
6334       Op.getOperand(2),  // rsrc
6335       DAG.getConstant(0, DL, MVT::i32), // vindex
6336       Offsets.first,     // voffset
6337       Op.getOperand(4),  // soffset
6338       Offsets.second,    // offset
6339       Op.getOperand(5),  // format
6340       Op.getOperand(6),  // cachepolicy
6341       DAG.getConstant(0, DL, MVT::i1), // idxen
6342     };
6343 
6344     if (LoadVT.getScalarType() == MVT::f16)
6345       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6346                                  M, DAG, Ops);
6347     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6348                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6349                                DAG);
6350   }
6351   case Intrinsic::amdgcn_struct_tbuffer_load: {
6352     MemSDNode *M = cast<MemSDNode>(Op);
6353     EVT LoadVT = Op.getValueType();
6354     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6355 
6356     SDValue Ops[] = {
6357       Op.getOperand(0),  // Chain
6358       Op.getOperand(2),  // rsrc
6359       Op.getOperand(3),  // vindex
6360       Offsets.first,     // voffset
6361       Op.getOperand(5),  // soffset
6362       Offsets.second,    // offset
6363       Op.getOperand(6),  // format
6364       Op.getOperand(7),  // cachepolicy
6365       DAG.getConstant(1, DL, MVT::i1), // idxen
6366     };
6367 
6368     if (LoadVT.getScalarType() == MVT::f16)
6369       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6370                                  M, DAG, Ops);
6371     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6372                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6373                                DAG);
6374   }
6375   case Intrinsic::amdgcn_buffer_atomic_swap:
6376   case Intrinsic::amdgcn_buffer_atomic_add:
6377   case Intrinsic::amdgcn_buffer_atomic_sub:
6378   case Intrinsic::amdgcn_buffer_atomic_smin:
6379   case Intrinsic::amdgcn_buffer_atomic_umin:
6380   case Intrinsic::amdgcn_buffer_atomic_smax:
6381   case Intrinsic::amdgcn_buffer_atomic_umax:
6382   case Intrinsic::amdgcn_buffer_atomic_and:
6383   case Intrinsic::amdgcn_buffer_atomic_or:
6384   case Intrinsic::amdgcn_buffer_atomic_xor: {
6385     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6386     unsigned IdxEn = 1;
6387     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6388       IdxEn = Idx->getZExtValue() != 0;
6389     SDValue Ops[] = {
6390       Op.getOperand(0), // Chain
6391       Op.getOperand(2), // vdata
6392       Op.getOperand(3), // rsrc
6393       Op.getOperand(4), // vindex
6394       SDValue(),        // voffset -- will be set by setBufferOffsets
6395       SDValue(),        // soffset -- will be set by setBufferOffsets
6396       SDValue(),        // offset -- will be set by setBufferOffsets
6397       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6398       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6399     };
6400     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6401     EVT VT = Op.getValueType();
6402 
6403     auto *M = cast<MemSDNode>(Op);
6404     unsigned Opcode = 0;
6405 
6406     switch (IntrID) {
6407     case Intrinsic::amdgcn_buffer_atomic_swap:
6408       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6409       break;
6410     case Intrinsic::amdgcn_buffer_atomic_add:
6411       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6412       break;
6413     case Intrinsic::amdgcn_buffer_atomic_sub:
6414       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6415       break;
6416     case Intrinsic::amdgcn_buffer_atomic_smin:
6417       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6418       break;
6419     case Intrinsic::amdgcn_buffer_atomic_umin:
6420       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6421       break;
6422     case Intrinsic::amdgcn_buffer_atomic_smax:
6423       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6424       break;
6425     case Intrinsic::amdgcn_buffer_atomic_umax:
6426       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6427       break;
6428     case Intrinsic::amdgcn_buffer_atomic_and:
6429       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6430       break;
6431     case Intrinsic::amdgcn_buffer_atomic_or:
6432       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6433       break;
6434     case Intrinsic::amdgcn_buffer_atomic_xor:
6435       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6436       break;
6437     default:
6438       llvm_unreachable("unhandled atomic opcode");
6439     }
6440 
6441     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6442                                    M->getMemOperand());
6443   }
6444   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6445   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6446   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6447   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6448   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6449   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6450   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6451   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6452   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6453   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6454   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6455   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6456     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6457     SDValue Ops[] = {
6458       Op.getOperand(0), // Chain
6459       Op.getOperand(2), // vdata
6460       Op.getOperand(3), // rsrc
6461       DAG.getConstant(0, DL, MVT::i32), // vindex
6462       Offsets.first,    // voffset
6463       Op.getOperand(5), // soffset
6464       Offsets.second,   // offset
6465       Op.getOperand(6), // cachepolicy
6466       DAG.getConstant(0, DL, MVT::i1), // idxen
6467     };
6468     EVT VT = Op.getValueType();
6469 
6470     auto *M = cast<MemSDNode>(Op);
6471     unsigned Opcode = 0;
6472 
6473     switch (IntrID) {
6474     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6475       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6476       break;
6477     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6478       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6479       break;
6480     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6481       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6482       break;
6483     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6484       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6485       break;
6486     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6487       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6488       break;
6489     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6490       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6491       break;
6492     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6493       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6494       break;
6495     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6496       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6497       break;
6498     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6499       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6500       break;
6501     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6502       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6503       break;
6504     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6505       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6506       break;
6507     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6508       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6509       break;
6510     default:
6511       llvm_unreachable("unhandled atomic opcode");
6512     }
6513 
6514     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6515                                    M->getMemOperand());
6516   }
6517   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6518   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6519   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6520   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6521   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6522   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6523   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6524   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6525   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6526   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6527   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6528   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6529     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6530     SDValue Ops[] = {
6531       Op.getOperand(0), // Chain
6532       Op.getOperand(2), // vdata
6533       Op.getOperand(3), // rsrc
6534       Op.getOperand(4), // vindex
6535       Offsets.first,    // voffset
6536       Op.getOperand(6), // soffset
6537       Offsets.second,   // offset
6538       Op.getOperand(7), // cachepolicy
6539       DAG.getConstant(1, DL, MVT::i1), // idxen
6540     };
6541     EVT VT = Op.getValueType();
6542 
6543     auto *M = cast<MemSDNode>(Op);
6544     unsigned Opcode = 0;
6545 
6546     switch (IntrID) {
6547     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6548       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6549       break;
6550     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6551       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6552       break;
6553     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6554       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6555       break;
6556     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6557       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6558       break;
6559     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6560       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6561       break;
6562     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6563       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6564       break;
6565     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6566       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6567       break;
6568     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6569       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6570       break;
6571     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6572       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6573       break;
6574     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6575       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6576       break;
6577     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6578       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6579       break;
6580     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6581       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6582       break;
6583     default:
6584       llvm_unreachable("unhandled atomic opcode");
6585     }
6586 
6587     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6588                                    M->getMemOperand());
6589   }
6590   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6591     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6592     unsigned IdxEn = 1;
6593     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6594       IdxEn = Idx->getZExtValue() != 0;
6595     SDValue Ops[] = {
6596       Op.getOperand(0), // Chain
6597       Op.getOperand(2), // src
6598       Op.getOperand(3), // cmp
6599       Op.getOperand(4), // rsrc
6600       Op.getOperand(5), // vindex
6601       SDValue(),        // voffset -- will be set by setBufferOffsets
6602       SDValue(),        // soffset -- will be set by setBufferOffsets
6603       SDValue(),        // offset -- will be set by setBufferOffsets
6604       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6605       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6606     };
6607     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6608     EVT VT = Op.getValueType();
6609     auto *M = cast<MemSDNode>(Op);
6610 
6611     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6612                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6613   }
6614   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6615     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6616     SDValue Ops[] = {
6617       Op.getOperand(0), // Chain
6618       Op.getOperand(2), // src
6619       Op.getOperand(3), // cmp
6620       Op.getOperand(4), // rsrc
6621       DAG.getConstant(0, DL, MVT::i32), // vindex
6622       Offsets.first,    // voffset
6623       Op.getOperand(6), // soffset
6624       Offsets.second,   // offset
6625       Op.getOperand(7), // cachepolicy
6626       DAG.getConstant(0, DL, MVT::i1), // idxen
6627     };
6628     EVT VT = Op.getValueType();
6629     auto *M = cast<MemSDNode>(Op);
6630 
6631     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6632                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6633   }
6634   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6635     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6636     SDValue Ops[] = {
6637       Op.getOperand(0), // Chain
6638       Op.getOperand(2), // src
6639       Op.getOperand(3), // cmp
6640       Op.getOperand(4), // rsrc
6641       Op.getOperand(5), // vindex
6642       Offsets.first,    // voffset
6643       Op.getOperand(7), // soffset
6644       Offsets.second,   // offset
6645       Op.getOperand(8), // cachepolicy
6646       DAG.getConstant(1, DL, MVT::i1), // idxen
6647     };
6648     EVT VT = Op.getValueType();
6649     auto *M = cast<MemSDNode>(Op);
6650 
6651     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6652                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6653   }
6654 
6655   default:
6656     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6657             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6658       return lowerImage(Op, ImageDimIntr, DAG);
6659 
6660     return SDValue();
6661   }
6662 }
6663 
6664 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6665 // dwordx4 if on SI.
6666 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6667                                               SDVTList VTList,
6668                                               ArrayRef<SDValue> Ops, EVT MemVT,
6669                                               MachineMemOperand *MMO,
6670                                               SelectionDAG &DAG) const {
6671   EVT VT = VTList.VTs[0];
6672   EVT WidenedVT = VT;
6673   EVT WidenedMemVT = MemVT;
6674   if (!Subtarget->hasDwordx3LoadStores() &&
6675       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6676     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6677                                  WidenedVT.getVectorElementType(), 4);
6678     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6679                                     WidenedMemVT.getVectorElementType(), 4);
6680     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6681   }
6682 
6683   assert(VTList.NumVTs == 2);
6684   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6685 
6686   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6687                                        WidenedMemVT, MMO);
6688   if (WidenedVT != VT) {
6689     auto Extract = DAG.getNode(
6690         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6691         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6692     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6693   }
6694   return NewOp;
6695 }
6696 
6697 SDValue SITargetLowering::handleD16VData(SDValue VData,
6698                                          SelectionDAG &DAG) const {
6699   EVT StoreVT = VData.getValueType();
6700 
6701   // No change for f16 and legal vector D16 types.
6702   if (!StoreVT.isVector())
6703     return VData;
6704 
6705   SDLoc DL(VData);
6706   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6707 
6708   if (Subtarget->hasUnpackedD16VMem()) {
6709     // We need to unpack the packed data to store.
6710     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6711     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6712 
6713     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6714                                         StoreVT.getVectorNumElements());
6715     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6716     return DAG.UnrollVectorOp(ZExt.getNode());
6717   }
6718 
6719   assert(isTypeLegal(StoreVT));
6720   return VData;
6721 }
6722 
6723 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6724                                               SelectionDAG &DAG) const {
6725   SDLoc DL(Op);
6726   SDValue Chain = Op.getOperand(0);
6727   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6728   MachineFunction &MF = DAG.getMachineFunction();
6729 
6730   switch (IntrinsicID) {
6731   case Intrinsic::amdgcn_exp: {
6732     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6733     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6734     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6735     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6736 
6737     const SDValue Ops[] = {
6738       Chain,
6739       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6740       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6741       Op.getOperand(4), // src0
6742       Op.getOperand(5), // src1
6743       Op.getOperand(6), // src2
6744       Op.getOperand(7), // src3
6745       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6746       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6747     };
6748 
6749     unsigned Opc = Done->isNullValue() ?
6750       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6751     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6752   }
6753   case Intrinsic::amdgcn_exp_compr: {
6754     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6755     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6756     SDValue Src0 = Op.getOperand(4);
6757     SDValue Src1 = Op.getOperand(5);
6758     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6759     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6760 
6761     SDValue Undef = DAG.getUNDEF(MVT::f32);
6762     const SDValue Ops[] = {
6763       Chain,
6764       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6765       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6766       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6767       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6768       Undef, // src2
6769       Undef, // src3
6770       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6771       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6772     };
6773 
6774     unsigned Opc = Done->isNullValue() ?
6775       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6776     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6777   }
6778   case Intrinsic::amdgcn_s_barrier: {
6779     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6780       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6781       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6782       if (WGSize <= ST.getWavefrontSize())
6783         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6784                                           Op.getOperand(0)), 0);
6785     }
6786     return SDValue();
6787   };
6788   case Intrinsic::amdgcn_tbuffer_store: {
6789     SDValue VData = Op.getOperand(2);
6790     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6791     if (IsD16)
6792       VData = handleD16VData(VData, DAG);
6793     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6794     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6795     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6796     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6797     unsigned IdxEn = 1;
6798     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6799       IdxEn = Idx->getZExtValue() != 0;
6800     SDValue Ops[] = {
6801       Chain,
6802       VData,             // vdata
6803       Op.getOperand(3),  // rsrc
6804       Op.getOperand(4),  // vindex
6805       Op.getOperand(5),  // voffset
6806       Op.getOperand(6),  // soffset
6807       Op.getOperand(7),  // offset
6808       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6809       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6810       DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6811     };
6812     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6813                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6814     MemSDNode *M = cast<MemSDNode>(Op);
6815     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6816                                    M->getMemoryVT(), M->getMemOperand());
6817   }
6818 
6819   case Intrinsic::amdgcn_struct_tbuffer_store: {
6820     SDValue VData = Op.getOperand(2);
6821     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6822     if (IsD16)
6823       VData = handleD16VData(VData, DAG);
6824     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6825     SDValue Ops[] = {
6826       Chain,
6827       VData,             // vdata
6828       Op.getOperand(3),  // rsrc
6829       Op.getOperand(4),  // vindex
6830       Offsets.first,     // voffset
6831       Op.getOperand(6),  // soffset
6832       Offsets.second,    // offset
6833       Op.getOperand(7),  // format
6834       Op.getOperand(8),  // cachepolicy
6835       DAG.getConstant(1, DL, MVT::i1), // idexen
6836     };
6837     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6838                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6839     MemSDNode *M = cast<MemSDNode>(Op);
6840     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6841                                    M->getMemoryVT(), M->getMemOperand());
6842   }
6843 
6844   case Intrinsic::amdgcn_raw_tbuffer_store: {
6845     SDValue VData = Op.getOperand(2);
6846     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6847     if (IsD16)
6848       VData = handleD16VData(VData, DAG);
6849     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6850     SDValue Ops[] = {
6851       Chain,
6852       VData,             // vdata
6853       Op.getOperand(3),  // rsrc
6854       DAG.getConstant(0, DL, MVT::i32), // vindex
6855       Offsets.first,     // voffset
6856       Op.getOperand(5),  // soffset
6857       Offsets.second,    // offset
6858       Op.getOperand(6),  // format
6859       Op.getOperand(7),  // cachepolicy
6860       DAG.getConstant(0, DL, MVT::i1), // idexen
6861     };
6862     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6863                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6864     MemSDNode *M = cast<MemSDNode>(Op);
6865     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6866                                    M->getMemoryVT(), M->getMemOperand());
6867   }
6868 
6869   case Intrinsic::amdgcn_buffer_store:
6870   case Intrinsic::amdgcn_buffer_store_format: {
6871     SDValue VData = Op.getOperand(2);
6872     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6873     if (IsD16)
6874       VData = handleD16VData(VData, DAG);
6875     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6876     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6877     unsigned IdxEn = 1;
6878     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6879       IdxEn = Idx->getZExtValue() != 0;
6880     SDValue Ops[] = {
6881       Chain,
6882       VData,
6883       Op.getOperand(3), // rsrc
6884       Op.getOperand(4), // vindex
6885       SDValue(), // voffset -- will be set by setBufferOffsets
6886       SDValue(), // soffset -- will be set by setBufferOffsets
6887       SDValue(), // offset -- will be set by setBufferOffsets
6888       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6889       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6890     };
6891     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6892     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6893                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6894     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6895     MemSDNode *M = cast<MemSDNode>(Op);
6896 
6897     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6898     EVT VDataType = VData.getValueType().getScalarType();
6899     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6900       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6901 
6902     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6903                                    M->getMemoryVT(), M->getMemOperand());
6904   }
6905 
6906   case Intrinsic::amdgcn_raw_buffer_store:
6907   case Intrinsic::amdgcn_raw_buffer_store_format: {
6908     const bool IsFormat =
6909         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6910 
6911     SDValue VData = Op.getOperand(2);
6912     EVT VDataVT = VData.getValueType();
6913     EVT EltType = VDataVT.getScalarType();
6914     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6915     if (IsD16)
6916       VData = handleD16VData(VData, DAG);
6917 
6918     if (!isTypeLegal(VDataVT)) {
6919       VData =
6920           DAG.getNode(ISD::BITCAST, DL,
6921                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6922     }
6923 
6924     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6925     SDValue Ops[] = {
6926       Chain,
6927       VData,
6928       Op.getOperand(3), // rsrc
6929       DAG.getConstant(0, DL, MVT::i32), // vindex
6930       Offsets.first,    // voffset
6931       Op.getOperand(5), // soffset
6932       Offsets.second,   // offset
6933       Op.getOperand(6), // cachepolicy
6934       DAG.getConstant(0, DL, MVT::i1), // idxen
6935     };
6936     unsigned Opc =
6937         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6938     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6939     MemSDNode *M = cast<MemSDNode>(Op);
6940 
6941     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6942     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6943       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6944 
6945     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6946                                    M->getMemoryVT(), M->getMemOperand());
6947   }
6948 
6949   case Intrinsic::amdgcn_struct_buffer_store:
6950   case Intrinsic::amdgcn_struct_buffer_store_format: {
6951     const bool IsFormat =
6952         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
6953 
6954     SDValue VData = Op.getOperand(2);
6955     EVT VDataVT = VData.getValueType();
6956     EVT EltType = VDataVT.getScalarType();
6957     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6958 
6959     if (IsD16)
6960       VData = handleD16VData(VData, DAG);
6961 
6962     if (!isTypeLegal(VDataVT)) {
6963       VData =
6964           DAG.getNode(ISD::BITCAST, DL,
6965                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6966     }
6967 
6968     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6969     SDValue Ops[] = {
6970       Chain,
6971       VData,
6972       Op.getOperand(3), // rsrc
6973       Op.getOperand(4), // vindex
6974       Offsets.first,    // voffset
6975       Op.getOperand(6), // soffset
6976       Offsets.second,   // offset
6977       Op.getOperand(7), // cachepolicy
6978       DAG.getConstant(1, DL, MVT::i1), // idxen
6979     };
6980     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6981                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6982     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6983     MemSDNode *M = cast<MemSDNode>(Op);
6984 
6985     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6986     EVT VDataType = VData.getValueType().getScalarType();
6987     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6988       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6989 
6990     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6991                                    M->getMemoryVT(), M->getMemOperand());
6992   }
6993 
6994   case Intrinsic::amdgcn_buffer_atomic_fadd: {
6995     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6996     unsigned IdxEn = 1;
6997     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6998       IdxEn = Idx->getZExtValue() != 0;
6999     SDValue Ops[] = {
7000       Chain,
7001       Op.getOperand(2), // vdata
7002       Op.getOperand(3), // rsrc
7003       Op.getOperand(4), // vindex
7004       SDValue(),        // voffset -- will be set by setBufferOffsets
7005       SDValue(),        // soffset -- will be set by setBufferOffsets
7006       SDValue(),        // offset -- will be set by setBufferOffsets
7007       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7008       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
7009     };
7010     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7011     EVT VT = Op.getOperand(2).getValueType();
7012 
7013     auto *M = cast<MemSDNode>(Op);
7014     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7015                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7016 
7017     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7018                                    M->getMemOperand());
7019   }
7020 
7021   case Intrinsic::amdgcn_global_atomic_fadd: {
7022     SDValue Ops[] = {
7023       Chain,
7024       Op.getOperand(2), // ptr
7025       Op.getOperand(3)  // vdata
7026     };
7027     EVT VT = Op.getOperand(3).getValueType();
7028 
7029     auto *M = cast<MemSDNode>(Op);
7030     unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD
7031                                     : AMDGPUISD::ATOMIC_FADD;
7032 
7033     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7034                                    M->getMemOperand());
7035   }
7036 
7037   case Intrinsic::amdgcn_end_cf:
7038     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7039                                       Op->getOperand(2), Chain), 0);
7040 
7041   default: {
7042     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7043             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7044       return lowerImage(Op, ImageDimIntr, DAG);
7045 
7046     return Op;
7047   }
7048   }
7049 }
7050 
7051 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7052 // offset (the offset that is included in bounds checking and swizzling, to be
7053 // split between the instruction's voffset and immoffset fields) and soffset
7054 // (the offset that is excluded from bounds checking and swizzling, to go in
7055 // the instruction's soffset field).  This function takes the first kind of
7056 // offset and figures out how to split it between voffset and immoffset.
7057 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7058     SDValue Offset, SelectionDAG &DAG) const {
7059   SDLoc DL(Offset);
7060   const unsigned MaxImm = 4095;
7061   SDValue N0 = Offset;
7062   ConstantSDNode *C1 = nullptr;
7063 
7064   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7065     N0 = SDValue();
7066   else if (DAG.isBaseWithConstantOffset(N0)) {
7067     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7068     N0 = N0.getOperand(0);
7069   }
7070 
7071   if (C1) {
7072     unsigned ImmOffset = C1->getZExtValue();
7073     // If the immediate value is too big for the immoffset field, put the value
7074     // and -4096 into the immoffset field so that the value that is copied/added
7075     // for the voffset field is a multiple of 4096, and it stands more chance
7076     // of being CSEd with the copy/add for another similar load/store.
7077     // However, do not do that rounding down to a multiple of 4096 if that is a
7078     // negative number, as it appears to be illegal to have a negative offset
7079     // in the vgpr, even if adding the immediate offset makes it positive.
7080     unsigned Overflow = ImmOffset & ~MaxImm;
7081     ImmOffset -= Overflow;
7082     if ((int32_t)Overflow < 0) {
7083       Overflow += ImmOffset;
7084       ImmOffset = 0;
7085     }
7086     C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
7087     if (Overflow) {
7088       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7089       if (!N0)
7090         N0 = OverflowVal;
7091       else {
7092         SDValue Ops[] = { N0, OverflowVal };
7093         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7094       }
7095     }
7096   }
7097   if (!N0)
7098     N0 = DAG.getConstant(0, DL, MVT::i32);
7099   if (!C1)
7100     C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
7101   return {N0, SDValue(C1, 0)};
7102 }
7103 
7104 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7105 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7106 // pointed to by Offsets.
7107 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7108                                         SelectionDAG &DAG, SDValue *Offsets,
7109                                         unsigned Align) const {
7110   SDLoc DL(CombinedOffset);
7111   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7112     uint32_t Imm = C->getZExtValue();
7113     uint32_t SOffset, ImmOffset;
7114     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7115       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7116       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7117       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
7118       return;
7119     }
7120   }
7121   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7122     SDValue N0 = CombinedOffset.getOperand(0);
7123     SDValue N1 = CombinedOffset.getOperand(1);
7124     uint32_t SOffset, ImmOffset;
7125     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7126     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7127                                                 Subtarget, Align)) {
7128       Offsets[0] = N0;
7129       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7130       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
7131       return;
7132     }
7133   }
7134   Offsets[0] = CombinedOffset;
7135   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7136   Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
7137 }
7138 
7139 // Handle 8 bit and 16 bit buffer loads
7140 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7141                                                      EVT LoadVT, SDLoc DL,
7142                                                      ArrayRef<SDValue> Ops,
7143                                                      MemSDNode *M) const {
7144   EVT IntVT = LoadVT.changeTypeToInteger();
7145   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7146          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7147 
7148   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7149   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7150                                                Ops, IntVT,
7151                                                M->getMemOperand());
7152   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7153   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7154 
7155   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7156 }
7157 
7158 // Handle 8 bit and 16 bit buffer stores
7159 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7160                                                       EVT VDataType, SDLoc DL,
7161                                                       SDValue Ops[],
7162                                                       MemSDNode *M) const {
7163   if (VDataType == MVT::f16)
7164     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7165 
7166   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7167   Ops[1] = BufferStoreExt;
7168   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7169                                  AMDGPUISD::BUFFER_STORE_SHORT;
7170   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7171   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7172                                      M->getMemOperand());
7173 }
7174 
7175 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7176                                  ISD::LoadExtType ExtType, SDValue Op,
7177                                  const SDLoc &SL, EVT VT) {
7178   if (VT.bitsLT(Op.getValueType()))
7179     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7180 
7181   switch (ExtType) {
7182   case ISD::SEXTLOAD:
7183     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7184   case ISD::ZEXTLOAD:
7185     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7186   case ISD::EXTLOAD:
7187     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7188   case ISD::NON_EXTLOAD:
7189     return Op;
7190   }
7191 
7192   llvm_unreachable("invalid ext type");
7193 }
7194 
7195 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7196   SelectionDAG &DAG = DCI.DAG;
7197   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7198     return SDValue();
7199 
7200   // FIXME: Constant loads should all be marked invariant.
7201   unsigned AS = Ld->getAddressSpace();
7202   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7203       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7204       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7205     return SDValue();
7206 
7207   // Don't do this early, since it may interfere with adjacent load merging for
7208   // illegal types. We can avoid losing alignment information for exotic types
7209   // pre-legalize.
7210   EVT MemVT = Ld->getMemoryVT();
7211   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7212       MemVT.getSizeInBits() >= 32)
7213     return SDValue();
7214 
7215   SDLoc SL(Ld);
7216 
7217   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7218          "unexpected vector extload");
7219 
7220   // TODO: Drop only high part of range.
7221   SDValue Ptr = Ld->getBasePtr();
7222   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7223                                 MVT::i32, SL, Ld->getChain(), Ptr,
7224                                 Ld->getOffset(),
7225                                 Ld->getPointerInfo(), MVT::i32,
7226                                 Ld->getAlignment(),
7227                                 Ld->getMemOperand()->getFlags(),
7228                                 Ld->getAAInfo(),
7229                                 nullptr); // Drop ranges
7230 
7231   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7232   if (MemVT.isFloatingPoint()) {
7233     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7234            "unexpected fp extload");
7235     TruncVT = MemVT.changeTypeToInteger();
7236   }
7237 
7238   SDValue Cvt = NewLoad;
7239   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7240     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7241                       DAG.getValueType(TruncVT));
7242   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7243              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7244     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7245   } else {
7246     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7247   }
7248 
7249   EVT VT = Ld->getValueType(0);
7250   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7251 
7252   DCI.AddToWorklist(Cvt.getNode());
7253 
7254   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7255   // the appropriate extension from the 32-bit load.
7256   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7257   DCI.AddToWorklist(Cvt.getNode());
7258 
7259   // Handle conversion back to floating point if necessary.
7260   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7261 
7262   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7263 }
7264 
7265 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7266   SDLoc DL(Op);
7267   LoadSDNode *Load = cast<LoadSDNode>(Op);
7268   ISD::LoadExtType ExtType = Load->getExtensionType();
7269   EVT MemVT = Load->getMemoryVT();
7270 
7271   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7272     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7273       return SDValue();
7274 
7275     // FIXME: Copied from PPC
7276     // First, load into 32 bits, then truncate to 1 bit.
7277 
7278     SDValue Chain = Load->getChain();
7279     SDValue BasePtr = Load->getBasePtr();
7280     MachineMemOperand *MMO = Load->getMemOperand();
7281 
7282     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7283 
7284     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7285                                    BasePtr, RealMemVT, MMO);
7286 
7287     if (!MemVT.isVector()) {
7288       SDValue Ops[] = {
7289         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7290         NewLD.getValue(1)
7291       };
7292 
7293       return DAG.getMergeValues(Ops, DL);
7294     }
7295 
7296     SmallVector<SDValue, 3> Elts;
7297     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7298       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7299                                 DAG.getConstant(I, DL, MVT::i32));
7300 
7301       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7302     }
7303 
7304     SDValue Ops[] = {
7305       DAG.getBuildVector(MemVT, DL, Elts),
7306       NewLD.getValue(1)
7307     };
7308 
7309     return DAG.getMergeValues(Ops, DL);
7310   }
7311 
7312   if (!MemVT.isVector())
7313     return SDValue();
7314 
7315   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7316          "Custom lowering for non-i32 vectors hasn't been implemented.");
7317 
7318   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7319                           *Load->getMemOperand())) {
7320     SDValue Ops[2];
7321     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7322     return DAG.getMergeValues(Ops, DL);
7323   }
7324 
7325   unsigned Alignment = Load->getAlignment();
7326   unsigned AS = Load->getAddressSpace();
7327   if (Subtarget->hasLDSMisalignedBug() &&
7328       AS == AMDGPUAS::FLAT_ADDRESS &&
7329       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7330     return SplitVectorLoad(Op, DAG);
7331   }
7332 
7333   MachineFunction &MF = DAG.getMachineFunction();
7334   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7335   // If there is a possibilty that flat instruction access scratch memory
7336   // then we need to use the same legalization rules we use for private.
7337   if (AS == AMDGPUAS::FLAT_ADDRESS)
7338     AS = MFI->hasFlatScratchInit() ?
7339          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7340 
7341   unsigned NumElements = MemVT.getVectorNumElements();
7342 
7343   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7344       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7345     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7346       if (MemVT.isPow2VectorType())
7347         return SDValue();
7348       if (NumElements == 3)
7349         return WidenVectorLoad(Op, DAG);
7350       return SplitVectorLoad(Op, DAG);
7351     }
7352     // Non-uniform loads will be selected to MUBUF instructions, so they
7353     // have the same legalization requirements as global and private
7354     // loads.
7355     //
7356   }
7357 
7358   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7359       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7360       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7361     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7362         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7363         Alignment >= 4 && NumElements < 32) {
7364       if (MemVT.isPow2VectorType())
7365         return SDValue();
7366       if (NumElements == 3)
7367         return WidenVectorLoad(Op, DAG);
7368       return SplitVectorLoad(Op, DAG);
7369     }
7370     // Non-uniform loads will be selected to MUBUF instructions, so they
7371     // have the same legalization requirements as global and private
7372     // loads.
7373     //
7374   }
7375   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7376       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7377       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7378       AS == AMDGPUAS::FLAT_ADDRESS) {
7379     if (NumElements > 4)
7380       return SplitVectorLoad(Op, DAG);
7381     // v3 loads not supported on SI.
7382     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7383       return WidenVectorLoad(Op, DAG);
7384     // v3 and v4 loads are supported for private and global memory.
7385     return SDValue();
7386   }
7387   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7388     // Depending on the setting of the private_element_size field in the
7389     // resource descriptor, we can only make private accesses up to a certain
7390     // size.
7391     switch (Subtarget->getMaxPrivateElementSize()) {
7392     case 4:
7393       return scalarizeVectorLoad(Load, DAG);
7394     case 8:
7395       if (NumElements > 2)
7396         return SplitVectorLoad(Op, DAG);
7397       return SDValue();
7398     case 16:
7399       // Same as global/flat
7400       if (NumElements > 4)
7401         return SplitVectorLoad(Op, DAG);
7402       // v3 loads not supported on SI.
7403       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7404         return WidenVectorLoad(Op, DAG);
7405       return SDValue();
7406     default:
7407       llvm_unreachable("unsupported private_element_size");
7408     }
7409   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7410     // Use ds_read_b128 if possible.
7411     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7412         MemVT.getStoreSize() == 16)
7413       return SDValue();
7414 
7415     if (NumElements > 2)
7416       return SplitVectorLoad(Op, DAG);
7417 
7418     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7419     // address is negative, then the instruction is incorrectly treated as
7420     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7421     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7422     // load later in the SILoadStoreOptimizer.
7423     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7424         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7425         Load->getAlignment() < 8) {
7426       return SplitVectorLoad(Op, DAG);
7427     }
7428   }
7429   return SDValue();
7430 }
7431 
7432 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7433   EVT VT = Op.getValueType();
7434   assert(VT.getSizeInBits() == 64);
7435 
7436   SDLoc DL(Op);
7437   SDValue Cond = Op.getOperand(0);
7438 
7439   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7440   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7441 
7442   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7443   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7444 
7445   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7446   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7447 
7448   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7449 
7450   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7451   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7452 
7453   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7454 
7455   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7456   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7457 }
7458 
7459 // Catch division cases where we can use shortcuts with rcp and rsq
7460 // instructions.
7461 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7462                                               SelectionDAG &DAG) const {
7463   SDLoc SL(Op);
7464   SDValue LHS = Op.getOperand(0);
7465   SDValue RHS = Op.getOperand(1);
7466   EVT VT = Op.getValueType();
7467   const SDNodeFlags Flags = Op->getFlags();
7468   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7469 
7470   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7471     return SDValue();
7472 
7473   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7474     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7475       if (CLHS->isExactlyValue(1.0)) {
7476         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7477         // the CI documentation has a worst case error of 1 ulp.
7478         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7479         // use it as long as we aren't trying to use denormals.
7480         //
7481         // v_rcp_f16 and v_rsq_f16 DO support denormals.
7482 
7483         // 1.0 / sqrt(x) -> rsq(x)
7484 
7485         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7486         // error seems really high at 2^29 ULP.
7487         if (RHS.getOpcode() == ISD::FSQRT)
7488           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7489 
7490         // 1.0 / x -> rcp(x)
7491         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7492       }
7493 
7494       // Same as for 1.0, but expand the sign out of the constant.
7495       if (CLHS->isExactlyValue(-1.0)) {
7496         // -1.0 / x -> rcp (fneg x)
7497         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7498         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7499       }
7500     }
7501   }
7502 
7503   if (Unsafe) {
7504     // Turn into multiply by the reciprocal.
7505     // x / y -> x * (1.0 / y)
7506     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7507     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7508   }
7509 
7510   return SDValue();
7511 }
7512 
7513 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7514                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7515   if (GlueChain->getNumValues() <= 1) {
7516     return DAG.getNode(Opcode, SL, VT, A, B);
7517   }
7518 
7519   assert(GlueChain->getNumValues() == 3);
7520 
7521   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7522   switch (Opcode) {
7523   default: llvm_unreachable("no chain equivalent for opcode");
7524   case ISD::FMUL:
7525     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7526     break;
7527   }
7528 
7529   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7530                      GlueChain.getValue(2));
7531 }
7532 
7533 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7534                            EVT VT, SDValue A, SDValue B, SDValue C,
7535                            SDValue GlueChain) {
7536   if (GlueChain->getNumValues() <= 1) {
7537     return DAG.getNode(Opcode, SL, VT, A, B, C);
7538   }
7539 
7540   assert(GlueChain->getNumValues() == 3);
7541 
7542   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7543   switch (Opcode) {
7544   default: llvm_unreachable("no chain equivalent for opcode");
7545   case ISD::FMA:
7546     Opcode = AMDGPUISD::FMA_W_CHAIN;
7547     break;
7548   }
7549 
7550   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7551                      GlueChain.getValue(2));
7552 }
7553 
7554 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7555   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7556     return FastLowered;
7557 
7558   SDLoc SL(Op);
7559   SDValue Src0 = Op.getOperand(0);
7560   SDValue Src1 = Op.getOperand(1);
7561 
7562   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7563   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7564 
7565   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7566   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7567 
7568   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7569   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7570 
7571   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7572 }
7573 
7574 // Faster 2.5 ULP division that does not support denormals.
7575 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7576   SDLoc SL(Op);
7577   SDValue LHS = Op.getOperand(1);
7578   SDValue RHS = Op.getOperand(2);
7579 
7580   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7581 
7582   const APFloat K0Val(BitsToFloat(0x6f800000));
7583   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7584 
7585   const APFloat K1Val(BitsToFloat(0x2f800000));
7586   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7587 
7588   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7589 
7590   EVT SetCCVT =
7591     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7592 
7593   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7594 
7595   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7596 
7597   // TODO: Should this propagate fast-math-flags?
7598   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7599 
7600   // rcp does not support denormals.
7601   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7602 
7603   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7604 
7605   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7606 }
7607 
7608 // Returns immediate value for setting the F32 denorm mode when using the
7609 // S_DENORM_MODE instruction.
7610 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7611                                           const SDLoc &SL, const GCNSubtarget *ST) {
7612   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7613   int DPDenormModeDefault = ST->hasFP64Denormals()
7614                                 ? FP_DENORM_FLUSH_NONE
7615                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7616 
7617   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7618   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7619 }
7620 
7621 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7622   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7623     return FastLowered;
7624 
7625   SDLoc SL(Op);
7626   SDValue LHS = Op.getOperand(0);
7627   SDValue RHS = Op.getOperand(1);
7628 
7629   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7630 
7631   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7632 
7633   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7634                                           RHS, RHS, LHS);
7635   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7636                                         LHS, RHS, LHS);
7637 
7638   // Denominator is scaled to not be denormal, so using rcp is ok.
7639   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7640                                   DenominatorScaled);
7641   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7642                                      DenominatorScaled);
7643 
7644   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7645                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7646                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7647   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7648 
7649   if (!Subtarget->hasFP32Denormals()) {
7650     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7651 
7652     SDValue EnableDenorm;
7653     if (Subtarget->hasDenormModeInst()) {
7654       const SDValue EnableDenormValue =
7655           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7656 
7657       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7658                                  DAG.getEntryNode(), EnableDenormValue);
7659     } else {
7660       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7661                                                         SL, MVT::i32);
7662       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7663                                  DAG.getEntryNode(), EnableDenormValue,
7664                                  BitField);
7665     }
7666 
7667     SDValue Ops[3] = {
7668       NegDivScale0,
7669       EnableDenorm.getValue(0),
7670       EnableDenorm.getValue(1)
7671     };
7672 
7673     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7674   }
7675 
7676   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7677                              ApproxRcp, One, NegDivScale0);
7678 
7679   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7680                              ApproxRcp, Fma0);
7681 
7682   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7683                            Fma1, Fma1);
7684 
7685   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7686                              NumeratorScaled, Mul);
7687 
7688   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7689 
7690   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7691                              NumeratorScaled, Fma3);
7692 
7693   if (!Subtarget->hasFP32Denormals()) {
7694 
7695     SDValue DisableDenorm;
7696     if (Subtarget->hasDenormModeInst()) {
7697       const SDValue DisableDenormValue =
7698           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7699 
7700       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7701                                   Fma4.getValue(1), DisableDenormValue,
7702                                   Fma4.getValue(2));
7703     } else {
7704       const SDValue DisableDenormValue =
7705           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7706 
7707       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7708                                   Fma4.getValue(1), DisableDenormValue,
7709                                   BitField, Fma4.getValue(2));
7710     }
7711 
7712     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7713                                       DisableDenorm, DAG.getRoot());
7714     DAG.setRoot(OutputChain);
7715   }
7716 
7717   SDValue Scale = NumeratorScaled.getValue(1);
7718   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7719                              Fma4, Fma1, Fma3, Scale);
7720 
7721   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7722 }
7723 
7724 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7725   if (DAG.getTarget().Options.UnsafeFPMath)
7726     return lowerFastUnsafeFDIV(Op, DAG);
7727 
7728   SDLoc SL(Op);
7729   SDValue X = Op.getOperand(0);
7730   SDValue Y = Op.getOperand(1);
7731 
7732   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7733 
7734   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7735 
7736   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7737 
7738   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7739 
7740   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7741 
7742   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7743 
7744   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7745 
7746   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7747 
7748   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7749 
7750   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7751   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7752 
7753   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7754                              NegDivScale0, Mul, DivScale1);
7755 
7756   SDValue Scale;
7757 
7758   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7759     // Workaround a hardware bug on SI where the condition output from div_scale
7760     // is not usable.
7761 
7762     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7763 
7764     // Figure out if the scale to use for div_fmas.
7765     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7766     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7767     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7768     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7769 
7770     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7771     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7772 
7773     SDValue Scale0Hi
7774       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7775     SDValue Scale1Hi
7776       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7777 
7778     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7779     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7780     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7781   } else {
7782     Scale = DivScale1.getValue(1);
7783   }
7784 
7785   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7786                              Fma4, Fma3, Mul, Scale);
7787 
7788   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7789 }
7790 
7791 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7792   EVT VT = Op.getValueType();
7793 
7794   if (VT == MVT::f32)
7795     return LowerFDIV32(Op, DAG);
7796 
7797   if (VT == MVT::f64)
7798     return LowerFDIV64(Op, DAG);
7799 
7800   if (VT == MVT::f16)
7801     return LowerFDIV16(Op, DAG);
7802 
7803   llvm_unreachable("Unexpected type for fdiv");
7804 }
7805 
7806 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7807   SDLoc DL(Op);
7808   StoreSDNode *Store = cast<StoreSDNode>(Op);
7809   EVT VT = Store->getMemoryVT();
7810 
7811   if (VT == MVT::i1) {
7812     return DAG.getTruncStore(Store->getChain(), DL,
7813        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7814        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7815   }
7816 
7817   assert(VT.isVector() &&
7818          Store->getValue().getValueType().getScalarType() == MVT::i32);
7819 
7820   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7821                           *Store->getMemOperand())) {
7822     return expandUnalignedStore(Store, DAG);
7823   }
7824 
7825   unsigned AS = Store->getAddressSpace();
7826   if (Subtarget->hasLDSMisalignedBug() &&
7827       AS == AMDGPUAS::FLAT_ADDRESS &&
7828       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7829     return SplitVectorStore(Op, DAG);
7830   }
7831 
7832   MachineFunction &MF = DAG.getMachineFunction();
7833   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7834   // If there is a possibilty that flat instruction access scratch memory
7835   // then we need to use the same legalization rules we use for private.
7836   if (AS == AMDGPUAS::FLAT_ADDRESS)
7837     AS = MFI->hasFlatScratchInit() ?
7838          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7839 
7840   unsigned NumElements = VT.getVectorNumElements();
7841   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7842       AS == AMDGPUAS::FLAT_ADDRESS) {
7843     if (NumElements > 4)
7844       return SplitVectorStore(Op, DAG);
7845     // v3 stores not supported on SI.
7846     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7847       return SplitVectorStore(Op, DAG);
7848     return SDValue();
7849   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7850     switch (Subtarget->getMaxPrivateElementSize()) {
7851     case 4:
7852       return scalarizeVectorStore(Store, DAG);
7853     case 8:
7854       if (NumElements > 2)
7855         return SplitVectorStore(Op, DAG);
7856       return SDValue();
7857     case 16:
7858       if (NumElements > 4 || NumElements == 3)
7859         return SplitVectorStore(Op, DAG);
7860       return SDValue();
7861     default:
7862       llvm_unreachable("unsupported private_element_size");
7863     }
7864   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7865     // Use ds_write_b128 if possible.
7866     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7867         VT.getStoreSize() == 16 && NumElements != 3)
7868       return SDValue();
7869 
7870     if (NumElements > 2)
7871       return SplitVectorStore(Op, DAG);
7872 
7873     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7874     // address is negative, then the instruction is incorrectly treated as
7875     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7876     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7877     // store later in the SILoadStoreOptimizer.
7878     if (!Subtarget->hasUsableDSOffset() &&
7879         NumElements == 2 && VT.getStoreSize() == 8 &&
7880         Store->getAlignment() < 8) {
7881       return SplitVectorStore(Op, DAG);
7882     }
7883 
7884     return SDValue();
7885   } else {
7886     llvm_unreachable("unhandled address space");
7887   }
7888 }
7889 
7890 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7891   SDLoc DL(Op);
7892   EVT VT = Op.getValueType();
7893   SDValue Arg = Op.getOperand(0);
7894   SDValue TrigVal;
7895 
7896   // TODO: Should this propagate fast-math-flags?
7897 
7898   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7899 
7900   if (Subtarget->hasTrigReducedRange()) {
7901     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7902     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7903   } else {
7904     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7905   }
7906 
7907   switch (Op.getOpcode()) {
7908   case ISD::FCOS:
7909     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7910   case ISD::FSIN:
7911     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7912   default:
7913     llvm_unreachable("Wrong trig opcode");
7914   }
7915 }
7916 
7917 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7918   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7919   assert(AtomicNode->isCompareAndSwap());
7920   unsigned AS = AtomicNode->getAddressSpace();
7921 
7922   // No custom lowering required for local address space
7923   if (!isFlatGlobalAddrSpace(AS))
7924     return Op;
7925 
7926   // Non-local address space requires custom lowering for atomic compare
7927   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7928   SDLoc DL(Op);
7929   SDValue ChainIn = Op.getOperand(0);
7930   SDValue Addr = Op.getOperand(1);
7931   SDValue Old = Op.getOperand(2);
7932   SDValue New = Op.getOperand(3);
7933   EVT VT = Op.getValueType();
7934   MVT SimpleVT = VT.getSimpleVT();
7935   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7936 
7937   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7938   SDValue Ops[] = { ChainIn, Addr, NewOld };
7939 
7940   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7941                                  Ops, VT, AtomicNode->getMemOperand());
7942 }
7943 
7944 //===----------------------------------------------------------------------===//
7945 // Custom DAG optimizations
7946 //===----------------------------------------------------------------------===//
7947 
7948 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7949                                                      DAGCombinerInfo &DCI) const {
7950   EVT VT = N->getValueType(0);
7951   EVT ScalarVT = VT.getScalarType();
7952   if (ScalarVT != MVT::f32)
7953     return SDValue();
7954 
7955   SelectionDAG &DAG = DCI.DAG;
7956   SDLoc DL(N);
7957 
7958   SDValue Src = N->getOperand(0);
7959   EVT SrcVT = Src.getValueType();
7960 
7961   // TODO: We could try to match extracting the higher bytes, which would be
7962   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7963   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7964   // about in practice.
7965   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7966     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7967       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7968       DCI.AddToWorklist(Cvt.getNode());
7969       return Cvt;
7970     }
7971   }
7972 
7973   return SDValue();
7974 }
7975 
7976 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7977 
7978 // This is a variant of
7979 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7980 //
7981 // The normal DAG combiner will do this, but only if the add has one use since
7982 // that would increase the number of instructions.
7983 //
7984 // This prevents us from seeing a constant offset that can be folded into a
7985 // memory instruction's addressing mode. If we know the resulting add offset of
7986 // a pointer can be folded into an addressing offset, we can replace the pointer
7987 // operand with the add of new constant offset. This eliminates one of the uses,
7988 // and may allow the remaining use to also be simplified.
7989 //
7990 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7991                                                unsigned AddrSpace,
7992                                                EVT MemVT,
7993                                                DAGCombinerInfo &DCI) const {
7994   SDValue N0 = N->getOperand(0);
7995   SDValue N1 = N->getOperand(1);
7996 
7997   // We only do this to handle cases where it's profitable when there are
7998   // multiple uses of the add, so defer to the standard combine.
7999   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8000       N0->hasOneUse())
8001     return SDValue();
8002 
8003   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8004   if (!CN1)
8005     return SDValue();
8006 
8007   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8008   if (!CAdd)
8009     return SDValue();
8010 
8011   // If the resulting offset is too large, we can't fold it into the addressing
8012   // mode offset.
8013   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8014   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8015 
8016   AddrMode AM;
8017   AM.HasBaseReg = true;
8018   AM.BaseOffs = Offset.getSExtValue();
8019   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8020     return SDValue();
8021 
8022   SelectionDAG &DAG = DCI.DAG;
8023   SDLoc SL(N);
8024   EVT VT = N->getValueType(0);
8025 
8026   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8027   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8028 
8029   SDNodeFlags Flags;
8030   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8031                           (N0.getOpcode() == ISD::OR ||
8032                            N0->getFlags().hasNoUnsignedWrap()));
8033 
8034   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8035 }
8036 
8037 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8038                                                   DAGCombinerInfo &DCI) const {
8039   SDValue Ptr = N->getBasePtr();
8040   SelectionDAG &DAG = DCI.DAG;
8041   SDLoc SL(N);
8042 
8043   // TODO: We could also do this for multiplies.
8044   if (Ptr.getOpcode() == ISD::SHL) {
8045     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8046                                           N->getMemoryVT(), DCI);
8047     if (NewPtr) {
8048       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8049 
8050       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8051       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8052     }
8053   }
8054 
8055   return SDValue();
8056 }
8057 
8058 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8059   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8060          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8061          (Opc == ISD::XOR && Val == 0);
8062 }
8063 
8064 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8065 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8066 // integer combine opportunities since most 64-bit operations are decomposed
8067 // this way.  TODO: We won't want this for SALU especially if it is an inline
8068 // immediate.
8069 SDValue SITargetLowering::splitBinaryBitConstantOp(
8070   DAGCombinerInfo &DCI,
8071   const SDLoc &SL,
8072   unsigned Opc, SDValue LHS,
8073   const ConstantSDNode *CRHS) const {
8074   uint64_t Val = CRHS->getZExtValue();
8075   uint32_t ValLo = Lo_32(Val);
8076   uint32_t ValHi = Hi_32(Val);
8077   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8078 
8079     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8080          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8081         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8082     // If we need to materialize a 64-bit immediate, it will be split up later
8083     // anyway. Avoid creating the harder to understand 64-bit immediate
8084     // materialization.
8085     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8086   }
8087 
8088   return SDValue();
8089 }
8090 
8091 // Returns true if argument is a boolean value which is not serialized into
8092 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8093 static bool isBoolSGPR(SDValue V) {
8094   if (V.getValueType() != MVT::i1)
8095     return false;
8096   switch (V.getOpcode()) {
8097   default: break;
8098   case ISD::SETCC:
8099   case ISD::AND:
8100   case ISD::OR:
8101   case ISD::XOR:
8102   case AMDGPUISD::FP_CLASS:
8103     return true;
8104   }
8105   return false;
8106 }
8107 
8108 // If a constant has all zeroes or all ones within each byte return it.
8109 // Otherwise return 0.
8110 static uint32_t getConstantPermuteMask(uint32_t C) {
8111   // 0xff for any zero byte in the mask
8112   uint32_t ZeroByteMask = 0;
8113   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8114   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8115   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8116   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8117   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8118   if ((NonZeroByteMask & C) != NonZeroByteMask)
8119     return 0; // Partial bytes selected.
8120   return C;
8121 }
8122 
8123 // Check if a node selects whole bytes from its operand 0 starting at a byte
8124 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8125 // or -1 if not succeeded.
8126 // Note byte select encoding:
8127 // value 0-3 selects corresponding source byte;
8128 // value 0xc selects zero;
8129 // value 0xff selects 0xff.
8130 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8131   assert(V.getValueSizeInBits() == 32);
8132 
8133   if (V.getNumOperands() != 2)
8134     return ~0;
8135 
8136   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8137   if (!N1)
8138     return ~0;
8139 
8140   uint32_t C = N1->getZExtValue();
8141 
8142   switch (V.getOpcode()) {
8143   default:
8144     break;
8145   case ISD::AND:
8146     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8147       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8148     }
8149     break;
8150 
8151   case ISD::OR:
8152     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8153       return (0x03020100 & ~ConstMask) | ConstMask;
8154     }
8155     break;
8156 
8157   case ISD::SHL:
8158     if (C % 8)
8159       return ~0;
8160 
8161     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8162 
8163   case ISD::SRL:
8164     if (C % 8)
8165       return ~0;
8166 
8167     return uint32_t(0x0c0c0c0c03020100ull >> C);
8168   }
8169 
8170   return ~0;
8171 }
8172 
8173 SDValue SITargetLowering::performAndCombine(SDNode *N,
8174                                             DAGCombinerInfo &DCI) const {
8175   if (DCI.isBeforeLegalize())
8176     return SDValue();
8177 
8178   SelectionDAG &DAG = DCI.DAG;
8179   EVT VT = N->getValueType(0);
8180   SDValue LHS = N->getOperand(0);
8181   SDValue RHS = N->getOperand(1);
8182 
8183 
8184   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8185   if (VT == MVT::i64 && CRHS) {
8186     if (SDValue Split
8187         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8188       return Split;
8189   }
8190 
8191   if (CRHS && VT == MVT::i32) {
8192     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8193     // nb = number of trailing zeroes in mask
8194     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8195     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8196     uint64_t Mask = CRHS->getZExtValue();
8197     unsigned Bits = countPopulation(Mask);
8198     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8199         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8200       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8201         unsigned Shift = CShift->getZExtValue();
8202         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8203         unsigned Offset = NB + Shift;
8204         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8205           SDLoc SL(N);
8206           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8207                                     LHS->getOperand(0),
8208                                     DAG.getConstant(Offset, SL, MVT::i32),
8209                                     DAG.getConstant(Bits, SL, MVT::i32));
8210           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8211           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8212                                     DAG.getValueType(NarrowVT));
8213           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8214                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8215           return Shl;
8216         }
8217       }
8218     }
8219 
8220     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8221     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8222         isa<ConstantSDNode>(LHS.getOperand(2))) {
8223       uint32_t Sel = getConstantPermuteMask(Mask);
8224       if (!Sel)
8225         return SDValue();
8226 
8227       // Select 0xc for all zero bytes
8228       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8229       SDLoc DL(N);
8230       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8231                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8232     }
8233   }
8234 
8235   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8236   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8237   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8238     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8239     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8240 
8241     SDValue X = LHS.getOperand(0);
8242     SDValue Y = RHS.getOperand(0);
8243     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8244       return SDValue();
8245 
8246     if (LCC == ISD::SETO) {
8247       if (X != LHS.getOperand(1))
8248         return SDValue();
8249 
8250       if (RCC == ISD::SETUNE) {
8251         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8252         if (!C1 || !C1->isInfinity() || C1->isNegative())
8253           return SDValue();
8254 
8255         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8256                               SIInstrFlags::N_SUBNORMAL |
8257                               SIInstrFlags::N_ZERO |
8258                               SIInstrFlags::P_ZERO |
8259                               SIInstrFlags::P_SUBNORMAL |
8260                               SIInstrFlags::P_NORMAL;
8261 
8262         static_assert(((~(SIInstrFlags::S_NAN |
8263                           SIInstrFlags::Q_NAN |
8264                           SIInstrFlags::N_INFINITY |
8265                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8266                       "mask not equal");
8267 
8268         SDLoc DL(N);
8269         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8270                            X, DAG.getConstant(Mask, DL, MVT::i32));
8271       }
8272     }
8273   }
8274 
8275   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8276     std::swap(LHS, RHS);
8277 
8278   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8279       RHS.hasOneUse()) {
8280     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8281     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8282     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8283     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8284     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8285         (RHS.getOperand(0) == LHS.getOperand(0) &&
8286          LHS.getOperand(0) == LHS.getOperand(1))) {
8287       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8288       unsigned NewMask = LCC == ISD::SETO ?
8289         Mask->getZExtValue() & ~OrdMask :
8290         Mask->getZExtValue() & OrdMask;
8291 
8292       SDLoc DL(N);
8293       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8294                          DAG.getConstant(NewMask, DL, MVT::i32));
8295     }
8296   }
8297 
8298   if (VT == MVT::i32 &&
8299       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8300     // and x, (sext cc from i1) => select cc, x, 0
8301     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8302       std::swap(LHS, RHS);
8303     if (isBoolSGPR(RHS.getOperand(0)))
8304       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8305                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8306   }
8307 
8308   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8309   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8310   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8311       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8312     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8313     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8314     if (LHSMask != ~0u && RHSMask != ~0u) {
8315       // Canonicalize the expression in an attempt to have fewer unique masks
8316       // and therefore fewer registers used to hold the masks.
8317       if (LHSMask > RHSMask) {
8318         std::swap(LHSMask, RHSMask);
8319         std::swap(LHS, RHS);
8320       }
8321 
8322       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8323       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8324       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8325       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8326 
8327       // Check of we need to combine values from two sources within a byte.
8328       if (!(LHSUsedLanes & RHSUsedLanes) &&
8329           // If we select high and lower word keep it for SDWA.
8330           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8331           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8332         // Each byte in each mask is either selector mask 0-3, or has higher
8333         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8334         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8335         // mask which is not 0xff wins. By anding both masks we have a correct
8336         // result except that 0x0c shall be corrected to give 0x0c only.
8337         uint32_t Mask = LHSMask & RHSMask;
8338         for (unsigned I = 0; I < 32; I += 8) {
8339           uint32_t ByteSel = 0xff << I;
8340           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8341             Mask &= (0x0c << I) & 0xffffffff;
8342         }
8343 
8344         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8345         // or 0x0c.
8346         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8347         SDLoc DL(N);
8348 
8349         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8350                            LHS.getOperand(0), RHS.getOperand(0),
8351                            DAG.getConstant(Sel, DL, MVT::i32));
8352       }
8353     }
8354   }
8355 
8356   return SDValue();
8357 }
8358 
8359 SDValue SITargetLowering::performOrCombine(SDNode *N,
8360                                            DAGCombinerInfo &DCI) const {
8361   SelectionDAG &DAG = DCI.DAG;
8362   SDValue LHS = N->getOperand(0);
8363   SDValue RHS = N->getOperand(1);
8364 
8365   EVT VT = N->getValueType(0);
8366   if (VT == MVT::i1) {
8367     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8368     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8369         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8370       SDValue Src = LHS.getOperand(0);
8371       if (Src != RHS.getOperand(0))
8372         return SDValue();
8373 
8374       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8375       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8376       if (!CLHS || !CRHS)
8377         return SDValue();
8378 
8379       // Only 10 bits are used.
8380       static const uint32_t MaxMask = 0x3ff;
8381 
8382       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8383       SDLoc DL(N);
8384       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8385                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8386     }
8387 
8388     return SDValue();
8389   }
8390 
8391   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8392   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8393       LHS.getOpcode() == AMDGPUISD::PERM &&
8394       isa<ConstantSDNode>(LHS.getOperand(2))) {
8395     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8396     if (!Sel)
8397       return SDValue();
8398 
8399     Sel |= LHS.getConstantOperandVal(2);
8400     SDLoc DL(N);
8401     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8402                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8403   }
8404 
8405   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8406   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8407   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8408       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8409     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8410     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8411     if (LHSMask != ~0u && RHSMask != ~0u) {
8412       // Canonicalize the expression in an attempt to have fewer unique masks
8413       // and therefore fewer registers used to hold the masks.
8414       if (LHSMask > RHSMask) {
8415         std::swap(LHSMask, RHSMask);
8416         std::swap(LHS, RHS);
8417       }
8418 
8419       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8420       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8421       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8422       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8423 
8424       // Check of we need to combine values from two sources within a byte.
8425       if (!(LHSUsedLanes & RHSUsedLanes) &&
8426           // If we select high and lower word keep it for SDWA.
8427           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8428           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8429         // Kill zero bytes selected by other mask. Zero value is 0xc.
8430         LHSMask &= ~RHSUsedLanes;
8431         RHSMask &= ~LHSUsedLanes;
8432         // Add 4 to each active LHS lane
8433         LHSMask |= LHSUsedLanes & 0x04040404;
8434         // Combine masks
8435         uint32_t Sel = LHSMask | RHSMask;
8436         SDLoc DL(N);
8437 
8438         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8439                            LHS.getOperand(0), RHS.getOperand(0),
8440                            DAG.getConstant(Sel, DL, MVT::i32));
8441       }
8442     }
8443   }
8444 
8445   if (VT != MVT::i64)
8446     return SDValue();
8447 
8448   // TODO: This could be a generic combine with a predicate for extracting the
8449   // high half of an integer being free.
8450 
8451   // (or i64:x, (zero_extend i32:y)) ->
8452   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8453   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8454       RHS.getOpcode() != ISD::ZERO_EXTEND)
8455     std::swap(LHS, RHS);
8456 
8457   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8458     SDValue ExtSrc = RHS.getOperand(0);
8459     EVT SrcVT = ExtSrc.getValueType();
8460     if (SrcVT == MVT::i32) {
8461       SDLoc SL(N);
8462       SDValue LowLHS, HiBits;
8463       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8464       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8465 
8466       DCI.AddToWorklist(LowOr.getNode());
8467       DCI.AddToWorklist(HiBits.getNode());
8468 
8469       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8470                                 LowOr, HiBits);
8471       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8472     }
8473   }
8474 
8475   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8476   if (CRHS) {
8477     if (SDValue Split
8478           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8479       return Split;
8480   }
8481 
8482   return SDValue();
8483 }
8484 
8485 SDValue SITargetLowering::performXorCombine(SDNode *N,
8486                                             DAGCombinerInfo &DCI) const {
8487   EVT VT = N->getValueType(0);
8488   if (VT != MVT::i64)
8489     return SDValue();
8490 
8491   SDValue LHS = N->getOperand(0);
8492   SDValue RHS = N->getOperand(1);
8493 
8494   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8495   if (CRHS) {
8496     if (SDValue Split
8497           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8498       return Split;
8499   }
8500 
8501   return SDValue();
8502 }
8503 
8504 // Instructions that will be lowered with a final instruction that zeros the
8505 // high result bits.
8506 // XXX - probably only need to list legal operations.
8507 static bool fp16SrcZerosHighBits(unsigned Opc) {
8508   switch (Opc) {
8509   case ISD::FADD:
8510   case ISD::FSUB:
8511   case ISD::FMUL:
8512   case ISD::FDIV:
8513   case ISD::FREM:
8514   case ISD::FMA:
8515   case ISD::FMAD:
8516   case ISD::FCANONICALIZE:
8517   case ISD::FP_ROUND:
8518   case ISD::UINT_TO_FP:
8519   case ISD::SINT_TO_FP:
8520   case ISD::FABS:
8521     // Fabs is lowered to a bit operation, but it's an and which will clear the
8522     // high bits anyway.
8523   case ISD::FSQRT:
8524   case ISD::FSIN:
8525   case ISD::FCOS:
8526   case ISD::FPOWI:
8527   case ISD::FPOW:
8528   case ISD::FLOG:
8529   case ISD::FLOG2:
8530   case ISD::FLOG10:
8531   case ISD::FEXP:
8532   case ISD::FEXP2:
8533   case ISD::FCEIL:
8534   case ISD::FTRUNC:
8535   case ISD::FRINT:
8536   case ISD::FNEARBYINT:
8537   case ISD::FROUND:
8538   case ISD::FFLOOR:
8539   case ISD::FMINNUM:
8540   case ISD::FMAXNUM:
8541   case AMDGPUISD::FRACT:
8542   case AMDGPUISD::CLAMP:
8543   case AMDGPUISD::COS_HW:
8544   case AMDGPUISD::SIN_HW:
8545   case AMDGPUISD::FMIN3:
8546   case AMDGPUISD::FMAX3:
8547   case AMDGPUISD::FMED3:
8548   case AMDGPUISD::FMAD_FTZ:
8549   case AMDGPUISD::RCP:
8550   case AMDGPUISD::RSQ:
8551   case AMDGPUISD::RCP_IFLAG:
8552   case AMDGPUISD::LDEXP:
8553     return true;
8554   default:
8555     // fcopysign, select and others may be lowered to 32-bit bit operations
8556     // which don't zero the high bits.
8557     return false;
8558   }
8559 }
8560 
8561 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8562                                                    DAGCombinerInfo &DCI) const {
8563   if (!Subtarget->has16BitInsts() ||
8564       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8565     return SDValue();
8566 
8567   EVT VT = N->getValueType(0);
8568   if (VT != MVT::i32)
8569     return SDValue();
8570 
8571   SDValue Src = N->getOperand(0);
8572   if (Src.getValueType() != MVT::i16)
8573     return SDValue();
8574 
8575   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8576   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8577   if (Src.getOpcode() == ISD::BITCAST) {
8578     SDValue BCSrc = Src.getOperand(0);
8579     if (BCSrc.getValueType() == MVT::f16 &&
8580         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8581       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8582   }
8583 
8584   return SDValue();
8585 }
8586 
8587 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8588                                                         DAGCombinerInfo &DCI)
8589                                                         const {
8590   SDValue Src = N->getOperand(0);
8591   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8592 
8593   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8594       VTSign->getVT() == MVT::i8) ||
8595       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8596       VTSign->getVT() == MVT::i16)) &&
8597       Src.hasOneUse()) {
8598     auto *M = cast<MemSDNode>(Src);
8599     SDValue Ops[] = {
8600       Src.getOperand(0), // Chain
8601       Src.getOperand(1), // rsrc
8602       Src.getOperand(2), // vindex
8603       Src.getOperand(3), // voffset
8604       Src.getOperand(4), // soffset
8605       Src.getOperand(5), // offset
8606       Src.getOperand(6),
8607       Src.getOperand(7)
8608     };
8609     // replace with BUFFER_LOAD_BYTE/SHORT
8610     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8611                                          Src.getOperand(0).getValueType());
8612     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8613                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8614     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8615                                                           ResList,
8616                                                           Ops, M->getMemoryVT(),
8617                                                           M->getMemOperand());
8618     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8619                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8620   }
8621   return SDValue();
8622 }
8623 
8624 SDValue SITargetLowering::performClassCombine(SDNode *N,
8625                                               DAGCombinerInfo &DCI) const {
8626   SelectionDAG &DAG = DCI.DAG;
8627   SDValue Mask = N->getOperand(1);
8628 
8629   // fp_class x, 0 -> false
8630   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8631     if (CMask->isNullValue())
8632       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8633   }
8634 
8635   if (N->getOperand(0).isUndef())
8636     return DAG.getUNDEF(MVT::i1);
8637 
8638   return SDValue();
8639 }
8640 
8641 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8642                                             DAGCombinerInfo &DCI) const {
8643   EVT VT = N->getValueType(0);
8644   SDValue N0 = N->getOperand(0);
8645 
8646   if (N0.isUndef())
8647     return N0;
8648 
8649   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8650                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8651     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8652                            N->getFlags());
8653   }
8654 
8655   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8656 }
8657 
8658 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8659                                        unsigned MaxDepth) const {
8660   unsigned Opcode = Op.getOpcode();
8661   if (Opcode == ISD::FCANONICALIZE)
8662     return true;
8663 
8664   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8665     auto F = CFP->getValueAPF();
8666     if (F.isNaN() && F.isSignaling())
8667       return false;
8668     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8669   }
8670 
8671   // If source is a result of another standard FP operation it is already in
8672   // canonical form.
8673   if (MaxDepth == 0)
8674     return false;
8675 
8676   switch (Opcode) {
8677   // These will flush denorms if required.
8678   case ISD::FADD:
8679   case ISD::FSUB:
8680   case ISD::FMUL:
8681   case ISD::FCEIL:
8682   case ISD::FFLOOR:
8683   case ISD::FMA:
8684   case ISD::FMAD:
8685   case ISD::FSQRT:
8686   case ISD::FDIV:
8687   case ISD::FREM:
8688   case ISD::FP_ROUND:
8689   case ISD::FP_EXTEND:
8690   case AMDGPUISD::FMUL_LEGACY:
8691   case AMDGPUISD::FMAD_FTZ:
8692   case AMDGPUISD::RCP:
8693   case AMDGPUISD::RSQ:
8694   case AMDGPUISD::RSQ_CLAMP:
8695   case AMDGPUISD::RCP_LEGACY:
8696   case AMDGPUISD::RSQ_LEGACY:
8697   case AMDGPUISD::RCP_IFLAG:
8698   case AMDGPUISD::TRIG_PREOP:
8699   case AMDGPUISD::DIV_SCALE:
8700   case AMDGPUISD::DIV_FMAS:
8701   case AMDGPUISD::DIV_FIXUP:
8702   case AMDGPUISD::FRACT:
8703   case AMDGPUISD::LDEXP:
8704   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8705   case AMDGPUISD::CVT_F32_UBYTE0:
8706   case AMDGPUISD::CVT_F32_UBYTE1:
8707   case AMDGPUISD::CVT_F32_UBYTE2:
8708   case AMDGPUISD::CVT_F32_UBYTE3:
8709     return true;
8710 
8711   // It can/will be lowered or combined as a bit operation.
8712   // Need to check their input recursively to handle.
8713   case ISD::FNEG:
8714   case ISD::FABS:
8715   case ISD::FCOPYSIGN:
8716     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8717 
8718   case ISD::FSIN:
8719   case ISD::FCOS:
8720   case ISD::FSINCOS:
8721     return Op.getValueType().getScalarType() != MVT::f16;
8722 
8723   case ISD::FMINNUM:
8724   case ISD::FMAXNUM:
8725   case ISD::FMINNUM_IEEE:
8726   case ISD::FMAXNUM_IEEE:
8727   case AMDGPUISD::CLAMP:
8728   case AMDGPUISD::FMED3:
8729   case AMDGPUISD::FMAX3:
8730   case AMDGPUISD::FMIN3: {
8731     // FIXME: Shouldn't treat the generic operations different based these.
8732     // However, we aren't really required to flush the result from
8733     // minnum/maxnum..
8734 
8735     // snans will be quieted, so we only need to worry about denormals.
8736     if (Subtarget->supportsMinMaxDenormModes() ||
8737         denormalsEnabledForType(Op.getValueType()))
8738       return true;
8739 
8740     // Flushing may be required.
8741     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8742     // targets need to check their input recursively.
8743 
8744     // FIXME: Does this apply with clamp? It's implemented with max.
8745     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8746       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8747         return false;
8748     }
8749 
8750     return true;
8751   }
8752   case ISD::SELECT: {
8753     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8754            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8755   }
8756   case ISD::BUILD_VECTOR: {
8757     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8758       SDValue SrcOp = Op.getOperand(i);
8759       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8760         return false;
8761     }
8762 
8763     return true;
8764   }
8765   case ISD::EXTRACT_VECTOR_ELT:
8766   case ISD::EXTRACT_SUBVECTOR: {
8767     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8768   }
8769   case ISD::INSERT_VECTOR_ELT: {
8770     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8771            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8772   }
8773   case ISD::UNDEF:
8774     // Could be anything.
8775     return false;
8776 
8777   case ISD::BITCAST: {
8778     // Hack round the mess we make when legalizing extract_vector_elt
8779     SDValue Src = Op.getOperand(0);
8780     if (Src.getValueType() == MVT::i16 &&
8781         Src.getOpcode() == ISD::TRUNCATE) {
8782       SDValue TruncSrc = Src.getOperand(0);
8783       if (TruncSrc.getValueType() == MVT::i32 &&
8784           TruncSrc.getOpcode() == ISD::BITCAST &&
8785           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8786         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8787       }
8788     }
8789 
8790     return false;
8791   }
8792   case ISD::INTRINSIC_WO_CHAIN: {
8793     unsigned IntrinsicID
8794       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8795     // TODO: Handle more intrinsics
8796     switch (IntrinsicID) {
8797     case Intrinsic::amdgcn_cvt_pkrtz:
8798     case Intrinsic::amdgcn_cubeid:
8799     case Intrinsic::amdgcn_frexp_mant:
8800     case Intrinsic::amdgcn_fdot2:
8801       return true;
8802     default:
8803       break;
8804     }
8805 
8806     LLVM_FALLTHROUGH;
8807   }
8808   default:
8809     return denormalsEnabledForType(Op.getValueType()) &&
8810            DAG.isKnownNeverSNaN(Op);
8811   }
8812 
8813   llvm_unreachable("invalid operation");
8814 }
8815 
8816 // Constant fold canonicalize.
8817 SDValue SITargetLowering::getCanonicalConstantFP(
8818   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8819   // Flush denormals to 0 if not enabled.
8820   if (C.isDenormal() && !denormalsEnabledForType(VT))
8821     return DAG.getConstantFP(0.0, SL, VT);
8822 
8823   if (C.isNaN()) {
8824     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8825     if (C.isSignaling()) {
8826       // Quiet a signaling NaN.
8827       // FIXME: Is this supposed to preserve payload bits?
8828       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8829     }
8830 
8831     // Make sure it is the canonical NaN bitpattern.
8832     //
8833     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8834     // immediate?
8835     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8836       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8837   }
8838 
8839   // Already canonical.
8840   return DAG.getConstantFP(C, SL, VT);
8841 }
8842 
8843 static bool vectorEltWillFoldAway(SDValue Op) {
8844   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8845 }
8846 
8847 SDValue SITargetLowering::performFCanonicalizeCombine(
8848   SDNode *N,
8849   DAGCombinerInfo &DCI) const {
8850   SelectionDAG &DAG = DCI.DAG;
8851   SDValue N0 = N->getOperand(0);
8852   EVT VT = N->getValueType(0);
8853 
8854   // fcanonicalize undef -> qnan
8855   if (N0.isUndef()) {
8856     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8857     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8858   }
8859 
8860   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8861     EVT VT = N->getValueType(0);
8862     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8863   }
8864 
8865   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8866   //                                                   (fcanonicalize k)
8867   //
8868   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8869 
8870   // TODO: This could be better with wider vectors that will be split to v2f16,
8871   // and to consider uses since there aren't that many packed operations.
8872   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8873       isTypeLegal(MVT::v2f16)) {
8874     SDLoc SL(N);
8875     SDValue NewElts[2];
8876     SDValue Lo = N0.getOperand(0);
8877     SDValue Hi = N0.getOperand(1);
8878     EVT EltVT = Lo.getValueType();
8879 
8880     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8881       for (unsigned I = 0; I != 2; ++I) {
8882         SDValue Op = N0.getOperand(I);
8883         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8884           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8885                                               CFP->getValueAPF());
8886         } else if (Op.isUndef()) {
8887           // Handled below based on what the other operand is.
8888           NewElts[I] = Op;
8889         } else {
8890           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8891         }
8892       }
8893 
8894       // If one half is undef, and one is constant, perfer a splat vector rather
8895       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8896       // cheaper to use and may be free with a packed operation.
8897       if (NewElts[0].isUndef()) {
8898         if (isa<ConstantFPSDNode>(NewElts[1]))
8899           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8900             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8901       }
8902 
8903       if (NewElts[1].isUndef()) {
8904         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8905           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8906       }
8907 
8908       return DAG.getBuildVector(VT, SL, NewElts);
8909     }
8910   }
8911 
8912   unsigned SrcOpc = N0.getOpcode();
8913 
8914   // If it's free to do so, push canonicalizes further up the source, which may
8915   // find a canonical source.
8916   //
8917   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8918   // sNaNs.
8919   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8920     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8921     if (CRHS && N0.hasOneUse()) {
8922       SDLoc SL(N);
8923       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8924                                    N0.getOperand(0));
8925       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8926       DCI.AddToWorklist(Canon0.getNode());
8927 
8928       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8929     }
8930   }
8931 
8932   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8933 }
8934 
8935 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8936   switch (Opc) {
8937   case ISD::FMAXNUM:
8938   case ISD::FMAXNUM_IEEE:
8939     return AMDGPUISD::FMAX3;
8940   case ISD::SMAX:
8941     return AMDGPUISD::SMAX3;
8942   case ISD::UMAX:
8943     return AMDGPUISD::UMAX3;
8944   case ISD::FMINNUM:
8945   case ISD::FMINNUM_IEEE:
8946     return AMDGPUISD::FMIN3;
8947   case ISD::SMIN:
8948     return AMDGPUISD::SMIN3;
8949   case ISD::UMIN:
8950     return AMDGPUISD::UMIN3;
8951   default:
8952     llvm_unreachable("Not a min/max opcode");
8953   }
8954 }
8955 
8956 SDValue SITargetLowering::performIntMed3ImmCombine(
8957   SelectionDAG &DAG, const SDLoc &SL,
8958   SDValue Op0, SDValue Op1, bool Signed) const {
8959   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8960   if (!K1)
8961     return SDValue();
8962 
8963   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8964   if (!K0)
8965     return SDValue();
8966 
8967   if (Signed) {
8968     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8969       return SDValue();
8970   } else {
8971     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8972       return SDValue();
8973   }
8974 
8975   EVT VT = K0->getValueType(0);
8976   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8977   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8978     return DAG.getNode(Med3Opc, SL, VT,
8979                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8980   }
8981 
8982   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8983   MVT NVT = MVT::i32;
8984   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8985 
8986   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8987   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8988   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8989 
8990   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8991   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8992 }
8993 
8994 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8995   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8996     return C;
8997 
8998   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8999     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9000       return C;
9001   }
9002 
9003   return nullptr;
9004 }
9005 
9006 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9007                                                   const SDLoc &SL,
9008                                                   SDValue Op0,
9009                                                   SDValue Op1) const {
9010   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9011   if (!K1)
9012     return SDValue();
9013 
9014   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9015   if (!K0)
9016     return SDValue();
9017 
9018   // Ordered >= (although NaN inputs should have folded away by now).
9019   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
9020   if (Cmp == APFloat::cmpGreaterThan)
9021     return SDValue();
9022 
9023   const MachineFunction &MF = DAG.getMachineFunction();
9024   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9025 
9026   // TODO: Check IEEE bit enabled?
9027   EVT VT = Op0.getValueType();
9028   if (Info->getMode().DX10Clamp) {
9029     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9030     // hardware fmed3 behavior converting to a min.
9031     // FIXME: Should this be allowing -0.0?
9032     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9033       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9034   }
9035 
9036   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9037   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9038     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9039     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9040     // then give the other result, which is different from med3 with a NaN
9041     // input.
9042     SDValue Var = Op0.getOperand(0);
9043     if (!DAG.isKnownNeverSNaN(Var))
9044       return SDValue();
9045 
9046     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9047 
9048     if ((!K0->hasOneUse() ||
9049          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9050         (!K1->hasOneUse() ||
9051          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9052       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9053                          Var, SDValue(K0, 0), SDValue(K1, 0));
9054     }
9055   }
9056 
9057   return SDValue();
9058 }
9059 
9060 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9061                                                DAGCombinerInfo &DCI) const {
9062   SelectionDAG &DAG = DCI.DAG;
9063 
9064   EVT VT = N->getValueType(0);
9065   unsigned Opc = N->getOpcode();
9066   SDValue Op0 = N->getOperand(0);
9067   SDValue Op1 = N->getOperand(1);
9068 
9069   // Only do this if the inner op has one use since this will just increases
9070   // register pressure for no benefit.
9071 
9072   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9073       !VT.isVector() &&
9074       (VT == MVT::i32 || VT == MVT::f32 ||
9075        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9076     // max(max(a, b), c) -> max3(a, b, c)
9077     // min(min(a, b), c) -> min3(a, b, c)
9078     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9079       SDLoc DL(N);
9080       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9081                          DL,
9082                          N->getValueType(0),
9083                          Op0.getOperand(0),
9084                          Op0.getOperand(1),
9085                          Op1);
9086     }
9087 
9088     // Try commuted.
9089     // max(a, max(b, c)) -> max3(a, b, c)
9090     // min(a, min(b, c)) -> min3(a, b, c)
9091     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9092       SDLoc DL(N);
9093       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9094                          DL,
9095                          N->getValueType(0),
9096                          Op0,
9097                          Op1.getOperand(0),
9098                          Op1.getOperand(1));
9099     }
9100   }
9101 
9102   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9103   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9104     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9105       return Med3;
9106   }
9107 
9108   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9109     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9110       return Med3;
9111   }
9112 
9113   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9114   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9115        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9116        (Opc == AMDGPUISD::FMIN_LEGACY &&
9117         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9118       (VT == MVT::f32 || VT == MVT::f64 ||
9119        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9120        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9121       Op0.hasOneUse()) {
9122     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9123       return Res;
9124   }
9125 
9126   return SDValue();
9127 }
9128 
9129 static bool isClampZeroToOne(SDValue A, SDValue B) {
9130   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9131     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9132       // FIXME: Should this be allowing -0.0?
9133       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9134              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9135     }
9136   }
9137 
9138   return false;
9139 }
9140 
9141 // FIXME: Should only worry about snans for version with chain.
9142 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9143                                               DAGCombinerInfo &DCI) const {
9144   EVT VT = N->getValueType(0);
9145   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9146   // NaNs. With a NaN input, the order of the operands may change the result.
9147 
9148   SelectionDAG &DAG = DCI.DAG;
9149   SDLoc SL(N);
9150 
9151   SDValue Src0 = N->getOperand(0);
9152   SDValue Src1 = N->getOperand(1);
9153   SDValue Src2 = N->getOperand(2);
9154 
9155   if (isClampZeroToOne(Src0, Src1)) {
9156     // const_a, const_b, x -> clamp is safe in all cases including signaling
9157     // nans.
9158     // FIXME: Should this be allowing -0.0?
9159     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9160   }
9161 
9162   const MachineFunction &MF = DAG.getMachineFunction();
9163   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9164 
9165   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9166   // handling no dx10-clamp?
9167   if (Info->getMode().DX10Clamp) {
9168     // If NaNs is clamped to 0, we are free to reorder the inputs.
9169 
9170     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9171       std::swap(Src0, Src1);
9172 
9173     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9174       std::swap(Src1, Src2);
9175 
9176     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9177       std::swap(Src0, Src1);
9178 
9179     if (isClampZeroToOne(Src1, Src2))
9180       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9181   }
9182 
9183   return SDValue();
9184 }
9185 
9186 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9187                                                  DAGCombinerInfo &DCI) const {
9188   SDValue Src0 = N->getOperand(0);
9189   SDValue Src1 = N->getOperand(1);
9190   if (Src0.isUndef() && Src1.isUndef())
9191     return DCI.DAG.getUNDEF(N->getValueType(0));
9192   return SDValue();
9193 }
9194 
9195 SDValue SITargetLowering::performExtractVectorEltCombine(
9196   SDNode *N, DAGCombinerInfo &DCI) const {
9197   SDValue Vec = N->getOperand(0);
9198   SelectionDAG &DAG = DCI.DAG;
9199 
9200   EVT VecVT = Vec.getValueType();
9201   EVT EltVT = VecVT.getVectorElementType();
9202 
9203   if ((Vec.getOpcode() == ISD::FNEG ||
9204        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9205     SDLoc SL(N);
9206     EVT EltVT = N->getValueType(0);
9207     SDValue Idx = N->getOperand(1);
9208     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9209                               Vec.getOperand(0), Idx);
9210     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9211   }
9212 
9213   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9214   //    =>
9215   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9216   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9217   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9218   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9219     SDLoc SL(N);
9220     EVT EltVT = N->getValueType(0);
9221     SDValue Idx = N->getOperand(1);
9222     unsigned Opc = Vec.getOpcode();
9223 
9224     switch(Opc) {
9225     default:
9226       break;
9227       // TODO: Support other binary operations.
9228     case ISD::FADD:
9229     case ISD::FSUB:
9230     case ISD::FMUL:
9231     case ISD::ADD:
9232     case ISD::UMIN:
9233     case ISD::UMAX:
9234     case ISD::SMIN:
9235     case ISD::SMAX:
9236     case ISD::FMAXNUM:
9237     case ISD::FMINNUM:
9238     case ISD::FMAXNUM_IEEE:
9239     case ISD::FMINNUM_IEEE: {
9240       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9241                                  Vec.getOperand(0), Idx);
9242       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9243                                  Vec.getOperand(1), Idx);
9244 
9245       DCI.AddToWorklist(Elt0.getNode());
9246       DCI.AddToWorklist(Elt1.getNode());
9247       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9248     }
9249     }
9250   }
9251 
9252   unsigned VecSize = VecVT.getSizeInBits();
9253   unsigned EltSize = EltVT.getSizeInBits();
9254 
9255   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9256   // This elminates non-constant index and subsequent movrel or scratch access.
9257   // Sub-dword vectors of size 2 dword or less have better implementation.
9258   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9259   // instructions.
9260   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9261       !isa<ConstantSDNode>(N->getOperand(1))) {
9262     SDLoc SL(N);
9263     SDValue Idx = N->getOperand(1);
9264     EVT IdxVT = Idx.getValueType();
9265     SDValue V;
9266     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9267       SDValue IC = DAG.getConstant(I, SL, IdxVT);
9268       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9269       if (I == 0)
9270         V = Elt;
9271       else
9272         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9273     }
9274     return V;
9275   }
9276 
9277   if (!DCI.isBeforeLegalize())
9278     return SDValue();
9279 
9280   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9281   // elements. This exposes more load reduction opportunities by replacing
9282   // multiple small extract_vector_elements with a single 32-bit extract.
9283   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9284   if (isa<MemSDNode>(Vec) &&
9285       EltSize <= 16 &&
9286       EltVT.isByteSized() &&
9287       VecSize > 32 &&
9288       VecSize % 32 == 0 &&
9289       Idx) {
9290     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9291 
9292     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9293     unsigned EltIdx = BitIndex / 32;
9294     unsigned LeftoverBitIdx = BitIndex % 32;
9295     SDLoc SL(N);
9296 
9297     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9298     DCI.AddToWorklist(Cast.getNode());
9299 
9300     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9301                               DAG.getConstant(EltIdx, SL, MVT::i32));
9302     DCI.AddToWorklist(Elt.getNode());
9303     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9304                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9305     DCI.AddToWorklist(Srl.getNode());
9306 
9307     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9308     DCI.AddToWorklist(Trunc.getNode());
9309     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9310   }
9311 
9312   return SDValue();
9313 }
9314 
9315 SDValue
9316 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9317                                                 DAGCombinerInfo &DCI) const {
9318   SDValue Vec = N->getOperand(0);
9319   SDValue Idx = N->getOperand(2);
9320   EVT VecVT = Vec.getValueType();
9321   EVT EltVT = VecVT.getVectorElementType();
9322   unsigned VecSize = VecVT.getSizeInBits();
9323   unsigned EltSize = EltVT.getSizeInBits();
9324 
9325   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9326   // => BUILD_VECTOR n x select (e, const-idx)
9327   // This elminates non-constant index and subsequent movrel or scratch access.
9328   // Sub-dword vectors of size 2 dword or less have better implementation.
9329   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9330   // instructions.
9331   if (isa<ConstantSDNode>(Idx) ||
9332       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9333     return SDValue();
9334 
9335   SelectionDAG &DAG = DCI.DAG;
9336   SDLoc SL(N);
9337   SDValue Ins = N->getOperand(1);
9338   EVT IdxVT = Idx.getValueType();
9339 
9340   SmallVector<SDValue, 16> Ops;
9341   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9342     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9343     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9344     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9345     Ops.push_back(V);
9346   }
9347 
9348   return DAG.getBuildVector(VecVT, SL, Ops);
9349 }
9350 
9351 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9352                                           const SDNode *N0,
9353                                           const SDNode *N1) const {
9354   EVT VT = N0->getValueType(0);
9355 
9356   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9357   // support denormals ever.
9358   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
9359        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
9360         getSubtarget()->hasMadF16())) &&
9361        isOperationLegal(ISD::FMAD, VT))
9362     return ISD::FMAD;
9363 
9364   const TargetOptions &Options = DAG.getTarget().Options;
9365   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9366        (N0->getFlags().hasAllowContract() &&
9367         N1->getFlags().hasAllowContract())) &&
9368       isFMAFasterThanFMulAndFAdd(VT)) {
9369     return ISD::FMA;
9370   }
9371 
9372   return 0;
9373 }
9374 
9375 // For a reassociatable opcode perform:
9376 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9377 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9378                                                SelectionDAG &DAG) const {
9379   EVT VT = N->getValueType(0);
9380   if (VT != MVT::i32 && VT != MVT::i64)
9381     return SDValue();
9382 
9383   unsigned Opc = N->getOpcode();
9384   SDValue Op0 = N->getOperand(0);
9385   SDValue Op1 = N->getOperand(1);
9386 
9387   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9388     return SDValue();
9389 
9390   if (Op0->isDivergent())
9391     std::swap(Op0, Op1);
9392 
9393   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9394     return SDValue();
9395 
9396   SDValue Op2 = Op1.getOperand(1);
9397   Op1 = Op1.getOperand(0);
9398   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9399     return SDValue();
9400 
9401   if (Op1->isDivergent())
9402     std::swap(Op1, Op2);
9403 
9404   // If either operand is constant this will conflict with
9405   // DAGCombiner::ReassociateOps().
9406   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9407       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9408     return SDValue();
9409 
9410   SDLoc SL(N);
9411   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9412   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9413 }
9414 
9415 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9416                            EVT VT,
9417                            SDValue N0, SDValue N1, SDValue N2,
9418                            bool Signed) {
9419   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9420   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9421   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9422   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9423 }
9424 
9425 SDValue SITargetLowering::performAddCombine(SDNode *N,
9426                                             DAGCombinerInfo &DCI) const {
9427   SelectionDAG &DAG = DCI.DAG;
9428   EVT VT = N->getValueType(0);
9429   SDLoc SL(N);
9430   SDValue LHS = N->getOperand(0);
9431   SDValue RHS = N->getOperand(1);
9432 
9433   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9434       && Subtarget->hasMad64_32() &&
9435       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9436       VT.getScalarSizeInBits() <= 64) {
9437     if (LHS.getOpcode() != ISD::MUL)
9438       std::swap(LHS, RHS);
9439 
9440     SDValue MulLHS = LHS.getOperand(0);
9441     SDValue MulRHS = LHS.getOperand(1);
9442     SDValue AddRHS = RHS;
9443 
9444     // TODO: Maybe restrict if SGPR inputs.
9445     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9446         numBitsUnsigned(MulRHS, DAG) <= 32) {
9447       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9448       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9449       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9450       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9451     }
9452 
9453     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9454       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9455       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9456       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9457       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9458     }
9459 
9460     return SDValue();
9461   }
9462 
9463   if (SDValue V = reassociateScalarOps(N, DAG)) {
9464     return V;
9465   }
9466 
9467   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9468     return SDValue();
9469 
9470   // add x, zext (setcc) => addcarry x, 0, setcc
9471   // add x, sext (setcc) => subcarry x, 0, setcc
9472   unsigned Opc = LHS.getOpcode();
9473   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9474       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9475     std::swap(RHS, LHS);
9476 
9477   Opc = RHS.getOpcode();
9478   switch (Opc) {
9479   default: break;
9480   case ISD::ZERO_EXTEND:
9481   case ISD::SIGN_EXTEND:
9482   case ISD::ANY_EXTEND: {
9483     auto Cond = RHS.getOperand(0);
9484     if (!isBoolSGPR(Cond))
9485       break;
9486     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9487     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9488     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9489     return DAG.getNode(Opc, SL, VTList, Args);
9490   }
9491   case ISD::ADDCARRY: {
9492     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9493     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9494     if (!C || C->getZExtValue() != 0) break;
9495     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9496     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9497   }
9498   }
9499   return SDValue();
9500 }
9501 
9502 SDValue SITargetLowering::performSubCombine(SDNode *N,
9503                                             DAGCombinerInfo &DCI) const {
9504   SelectionDAG &DAG = DCI.DAG;
9505   EVT VT = N->getValueType(0);
9506 
9507   if (VT != MVT::i32)
9508     return SDValue();
9509 
9510   SDLoc SL(N);
9511   SDValue LHS = N->getOperand(0);
9512   SDValue RHS = N->getOperand(1);
9513 
9514   if (LHS.getOpcode() == ISD::SUBCARRY) {
9515     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9516     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9517     if (!C || !C->isNullValue())
9518       return SDValue();
9519     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9520     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9521   }
9522   return SDValue();
9523 }
9524 
9525 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9526   DAGCombinerInfo &DCI) const {
9527 
9528   if (N->getValueType(0) != MVT::i32)
9529     return SDValue();
9530 
9531   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9532   if (!C || C->getZExtValue() != 0)
9533     return SDValue();
9534 
9535   SelectionDAG &DAG = DCI.DAG;
9536   SDValue LHS = N->getOperand(0);
9537 
9538   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9539   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9540   unsigned LHSOpc = LHS.getOpcode();
9541   unsigned Opc = N->getOpcode();
9542   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9543       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9544     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9545     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9546   }
9547   return SDValue();
9548 }
9549 
9550 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9551                                              DAGCombinerInfo &DCI) const {
9552   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9553     return SDValue();
9554 
9555   SelectionDAG &DAG = DCI.DAG;
9556   EVT VT = N->getValueType(0);
9557 
9558   SDLoc SL(N);
9559   SDValue LHS = N->getOperand(0);
9560   SDValue RHS = N->getOperand(1);
9561 
9562   // These should really be instruction patterns, but writing patterns with
9563   // source modiifiers is a pain.
9564 
9565   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9566   if (LHS.getOpcode() == ISD::FADD) {
9567     SDValue A = LHS.getOperand(0);
9568     if (A == LHS.getOperand(1)) {
9569       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9570       if (FusedOp != 0) {
9571         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9572         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9573       }
9574     }
9575   }
9576 
9577   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9578   if (RHS.getOpcode() == ISD::FADD) {
9579     SDValue A = RHS.getOperand(0);
9580     if (A == RHS.getOperand(1)) {
9581       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9582       if (FusedOp != 0) {
9583         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9584         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9585       }
9586     }
9587   }
9588 
9589   return SDValue();
9590 }
9591 
9592 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9593                                              DAGCombinerInfo &DCI) const {
9594   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9595     return SDValue();
9596 
9597   SelectionDAG &DAG = DCI.DAG;
9598   SDLoc SL(N);
9599   EVT VT = N->getValueType(0);
9600   assert(!VT.isVector());
9601 
9602   // Try to get the fneg to fold into the source modifier. This undoes generic
9603   // DAG combines and folds them into the mad.
9604   //
9605   // Only do this if we are not trying to support denormals. v_mad_f32 does
9606   // not support denormals ever.
9607   SDValue LHS = N->getOperand(0);
9608   SDValue RHS = N->getOperand(1);
9609   if (LHS.getOpcode() == ISD::FADD) {
9610     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9611     SDValue A = LHS.getOperand(0);
9612     if (A == LHS.getOperand(1)) {
9613       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9614       if (FusedOp != 0){
9615         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9616         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9617 
9618         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9619       }
9620     }
9621   }
9622 
9623   if (RHS.getOpcode() == ISD::FADD) {
9624     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9625 
9626     SDValue A = RHS.getOperand(0);
9627     if (A == RHS.getOperand(1)) {
9628       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9629       if (FusedOp != 0){
9630         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9631         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9632       }
9633     }
9634   }
9635 
9636   return SDValue();
9637 }
9638 
9639 SDValue SITargetLowering::performFMACombine(SDNode *N,
9640                                             DAGCombinerInfo &DCI) const {
9641   SelectionDAG &DAG = DCI.DAG;
9642   EVT VT = N->getValueType(0);
9643   SDLoc SL(N);
9644 
9645   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9646     return SDValue();
9647 
9648   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9649   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9650   SDValue Op1 = N->getOperand(0);
9651   SDValue Op2 = N->getOperand(1);
9652   SDValue FMA = N->getOperand(2);
9653 
9654   if (FMA.getOpcode() != ISD::FMA ||
9655       Op1.getOpcode() != ISD::FP_EXTEND ||
9656       Op2.getOpcode() != ISD::FP_EXTEND)
9657     return SDValue();
9658 
9659   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9660   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9661   // is sufficient to allow generaing fdot2.
9662   const TargetOptions &Options = DAG.getTarget().Options;
9663   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9664       (N->getFlags().hasAllowContract() &&
9665        FMA->getFlags().hasAllowContract())) {
9666     Op1 = Op1.getOperand(0);
9667     Op2 = Op2.getOperand(0);
9668     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9669         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9670       return SDValue();
9671 
9672     SDValue Vec1 = Op1.getOperand(0);
9673     SDValue Idx1 = Op1.getOperand(1);
9674     SDValue Vec2 = Op2.getOperand(0);
9675 
9676     SDValue FMAOp1 = FMA.getOperand(0);
9677     SDValue FMAOp2 = FMA.getOperand(1);
9678     SDValue FMAAcc = FMA.getOperand(2);
9679 
9680     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9681         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9682       return SDValue();
9683 
9684     FMAOp1 = FMAOp1.getOperand(0);
9685     FMAOp2 = FMAOp2.getOperand(0);
9686     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9687         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9688       return SDValue();
9689 
9690     SDValue Vec3 = FMAOp1.getOperand(0);
9691     SDValue Vec4 = FMAOp2.getOperand(0);
9692     SDValue Idx2 = FMAOp1.getOperand(1);
9693 
9694     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9695         // Idx1 and Idx2 cannot be the same.
9696         Idx1 == Idx2)
9697       return SDValue();
9698 
9699     if (Vec1 == Vec2 || Vec3 == Vec4)
9700       return SDValue();
9701 
9702     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9703       return SDValue();
9704 
9705     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9706         (Vec1 == Vec4 && Vec2 == Vec3)) {
9707       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9708                          DAG.getTargetConstant(0, SL, MVT::i1));
9709     }
9710   }
9711   return SDValue();
9712 }
9713 
9714 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9715                                               DAGCombinerInfo &DCI) const {
9716   SelectionDAG &DAG = DCI.DAG;
9717   SDLoc SL(N);
9718 
9719   SDValue LHS = N->getOperand(0);
9720   SDValue RHS = N->getOperand(1);
9721   EVT VT = LHS.getValueType();
9722   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9723 
9724   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9725   if (!CRHS) {
9726     CRHS = dyn_cast<ConstantSDNode>(LHS);
9727     if (CRHS) {
9728       std::swap(LHS, RHS);
9729       CC = getSetCCSwappedOperands(CC);
9730     }
9731   }
9732 
9733   if (CRHS) {
9734     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9735         isBoolSGPR(LHS.getOperand(0))) {
9736       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9737       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9738       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9739       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9740       if ((CRHS->isAllOnesValue() &&
9741            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9742           (CRHS->isNullValue() &&
9743            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9744         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9745                            DAG.getConstant(-1, SL, MVT::i1));
9746       if ((CRHS->isAllOnesValue() &&
9747            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9748           (CRHS->isNullValue() &&
9749            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9750         return LHS.getOperand(0);
9751     }
9752 
9753     uint64_t CRHSVal = CRHS->getZExtValue();
9754     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9755         LHS.getOpcode() == ISD::SELECT &&
9756         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9757         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9758         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9759         isBoolSGPR(LHS.getOperand(0))) {
9760       // Given CT != FT:
9761       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9762       // setcc (select cc, CT, CF), CF, ne => cc
9763       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9764       // setcc (select cc, CT, CF), CT, eq => cc
9765       uint64_t CT = LHS.getConstantOperandVal(1);
9766       uint64_t CF = LHS.getConstantOperandVal(2);
9767 
9768       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9769           (CT == CRHSVal && CC == ISD::SETNE))
9770         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9771                            DAG.getConstant(-1, SL, MVT::i1));
9772       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9773           (CT == CRHSVal && CC == ISD::SETEQ))
9774         return LHS.getOperand(0);
9775     }
9776   }
9777 
9778   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9779                                            VT != MVT::f16))
9780     return SDValue();
9781 
9782   // Match isinf/isfinite pattern
9783   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9784   // (fcmp one (fabs x), inf) -> (fp_class x,
9785   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9786   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9787     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9788     if (!CRHS)
9789       return SDValue();
9790 
9791     const APFloat &APF = CRHS->getValueAPF();
9792     if (APF.isInfinity() && !APF.isNegative()) {
9793       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9794                                  SIInstrFlags::N_INFINITY;
9795       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9796                                     SIInstrFlags::P_ZERO |
9797                                     SIInstrFlags::N_NORMAL |
9798                                     SIInstrFlags::P_NORMAL |
9799                                     SIInstrFlags::N_SUBNORMAL |
9800                                     SIInstrFlags::P_SUBNORMAL;
9801       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9802       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9803                          DAG.getConstant(Mask, SL, MVT::i32));
9804     }
9805   }
9806 
9807   return SDValue();
9808 }
9809 
9810 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9811                                                      DAGCombinerInfo &DCI) const {
9812   SelectionDAG &DAG = DCI.DAG;
9813   SDLoc SL(N);
9814   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9815 
9816   SDValue Src = N->getOperand(0);
9817   SDValue Srl = N->getOperand(0);
9818   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9819     Srl = Srl.getOperand(0);
9820 
9821   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9822   if (Srl.getOpcode() == ISD::SRL) {
9823     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9824     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9825     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9826 
9827     if (const ConstantSDNode *C =
9828         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9829       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9830                                EVT(MVT::i32));
9831 
9832       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9833       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9834         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9835                            MVT::f32, Srl);
9836       }
9837     }
9838   }
9839 
9840   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9841 
9842   KnownBits Known;
9843   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9844                                         !DCI.isBeforeLegalizeOps());
9845   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9846   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9847     DCI.CommitTargetLoweringOpt(TLO);
9848   }
9849 
9850   return SDValue();
9851 }
9852 
9853 SDValue SITargetLowering::performClampCombine(SDNode *N,
9854                                               DAGCombinerInfo &DCI) const {
9855   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9856   if (!CSrc)
9857     return SDValue();
9858 
9859   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9860   const APFloat &F = CSrc->getValueAPF();
9861   APFloat Zero = APFloat::getZero(F.getSemantics());
9862   APFloat::cmpResult Cmp0 = F.compare(Zero);
9863   if (Cmp0 == APFloat::cmpLessThan ||
9864       (Cmp0 == APFloat::cmpUnordered &&
9865        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9866     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9867   }
9868 
9869   APFloat One(F.getSemantics(), "1.0");
9870   APFloat::cmpResult Cmp1 = F.compare(One);
9871   if (Cmp1 == APFloat::cmpGreaterThan)
9872     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9873 
9874   return SDValue(CSrc, 0);
9875 }
9876 
9877 
9878 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9879                                             DAGCombinerInfo &DCI) const {
9880   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9881     return SDValue();
9882   switch (N->getOpcode()) {
9883   default:
9884     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9885   case ISD::ADD:
9886     return performAddCombine(N, DCI);
9887   case ISD::SUB:
9888     return performSubCombine(N, DCI);
9889   case ISD::ADDCARRY:
9890   case ISD::SUBCARRY:
9891     return performAddCarrySubCarryCombine(N, DCI);
9892   case ISD::FADD:
9893     return performFAddCombine(N, DCI);
9894   case ISD::FSUB:
9895     return performFSubCombine(N, DCI);
9896   case ISD::SETCC:
9897     return performSetCCCombine(N, DCI);
9898   case ISD::FMAXNUM:
9899   case ISD::FMINNUM:
9900   case ISD::FMAXNUM_IEEE:
9901   case ISD::FMINNUM_IEEE:
9902   case ISD::SMAX:
9903   case ISD::SMIN:
9904   case ISD::UMAX:
9905   case ISD::UMIN:
9906   case AMDGPUISD::FMIN_LEGACY:
9907   case AMDGPUISD::FMAX_LEGACY:
9908     return performMinMaxCombine(N, DCI);
9909   case ISD::FMA:
9910     return performFMACombine(N, DCI);
9911   case ISD::LOAD: {
9912     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9913       return Widended;
9914     LLVM_FALLTHROUGH;
9915   }
9916   case ISD::STORE:
9917   case ISD::ATOMIC_LOAD:
9918   case ISD::ATOMIC_STORE:
9919   case ISD::ATOMIC_CMP_SWAP:
9920   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9921   case ISD::ATOMIC_SWAP:
9922   case ISD::ATOMIC_LOAD_ADD:
9923   case ISD::ATOMIC_LOAD_SUB:
9924   case ISD::ATOMIC_LOAD_AND:
9925   case ISD::ATOMIC_LOAD_OR:
9926   case ISD::ATOMIC_LOAD_XOR:
9927   case ISD::ATOMIC_LOAD_NAND:
9928   case ISD::ATOMIC_LOAD_MIN:
9929   case ISD::ATOMIC_LOAD_MAX:
9930   case ISD::ATOMIC_LOAD_UMIN:
9931   case ISD::ATOMIC_LOAD_UMAX:
9932   case ISD::ATOMIC_LOAD_FADD:
9933   case AMDGPUISD::ATOMIC_INC:
9934   case AMDGPUISD::ATOMIC_DEC:
9935   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9936   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9937     if (DCI.isBeforeLegalize())
9938       break;
9939     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9940   case ISD::AND:
9941     return performAndCombine(N, DCI);
9942   case ISD::OR:
9943     return performOrCombine(N, DCI);
9944   case ISD::XOR:
9945     return performXorCombine(N, DCI);
9946   case ISD::ZERO_EXTEND:
9947     return performZeroExtendCombine(N, DCI);
9948   case ISD::SIGN_EXTEND_INREG:
9949     return performSignExtendInRegCombine(N , DCI);
9950   case AMDGPUISD::FP_CLASS:
9951     return performClassCombine(N, DCI);
9952   case ISD::FCANONICALIZE:
9953     return performFCanonicalizeCombine(N, DCI);
9954   case AMDGPUISD::RCP:
9955     return performRcpCombine(N, DCI);
9956   case AMDGPUISD::FRACT:
9957   case AMDGPUISD::RSQ:
9958   case AMDGPUISD::RCP_LEGACY:
9959   case AMDGPUISD::RSQ_LEGACY:
9960   case AMDGPUISD::RCP_IFLAG:
9961   case AMDGPUISD::RSQ_CLAMP:
9962   case AMDGPUISD::LDEXP: {
9963     SDValue Src = N->getOperand(0);
9964     if (Src.isUndef())
9965       return Src;
9966     break;
9967   }
9968   case ISD::SINT_TO_FP:
9969   case ISD::UINT_TO_FP:
9970     return performUCharToFloatCombine(N, DCI);
9971   case AMDGPUISD::CVT_F32_UBYTE0:
9972   case AMDGPUISD::CVT_F32_UBYTE1:
9973   case AMDGPUISD::CVT_F32_UBYTE2:
9974   case AMDGPUISD::CVT_F32_UBYTE3:
9975     return performCvtF32UByteNCombine(N, DCI);
9976   case AMDGPUISD::FMED3:
9977     return performFMed3Combine(N, DCI);
9978   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9979     return performCvtPkRTZCombine(N, DCI);
9980   case AMDGPUISD::CLAMP:
9981     return performClampCombine(N, DCI);
9982   case ISD::SCALAR_TO_VECTOR: {
9983     SelectionDAG &DAG = DCI.DAG;
9984     EVT VT = N->getValueType(0);
9985 
9986     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9987     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9988       SDLoc SL(N);
9989       SDValue Src = N->getOperand(0);
9990       EVT EltVT = Src.getValueType();
9991       if (EltVT == MVT::f16)
9992         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9993 
9994       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9995       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9996     }
9997 
9998     break;
9999   }
10000   case ISD::EXTRACT_VECTOR_ELT:
10001     return performExtractVectorEltCombine(N, DCI);
10002   case ISD::INSERT_VECTOR_ELT:
10003     return performInsertVectorEltCombine(N, DCI);
10004   }
10005   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10006 }
10007 
10008 /// Helper function for adjustWritemask
10009 static unsigned SubIdx2Lane(unsigned Idx) {
10010   switch (Idx) {
10011   default: return 0;
10012   case AMDGPU::sub0: return 0;
10013   case AMDGPU::sub1: return 1;
10014   case AMDGPU::sub2: return 2;
10015   case AMDGPU::sub3: return 3;
10016   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10017   }
10018 }
10019 
10020 /// Adjust the writemask of MIMG instructions
10021 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10022                                           SelectionDAG &DAG) const {
10023   unsigned Opcode = Node->getMachineOpcode();
10024 
10025   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10026   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10027   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10028     return Node; // not implemented for D16
10029 
10030   SDNode *Users[5] = { nullptr };
10031   unsigned Lane = 0;
10032   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10033   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10034   unsigned NewDmask = 0;
10035   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10036   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10037   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10038                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10039   unsigned TFCLane = 0;
10040   bool HasChain = Node->getNumValues() > 1;
10041 
10042   if (OldDmask == 0) {
10043     // These are folded out, but on the chance it happens don't assert.
10044     return Node;
10045   }
10046 
10047   unsigned OldBitsSet = countPopulation(OldDmask);
10048   // Work out which is the TFE/LWE lane if that is enabled.
10049   if (UsesTFC) {
10050     TFCLane = OldBitsSet;
10051   }
10052 
10053   // Try to figure out the used register components
10054   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10055        I != E; ++I) {
10056 
10057     // Don't look at users of the chain.
10058     if (I.getUse().getResNo() != 0)
10059       continue;
10060 
10061     // Abort if we can't understand the usage
10062     if (!I->isMachineOpcode() ||
10063         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10064       return Node;
10065 
10066     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10067     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10068     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10069     // set, etc.
10070     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10071 
10072     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10073     if (UsesTFC && Lane == TFCLane) {
10074       Users[Lane] = *I;
10075     } else {
10076       // Set which texture component corresponds to the lane.
10077       unsigned Comp;
10078       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10079         Comp = countTrailingZeros(Dmask);
10080         Dmask &= ~(1 << Comp);
10081       }
10082 
10083       // Abort if we have more than one user per component.
10084       if (Users[Lane])
10085         return Node;
10086 
10087       Users[Lane] = *I;
10088       NewDmask |= 1 << Comp;
10089     }
10090   }
10091 
10092   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10093   bool NoChannels = !NewDmask;
10094   if (NoChannels) {
10095     if (!UsesTFC) {
10096       // No uses of the result and not using TFC. Then do nothing.
10097       return Node;
10098     }
10099     // If the original dmask has one channel - then nothing to do
10100     if (OldBitsSet == 1)
10101       return Node;
10102     // Use an arbitrary dmask - required for the instruction to work
10103     NewDmask = 1;
10104   }
10105   // Abort if there's no change
10106   if (NewDmask == OldDmask)
10107     return Node;
10108 
10109   unsigned BitsSet = countPopulation(NewDmask);
10110 
10111   // Check for TFE or LWE - increase the number of channels by one to account
10112   // for the extra return value
10113   // This will need adjustment for D16 if this is also included in
10114   // adjustWriteMask (this function) but at present D16 are excluded.
10115   unsigned NewChannels = BitsSet + UsesTFC;
10116 
10117   int NewOpcode =
10118       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10119   assert(NewOpcode != -1 &&
10120          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10121          "failed to find equivalent MIMG op");
10122 
10123   // Adjust the writemask in the node
10124   SmallVector<SDValue, 12> Ops;
10125   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10126   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10127   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10128 
10129   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10130 
10131   MVT ResultVT = NewChannels == 1 ?
10132     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10133                            NewChannels == 5 ? 8 : NewChannels);
10134   SDVTList NewVTList = HasChain ?
10135     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10136 
10137 
10138   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10139                                               NewVTList, Ops);
10140 
10141   if (HasChain) {
10142     // Update chain.
10143     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10144     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10145   }
10146 
10147   if (NewChannels == 1) {
10148     assert(Node->hasNUsesOfValue(1, 0));
10149     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10150                                       SDLoc(Node), Users[Lane]->getValueType(0),
10151                                       SDValue(NewNode, 0));
10152     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10153     return nullptr;
10154   }
10155 
10156   // Update the users of the node with the new indices
10157   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10158     SDNode *User = Users[i];
10159     if (!User) {
10160       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10161       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10162       if (i || !NoChannels)
10163         continue;
10164     } else {
10165       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10166       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10167     }
10168 
10169     switch (Idx) {
10170     default: break;
10171     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10172     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10173     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10174     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10175     }
10176   }
10177 
10178   DAG.RemoveDeadNode(Node);
10179   return nullptr;
10180 }
10181 
10182 static bool isFrameIndexOp(SDValue Op) {
10183   if (Op.getOpcode() == ISD::AssertZext)
10184     Op = Op.getOperand(0);
10185 
10186   return isa<FrameIndexSDNode>(Op);
10187 }
10188 
10189 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10190 /// with frame index operands.
10191 /// LLVM assumes that inputs are to these instructions are registers.
10192 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10193                                                         SelectionDAG &DAG) const {
10194   if (Node->getOpcode() == ISD::CopyToReg) {
10195     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10196     SDValue SrcVal = Node->getOperand(2);
10197 
10198     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10199     // to try understanding copies to physical registers.
10200     if (SrcVal.getValueType() == MVT::i1 &&
10201         Register::isPhysicalRegister(DestReg->getReg())) {
10202       SDLoc SL(Node);
10203       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10204       SDValue VReg = DAG.getRegister(
10205         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10206 
10207       SDNode *Glued = Node->getGluedNode();
10208       SDValue ToVReg
10209         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10210                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10211       SDValue ToResultReg
10212         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10213                            VReg, ToVReg.getValue(1));
10214       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10215       DAG.RemoveDeadNode(Node);
10216       return ToResultReg.getNode();
10217     }
10218   }
10219 
10220   SmallVector<SDValue, 8> Ops;
10221   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10222     if (!isFrameIndexOp(Node->getOperand(i))) {
10223       Ops.push_back(Node->getOperand(i));
10224       continue;
10225     }
10226 
10227     SDLoc DL(Node);
10228     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10229                                      Node->getOperand(i).getValueType(),
10230                                      Node->getOperand(i)), 0));
10231   }
10232 
10233   return DAG.UpdateNodeOperands(Node, Ops);
10234 }
10235 
10236 /// Fold the instructions after selecting them.
10237 /// Returns null if users were already updated.
10238 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10239                                           SelectionDAG &DAG) const {
10240   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10241   unsigned Opcode = Node->getMachineOpcode();
10242 
10243   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10244       !TII->isGather4(Opcode)) {
10245     return adjustWritemask(Node, DAG);
10246   }
10247 
10248   if (Opcode == AMDGPU::INSERT_SUBREG ||
10249       Opcode == AMDGPU::REG_SEQUENCE) {
10250     legalizeTargetIndependentNode(Node, DAG);
10251     return Node;
10252   }
10253 
10254   switch (Opcode) {
10255   case AMDGPU::V_DIV_SCALE_F32:
10256   case AMDGPU::V_DIV_SCALE_F64: {
10257     // Satisfy the operand register constraint when one of the inputs is
10258     // undefined. Ordinarily each undef value will have its own implicit_def of
10259     // a vreg, so force these to use a single register.
10260     SDValue Src0 = Node->getOperand(0);
10261     SDValue Src1 = Node->getOperand(1);
10262     SDValue Src2 = Node->getOperand(2);
10263 
10264     if ((Src0.isMachineOpcode() &&
10265          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10266         (Src0 == Src1 || Src0 == Src2))
10267       break;
10268 
10269     MVT VT = Src0.getValueType().getSimpleVT();
10270     const TargetRegisterClass *RC =
10271         getRegClassFor(VT, Src0.getNode()->isDivergent());
10272 
10273     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10274     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10275 
10276     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10277                                       UndefReg, Src0, SDValue());
10278 
10279     // src0 must be the same register as src1 or src2, even if the value is
10280     // undefined, so make sure we don't violate this constraint.
10281     if (Src0.isMachineOpcode() &&
10282         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10283       if (Src1.isMachineOpcode() &&
10284           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10285         Src0 = Src1;
10286       else if (Src2.isMachineOpcode() &&
10287                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10288         Src0 = Src2;
10289       else {
10290         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10291         Src0 = UndefReg;
10292         Src1 = UndefReg;
10293       }
10294     } else
10295       break;
10296 
10297     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10298     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10299       Ops.push_back(Node->getOperand(I));
10300 
10301     Ops.push_back(ImpDef.getValue(1));
10302     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10303   }
10304   case AMDGPU::V_PERMLANE16_B32:
10305   case AMDGPU::V_PERMLANEX16_B32: {
10306     ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
10307     ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
10308     if (!FI->getZExtValue() && !BC->getZExtValue())
10309       break;
10310     SDValue VDstIn = Node->getOperand(6);
10311     if (VDstIn.isMachineOpcode()
10312         && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
10313       break;
10314     MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
10315                                                SDLoc(Node), MVT::i32);
10316     SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
10317                                     SDValue(BC, 0), Node->getOperand(3),
10318                                     Node->getOperand(4), Node->getOperand(5),
10319                                     SDValue(ImpDef, 0), Node->getOperand(7) };
10320     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10321   }
10322   default:
10323     break;
10324   }
10325 
10326   return Node;
10327 }
10328 
10329 /// Assign the register class depending on the number of
10330 /// bits set in the writemask
10331 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10332                                                      SDNode *Node) const {
10333   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10334 
10335   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10336 
10337   if (TII->isVOP3(MI.getOpcode())) {
10338     // Make sure constant bus requirements are respected.
10339     TII->legalizeOperandsVOP3(MRI, MI);
10340 
10341     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10342     // This saves a chain-copy of registers and better ballance register
10343     // use between vgpr and agpr as agpr tuples tend to be big.
10344     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10345       unsigned Opc = MI.getOpcode();
10346       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10347       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10348                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10349         if (I == -1)
10350           break;
10351         MachineOperand &Op = MI.getOperand(I);
10352         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10353              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10354             !Register::isVirtualRegister(Op.getReg()) ||
10355             !TRI->isAGPR(MRI, Op.getReg()))
10356           continue;
10357         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10358         if (!Src || !Src->isCopy() ||
10359             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10360           continue;
10361         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10362         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10363         // All uses of agpr64 and agpr32 can also accept vgpr except for
10364         // v_accvgpr_read, but we do not produce agpr reads during selection,
10365         // so no use checks are needed.
10366         MRI.setRegClass(Op.getReg(), NewRC);
10367       }
10368     }
10369 
10370     return;
10371   }
10372 
10373   // Replace unused atomics with the no return version.
10374   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10375   if (NoRetAtomicOp != -1) {
10376     if (!Node->hasAnyUseOfValue(0)) {
10377       MI.setDesc(TII->get(NoRetAtomicOp));
10378       MI.RemoveOperand(0);
10379       return;
10380     }
10381 
10382     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10383     // instruction, because the return type of these instructions is a vec2 of
10384     // the memory type, so it can be tied to the input operand.
10385     // This means these instructions always have a use, so we need to add a
10386     // special case to check if the atomic has only one extract_subreg use,
10387     // which itself has no uses.
10388     if ((Node->hasNUsesOfValue(1, 0) &&
10389          Node->use_begin()->isMachineOpcode() &&
10390          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10391          !Node->use_begin()->hasAnyUseOfValue(0))) {
10392       Register Def = MI.getOperand(0).getReg();
10393 
10394       // Change this into a noret atomic.
10395       MI.setDesc(TII->get(NoRetAtomicOp));
10396       MI.RemoveOperand(0);
10397 
10398       // If we only remove the def operand from the atomic instruction, the
10399       // extract_subreg will be left with a use of a vreg without a def.
10400       // So we need to insert an implicit_def to avoid machine verifier
10401       // errors.
10402       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10403               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10404     }
10405     return;
10406   }
10407 }
10408 
10409 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10410                               uint64_t Val) {
10411   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10412   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10413 }
10414 
10415 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10416                                                 const SDLoc &DL,
10417                                                 SDValue Ptr) const {
10418   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10419 
10420   // Build the half of the subregister with the constants before building the
10421   // full 128-bit register. If we are building multiple resource descriptors,
10422   // this will allow CSEing of the 2-component register.
10423   const SDValue Ops0[] = {
10424     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10425     buildSMovImm32(DAG, DL, 0),
10426     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10427     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10428     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10429   };
10430 
10431   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10432                                                 MVT::v2i32, Ops0), 0);
10433 
10434   // Combine the constants and the pointer.
10435   const SDValue Ops1[] = {
10436     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10437     Ptr,
10438     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10439     SubRegHi,
10440     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10441   };
10442 
10443   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10444 }
10445 
10446 /// Return a resource descriptor with the 'Add TID' bit enabled
10447 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10448 ///        of the resource descriptor) to create an offset, which is added to
10449 ///        the resource pointer.
10450 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10451                                            SDValue Ptr, uint32_t RsrcDword1,
10452                                            uint64_t RsrcDword2And3) const {
10453   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10454   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10455   if (RsrcDword1) {
10456     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10457                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10458                     0);
10459   }
10460 
10461   SDValue DataLo = buildSMovImm32(DAG, DL,
10462                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10463   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10464 
10465   const SDValue Ops[] = {
10466     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10467     PtrLo,
10468     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10469     PtrHi,
10470     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10471     DataLo,
10472     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10473     DataHi,
10474     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10475   };
10476 
10477   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10478 }
10479 
10480 //===----------------------------------------------------------------------===//
10481 //                         SI Inline Assembly Support
10482 //===----------------------------------------------------------------------===//
10483 
10484 std::pair<unsigned, const TargetRegisterClass *>
10485 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10486                                                StringRef Constraint,
10487                                                MVT VT) const {
10488   const TargetRegisterClass *RC = nullptr;
10489   if (Constraint.size() == 1) {
10490     switch (Constraint[0]) {
10491     default:
10492       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10493     case 's':
10494     case 'r':
10495       switch (VT.getSizeInBits()) {
10496       default:
10497         return std::make_pair(0U, nullptr);
10498       case 32:
10499       case 16:
10500         RC = &AMDGPU::SReg_32_XM0RegClass;
10501         break;
10502       case 64:
10503         RC = &AMDGPU::SGPR_64RegClass;
10504         break;
10505       case 96:
10506         RC = &AMDGPU::SReg_96RegClass;
10507         break;
10508       case 128:
10509         RC = &AMDGPU::SReg_128RegClass;
10510         break;
10511       case 160:
10512         RC = &AMDGPU::SReg_160RegClass;
10513         break;
10514       case 256:
10515         RC = &AMDGPU::SReg_256RegClass;
10516         break;
10517       case 512:
10518         RC = &AMDGPU::SReg_512RegClass;
10519         break;
10520       }
10521       break;
10522     case 'v':
10523       switch (VT.getSizeInBits()) {
10524       default:
10525         return std::make_pair(0U, nullptr);
10526       case 32:
10527       case 16:
10528         RC = &AMDGPU::VGPR_32RegClass;
10529         break;
10530       case 64:
10531         RC = &AMDGPU::VReg_64RegClass;
10532         break;
10533       case 96:
10534         RC = &AMDGPU::VReg_96RegClass;
10535         break;
10536       case 128:
10537         RC = &AMDGPU::VReg_128RegClass;
10538         break;
10539       case 160:
10540         RC = &AMDGPU::VReg_160RegClass;
10541         break;
10542       case 256:
10543         RC = &AMDGPU::VReg_256RegClass;
10544         break;
10545       case 512:
10546         RC = &AMDGPU::VReg_512RegClass;
10547         break;
10548       }
10549       break;
10550     case 'a':
10551       if (!Subtarget->hasMAIInsts())
10552         break;
10553       switch (VT.getSizeInBits()) {
10554       default:
10555         return std::make_pair(0U, nullptr);
10556       case 32:
10557       case 16:
10558         RC = &AMDGPU::AGPR_32RegClass;
10559         break;
10560       case 64:
10561         RC = &AMDGPU::AReg_64RegClass;
10562         break;
10563       case 128:
10564         RC = &AMDGPU::AReg_128RegClass;
10565         break;
10566       case 512:
10567         RC = &AMDGPU::AReg_512RegClass;
10568         break;
10569       case 1024:
10570         RC = &AMDGPU::AReg_1024RegClass;
10571         // v32 types are not legal but we support them here.
10572         return std::make_pair(0U, RC);
10573       }
10574       break;
10575     }
10576     // We actually support i128, i16 and f16 as inline parameters
10577     // even if they are not reported as legal
10578     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10579                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10580       return std::make_pair(0U, RC);
10581   }
10582 
10583   if (Constraint.size() > 1) {
10584     if (Constraint[1] == 'v') {
10585       RC = &AMDGPU::VGPR_32RegClass;
10586     } else if (Constraint[1] == 's') {
10587       RC = &AMDGPU::SGPR_32RegClass;
10588     } else if (Constraint[1] == 'a') {
10589       RC = &AMDGPU::AGPR_32RegClass;
10590     }
10591 
10592     if (RC) {
10593       uint32_t Idx;
10594       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10595       if (!Failed && Idx < RC->getNumRegs())
10596         return std::make_pair(RC->getRegister(Idx), RC);
10597     }
10598   }
10599   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10600 }
10601 
10602 SITargetLowering::ConstraintType
10603 SITargetLowering::getConstraintType(StringRef Constraint) const {
10604   if (Constraint.size() == 1) {
10605     switch (Constraint[0]) {
10606     default: break;
10607     case 's':
10608     case 'v':
10609     case 'a':
10610       return C_RegisterClass;
10611     }
10612   }
10613   return TargetLowering::getConstraintType(Constraint);
10614 }
10615 
10616 // Figure out which registers should be reserved for stack access. Only after
10617 // the function is legalized do we know all of the non-spill stack objects or if
10618 // calls are present.
10619 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10620   MachineRegisterInfo &MRI = MF.getRegInfo();
10621   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10622   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10623   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10624 
10625   if (Info->isEntryFunction()) {
10626     // Callable functions have fixed registers used for stack access.
10627     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10628   }
10629 
10630   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10631                              Info->getStackPtrOffsetReg()));
10632   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10633     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10634 
10635   // We need to worry about replacing the default register with itself in case
10636   // of MIR testcases missing the MFI.
10637   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10638     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10639 
10640   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10641     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10642 
10643   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10644     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10645                        Info->getScratchWaveOffsetReg());
10646   }
10647 
10648   Info->limitOccupancy(MF);
10649 
10650   if (ST.isWave32() && !MF.empty()) {
10651     // Add VCC_HI def because many instructions marked as imp-use VCC where
10652     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10653     // having a use of undef.
10654 
10655     const SIInstrInfo *TII = ST.getInstrInfo();
10656     DebugLoc DL;
10657 
10658     MachineBasicBlock &MBB = MF.front();
10659     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10660     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10661 
10662     for (auto &MBB : MF) {
10663       for (auto &MI : MBB) {
10664         TII->fixImplicitOperands(MI);
10665       }
10666     }
10667   }
10668 
10669   TargetLoweringBase::finalizeLowering(MF);
10670 }
10671 
10672 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10673                                                      KnownBits &Known,
10674                                                      const APInt &DemandedElts,
10675                                                      const SelectionDAG &DAG,
10676                                                      unsigned Depth) const {
10677   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10678                                                 DAG, Depth);
10679 
10680   // Set the high bits to zero based on the maximum allowed scratch size per
10681   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10682   // calculation won't overflow, so assume the sign bit is never set.
10683   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10684 }
10685 
10686 llvm::Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10687   const llvm::Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10688   const llvm::Align CacheLineAlign = llvm::Align(64);
10689 
10690   // Pre-GFX10 target did not benefit from loop alignment
10691   if (!ML || DisableLoopAlignment ||
10692       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10693       getSubtarget()->hasInstFwdPrefetchBug())
10694     return PrefAlign;
10695 
10696   // On GFX10 I$ is 4 x 64 bytes cache lines.
10697   // By default prefetcher keeps one cache line behind and reads two ahead.
10698   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10699   // behind and one ahead.
10700   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10701   // If loop fits 64 bytes it always spans no more than two cache lines and
10702   // does not need an alignment.
10703   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10704   // Else if loop is less or equal 192 bytes we need two lines behind.
10705 
10706   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10707   const MachineBasicBlock *Header = ML->getHeader();
10708   if (Header->getAlignment() != PrefAlign)
10709     return Header->getAlignment(); // Already processed.
10710 
10711   unsigned LoopSize = 0;
10712   for (const MachineBasicBlock *MBB : ML->blocks()) {
10713     // If inner loop block is aligned assume in average half of the alignment
10714     // size to be added as nops.
10715     if (MBB != Header)
10716       LoopSize += (1 << MBB->getLogAlignment()) / 2;
10717 
10718     for (const MachineInstr &MI : *MBB) {
10719       LoopSize += TII->getInstSizeInBytes(MI);
10720       if (LoopSize > 192)
10721         return PrefAlign;
10722     }
10723   }
10724 
10725   if (LoopSize <= 64)
10726     return PrefAlign;
10727 
10728   if (LoopSize <= 128)
10729     return CacheLineAlign;
10730 
10731   // If any of parent loops is surrounded by prefetch instructions do not
10732   // insert new for inner loop, which would reset parent's settings.
10733   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10734     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10735       auto I = Exit->getFirstNonDebugInstr();
10736       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10737         return CacheLineAlign;
10738     }
10739   }
10740 
10741   MachineBasicBlock *Pre = ML->getLoopPreheader();
10742   MachineBasicBlock *Exit = ML->getExitBlock();
10743 
10744   if (Pre && Exit) {
10745     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10746             TII->get(AMDGPU::S_INST_PREFETCH))
10747       .addImm(1); // prefetch 2 lines behind PC
10748 
10749     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10750             TII->get(AMDGPU::S_INST_PREFETCH))
10751       .addImm(2); // prefetch 1 line behind PC
10752   }
10753 
10754   return CacheLineAlign;
10755 }
10756 
10757 LLVM_ATTRIBUTE_UNUSED
10758 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10759   assert(N->getOpcode() == ISD::CopyFromReg);
10760   do {
10761     // Follow the chain until we find an INLINEASM node.
10762     N = N->getOperand(0).getNode();
10763     if (N->getOpcode() == ISD::INLINEASM ||
10764         N->getOpcode() == ISD::INLINEASM_BR)
10765       return true;
10766   } while (N->getOpcode() == ISD::CopyFromReg);
10767   return false;
10768 }
10769 
10770 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10771   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10772 {
10773   switch (N->getOpcode()) {
10774     case ISD::CopyFromReg:
10775     {
10776       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10777       const MachineFunction * MF = FLI->MF;
10778       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10779       const MachineRegisterInfo &MRI = MF->getRegInfo();
10780       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10781       unsigned Reg = R->getReg();
10782       if (Register::isPhysicalRegister(Reg))
10783         return !TRI.isSGPRReg(MRI, Reg);
10784 
10785       if (MRI.isLiveIn(Reg)) {
10786         // workitem.id.x workitem.id.y workitem.id.z
10787         // Any VGPR formal argument is also considered divergent
10788         if (!TRI.isSGPRReg(MRI, Reg))
10789           return true;
10790         // Formal arguments of non-entry functions
10791         // are conservatively considered divergent
10792         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10793           return true;
10794         return false;
10795       }
10796       const Value *V = FLI->getValueFromVirtualReg(Reg);
10797       if (V)
10798         return KDA->isDivergent(V);
10799       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10800       return !TRI.isSGPRReg(MRI, Reg);
10801     }
10802     break;
10803     case ISD::LOAD: {
10804       const LoadSDNode *L = cast<LoadSDNode>(N);
10805       unsigned AS = L->getAddressSpace();
10806       // A flat load may access private memory.
10807       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10808     } break;
10809     case ISD::CALLSEQ_END:
10810     return true;
10811     break;
10812     case ISD::INTRINSIC_WO_CHAIN:
10813     {
10814 
10815     }
10816       return AMDGPU::isIntrinsicSourceOfDivergence(
10817       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10818     case ISD::INTRINSIC_W_CHAIN:
10819       return AMDGPU::isIntrinsicSourceOfDivergence(
10820       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10821     // In some cases intrinsics that are a source of divergence have been
10822     // lowered to AMDGPUISD so we also need to check those too.
10823     case AMDGPUISD::INTERP_MOV:
10824     case AMDGPUISD::INTERP_P1:
10825     case AMDGPUISD::INTERP_P2:
10826       return true;
10827   }
10828   return false;
10829 }
10830 
10831 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10832   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10833   case MVT::f32:
10834     return Subtarget->hasFP32Denormals();
10835   case MVT::f64:
10836     return Subtarget->hasFP64Denormals();
10837   case MVT::f16:
10838     return Subtarget->hasFP16Denormals();
10839   default:
10840     return false;
10841   }
10842 }
10843 
10844 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10845                                                     const SelectionDAG &DAG,
10846                                                     bool SNaN,
10847                                                     unsigned Depth) const {
10848   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10849     const MachineFunction &MF = DAG.getMachineFunction();
10850     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10851 
10852     if (Info->getMode().DX10Clamp)
10853       return true; // Clamped to 0.
10854     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10855   }
10856 
10857   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10858                                                             SNaN, Depth);
10859 }
10860 
10861 TargetLowering::AtomicExpansionKind
10862 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10863   switch (RMW->getOperation()) {
10864   case AtomicRMWInst::FAdd: {
10865     Type *Ty = RMW->getType();
10866 
10867     // We don't have a way to support 16-bit atomics now, so just leave them
10868     // as-is.
10869     if (Ty->isHalfTy())
10870       return AtomicExpansionKind::None;
10871 
10872     if (!Ty->isFloatTy())
10873       return AtomicExpansionKind::CmpXChg;
10874 
10875     // TODO: Do have these for flat. Older targets also had them for buffers.
10876     unsigned AS = RMW->getPointerAddressSpace();
10877     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10878       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10879   }
10880   default:
10881     break;
10882   }
10883 
10884   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10885 }
10886