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 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/IntrinsicsAMDGPU.h"
30 #include "llvm/IR/IntrinsicsR600.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/KnownBits.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "si-lower"
37 
38 STATISTIC(NumTailCalls, "Number of tail calls");
39 
40 static cl::opt<bool> DisableLoopAlignment(
41   "amdgpu-disable-loop-alignment",
42   cl::desc("Do not align and prefetch loops"),
43   cl::init(false));
44 
45 static cl::opt<bool> VGPRReserveforSGPRSpill(
46     "amdgpu-reserve-vgpr-for-sgpr-spill",
47     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
48 
49 static cl::opt<bool> UseDivergentRegisterIndexing(
50   "amdgpu-use-divergent-register-indexing",
51   cl::Hidden,
52   cl::desc("Use indirect register addressing for divergent indexes"),
53   cl::init(false));
54 
55 static bool hasFP32Denormals(const MachineFunction &MF) {
56   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
57   return Info->getMode().allFP32Denormals();
58 }
59 
60 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
61   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
62   return Info->getMode().allFP64FP16Denormals();
63 }
64 
65 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
66   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
67   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
68     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
69       return AMDGPU::SGPR0 + Reg;
70     }
71   }
72   llvm_unreachable("Cannot allocate sgpr");
73 }
74 
75 SITargetLowering::SITargetLowering(const TargetMachine &TM,
76                                    const GCNSubtarget &STI)
77     : AMDGPUTargetLowering(TM, STI),
78       Subtarget(&STI) {
79   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
80   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
81 
82   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
83   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
84 
85   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
86 
87   const SIRegisterInfo *TRI = STI.getRegisterInfo();
88   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
89 
90   addRegisterClass(MVT::f64, V64RegClass);
91   addRegisterClass(MVT::v2f32, V64RegClass);
92 
93   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
94   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
95 
96   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
97   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
98 
99   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
100   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
101 
102   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
103   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
104 
105   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
106   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
107 
108   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
109   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
110 
111   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
112   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
113 
114   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
115   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
116 
117   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
118   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
119 
120   if (Subtarget->has16BitInsts()) {
121     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
122     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
123 
124     // Unless there are also VOP3P operations, not operations are really legal.
125     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
126     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
127     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
128     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
129   }
130 
131   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
132   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
133 
134   computeRegisterProperties(Subtarget->getRegisterInfo());
135 
136   // The boolean content concept here is too inflexible. Compares only ever
137   // really produce a 1-bit result. Any copy/extend from these will turn into a
138   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
139   // it's what most targets use.
140   setBooleanContents(ZeroOrOneBooleanContent);
141   setBooleanVectorContents(ZeroOrOneBooleanContent);
142 
143   // We need to custom lower vector stores from local memory
144   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
145   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
146   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
147   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
148   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
149   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
150   setOperationAction(ISD::LOAD, MVT::i1, Custom);
151   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
152 
153   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
154   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
155   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
156   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
157   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
158   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
159   setOperationAction(ISD::STORE, MVT::i1, Custom);
160   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
161 
162   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
163   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
164   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
165   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
166   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
167   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
168   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
169   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
170   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
171   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
172   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
173   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
174   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
175   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
176   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
177   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
178 
179   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
180   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
181   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
183   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
184 
185   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
186   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
187 
188   setOperationAction(ISD::SELECT, MVT::i1, Promote);
189   setOperationAction(ISD::SELECT, MVT::i64, Custom);
190   setOperationAction(ISD::SELECT, MVT::f64, Promote);
191   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
192 
193   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
194   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
196   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
197   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
198 
199   setOperationAction(ISD::SETCC, MVT::i1, Promote);
200   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
201   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
202   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
203 
204   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
205   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
206   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
207   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
208   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
209   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
210   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
211   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
212 
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
221 
222   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
223   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
225   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
227   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
228 
229   setOperationAction(ISD::UADDO, MVT::i32, Legal);
230   setOperationAction(ISD::USUBO, MVT::i32, Legal);
231 
232   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
233   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
234 
235   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
236   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
237   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
238 
239 #if 0
240   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
241   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
242 #endif
243 
244   // We only support LOAD/STORE and vector manipulation ops for vectors
245   // with > 4 elements.
246   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
247                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
248                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
249                   MVT::v16i64, MVT::v16f64, 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   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
305   }
306 
307   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
308     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
310 
311     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
312     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
313 
314     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
315     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
316 
317     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
319   }
320 
321   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
322     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
323     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
324 
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
326     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
327 
328     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
330 
331     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
333   }
334 
335   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
336   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
337   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
338   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
339 
340   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
341   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
342 
343   // Avoid stack access for these.
344   // TODO: Generalize to more vector types.
345   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
346   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
347   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
348   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
349 
350   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
351   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
352   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
353   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
354   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
355 
356   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
357   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
358   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
359 
360   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
361   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
362   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
363   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
364 
365   // Deal with vec3 vector operations when widened to vec4.
366   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
367   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
368   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
369   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
370 
371   // Deal with vec5 vector operations when widened to vec8.
372   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
373   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
374   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
375   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
376 
377   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
378   // and output demarshalling
379   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
380   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
381 
382   // We can't return success/failure, only the old value,
383   // let LLVM add the comparison
384   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
385   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
386 
387   if (Subtarget->hasFlatAddressSpace()) {
388     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
389     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
390   }
391 
392   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
393   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
394 
395   // FIXME: This should be narrowed to i32, but that only happens if i64 is
396   // illegal.
397   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
398   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
399   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
400 
401   // On SI this is s_memtime and s_memrealtime on VI.
402   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
403   setOperationAction(ISD::TRAP, MVT::Other, Custom);
404   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
405 
406   if (Subtarget->has16BitInsts()) {
407     setOperationAction(ISD::FPOW, MVT::f16, Promote);
408     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
409     setOperationAction(ISD::FLOG, MVT::f16, Custom);
410     setOperationAction(ISD::FEXP, MVT::f16, Custom);
411     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
412   }
413 
414   if (Subtarget->hasMadMacF32Insts())
415     setOperationAction(ISD::FMAD, MVT::f32, Legal);
416 
417   if (!Subtarget->hasBFI()) {
418     // fcopysign can be done in a single instruction with BFI.
419     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
420     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
421   }
422 
423   if (!Subtarget->hasBCNT(32))
424     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
425 
426   if (!Subtarget->hasBCNT(64))
427     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
428 
429   if (Subtarget->hasFFBH())
430     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
431 
432   if (Subtarget->hasFFBL())
433     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
434 
435   // We only really have 32-bit BFE instructions (and 16-bit on VI).
436   //
437   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
438   // effort to match them now. We want this to be false for i64 cases when the
439   // extraction isn't restricted to the upper or lower half. Ideally we would
440   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
441   // span the midpoint are probably relatively rare, so don't worry about them
442   // for now.
443   if (Subtarget->hasBFE())
444     setHasExtractBitsInsn(true);
445 
446   // Clamp modifier on add/sub
447   if (Subtarget->hasIntClamp()) {
448     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
449     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
450   }
451 
452   if (Subtarget->hasAddNoCarry()) {
453     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
454     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
455     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
456     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
457   }
458 
459   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
460   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
461   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
462   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
463 
464 
465   // These are really only legal for ieee_mode functions. We should be avoiding
466   // them for functions that don't have ieee_mode enabled, so just say they are
467   // legal.
468   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
469   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
470   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
471   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
472 
473 
474   if (Subtarget->haveRoundOpsF64()) {
475     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
476     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
477     setOperationAction(ISD::FRINT, MVT::f64, Legal);
478   } else {
479     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
480     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
481     setOperationAction(ISD::FRINT, MVT::f64, Custom);
482     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
483   }
484 
485   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
486 
487   setOperationAction(ISD::FSIN, MVT::f32, Custom);
488   setOperationAction(ISD::FCOS, MVT::f32, Custom);
489   setOperationAction(ISD::FDIV, MVT::f32, Custom);
490   setOperationAction(ISD::FDIV, MVT::f64, Custom);
491 
492   if (Subtarget->has16BitInsts()) {
493     setOperationAction(ISD::Constant, MVT::i16, Legal);
494 
495     setOperationAction(ISD::SMIN, MVT::i16, Legal);
496     setOperationAction(ISD::SMAX, MVT::i16, Legal);
497 
498     setOperationAction(ISD::UMIN, MVT::i16, Legal);
499     setOperationAction(ISD::UMAX, MVT::i16, Legal);
500 
501     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
502     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
503 
504     setOperationAction(ISD::ROTR, MVT::i16, Expand);
505     setOperationAction(ISD::ROTL, MVT::i16, Expand);
506 
507     setOperationAction(ISD::SDIV, MVT::i16, Promote);
508     setOperationAction(ISD::UDIV, MVT::i16, Promote);
509     setOperationAction(ISD::SREM, MVT::i16, Promote);
510     setOperationAction(ISD::UREM, MVT::i16, Promote);
511     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
512     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
513 
514     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
515 
516     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
517     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
518     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
519     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
520     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
521 
522     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
523 
524     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
525 
526     setOperationAction(ISD::LOAD, MVT::i16, Custom);
527 
528     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
529 
530     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
531     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
532     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
533     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
534 
535     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
537 
538     // F16 - Constant Actions.
539     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
540 
541     // F16 - Load/Store Actions.
542     setOperationAction(ISD::LOAD, MVT::f16, Promote);
543     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
544     setOperationAction(ISD::STORE, MVT::f16, Promote);
545     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
546 
547     // F16 - VOP1 Actions.
548     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
549     setOperationAction(ISD::FCOS, MVT::f16, Custom);
550     setOperationAction(ISD::FSIN, MVT::f16, Custom);
551 
552     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
553     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
554 
555     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
556     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
557     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
558     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
559     setOperationAction(ISD::FROUND, MVT::f16, Custom);
560 
561     // F16 - VOP2 Actions.
562     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
563     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
564 
565     setOperationAction(ISD::FDIV, MVT::f16, Custom);
566 
567     // F16 - VOP3 Actions.
568     setOperationAction(ISD::FMA, MVT::f16, Legal);
569     if (STI.hasMadF16())
570       setOperationAction(ISD::FMAD, MVT::f16, Legal);
571 
572     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
573       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
574         switch (Op) {
575         case ISD::LOAD:
576         case ISD::STORE:
577         case ISD::BUILD_VECTOR:
578         case ISD::BITCAST:
579         case ISD::EXTRACT_VECTOR_ELT:
580         case ISD::INSERT_VECTOR_ELT:
581         case ISD::INSERT_SUBVECTOR:
582         case ISD::EXTRACT_SUBVECTOR:
583         case ISD::SCALAR_TO_VECTOR:
584           break;
585         case ISD::CONCAT_VECTORS:
586           setOperationAction(Op, VT, Custom);
587           break;
588         default:
589           setOperationAction(Op, VT, Expand);
590           break;
591         }
592       }
593     }
594 
595     // v_perm_b32 can handle either of these.
596     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
597     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
598     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
599 
600     // XXX - Do these do anything? Vector constants turn into build_vector.
601     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
602     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
603 
604     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
605     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
606 
607     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
608     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
609     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
610     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
611 
612     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
613     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
614     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
615     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
616 
617     setOperationAction(ISD::AND, MVT::v2i16, Promote);
618     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
619     setOperationAction(ISD::OR, MVT::v2i16, Promote);
620     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
621     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
622     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
623 
624     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
625     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
626     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
627     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
628 
629     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
630     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
631     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
632     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
633 
634     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
635     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
636     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
637     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
638 
639     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
640     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
641     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
642 
643     if (!Subtarget->hasVOP3PInsts()) {
644       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
645       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
646     }
647 
648     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
649     // This isn't really legal, but this avoids the legalizer unrolling it (and
650     // allows matching fneg (fabs x) patterns)
651     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
654     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
655     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
656     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
657 
658     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
659     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
660 
661     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
662     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
663   }
664 
665   if (Subtarget->hasVOP3PInsts()) {
666     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
667     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
668     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
669     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
670     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
671     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
672     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
673     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
674     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
675     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
676 
677     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
678     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
679     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
680     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
681 
682     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
683     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
684     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
685 
686     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
687     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
688 
689     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
690 
691     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
692     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
693 
694     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
695     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
696 
697     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
698     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
699     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
700     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
701     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
702     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
703 
704     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
705     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
706     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
707     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
708 
709     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
710     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
711     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
712     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
713 
714     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
715     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
716     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
717 
718     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
719     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
720 
721     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
722     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
723     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
724 
725     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
726     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
727     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
728 
729     if (Subtarget->hasPackedFP32Ops()) {
730       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
731       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
732       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
733       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
734 
735       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
736         setOperationAction(ISD::FADD, VT, Custom);
737         setOperationAction(ISD::FMUL, VT, Custom);
738         setOperationAction(ISD::FMA, VT, Custom);
739       }
740     }
741   }
742 
743   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
744   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
745 
746   if (Subtarget->has16BitInsts()) {
747     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
748     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
749     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
750     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
751   } else {
752     // Legalization hack.
753     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
754     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
755 
756     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
757     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
758   }
759 
760   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
761     setOperationAction(ISD::SELECT, VT, Custom);
762   }
763 
764   setOperationAction(ISD::SMULO, MVT::i64, Custom);
765   setOperationAction(ISD::UMULO, MVT::i64, Custom);
766 
767   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
768   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
774 
775   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
776   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
786 
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
796   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
797 
798   setTargetDAGCombine(ISD::ADD);
799   setTargetDAGCombine(ISD::ADDCARRY);
800   setTargetDAGCombine(ISD::SUB);
801   setTargetDAGCombine(ISD::SUBCARRY);
802   setTargetDAGCombine(ISD::FADD);
803   setTargetDAGCombine(ISD::FSUB);
804   setTargetDAGCombine(ISD::FMINNUM);
805   setTargetDAGCombine(ISD::FMAXNUM);
806   setTargetDAGCombine(ISD::FMINNUM_IEEE);
807   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
808   setTargetDAGCombine(ISD::FMA);
809   setTargetDAGCombine(ISD::SMIN);
810   setTargetDAGCombine(ISD::SMAX);
811   setTargetDAGCombine(ISD::UMIN);
812   setTargetDAGCombine(ISD::UMAX);
813   setTargetDAGCombine(ISD::SETCC);
814   setTargetDAGCombine(ISD::AND);
815   setTargetDAGCombine(ISD::OR);
816   setTargetDAGCombine(ISD::XOR);
817   setTargetDAGCombine(ISD::SINT_TO_FP);
818   setTargetDAGCombine(ISD::UINT_TO_FP);
819   setTargetDAGCombine(ISD::FCANONICALIZE);
820   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
821   setTargetDAGCombine(ISD::ZERO_EXTEND);
822   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
823   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
824   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
825 
826   // All memory operations. Some folding on the pointer operand is done to help
827   // matching the constant offsets in the addressing modes.
828   setTargetDAGCombine(ISD::LOAD);
829   setTargetDAGCombine(ISD::STORE);
830   setTargetDAGCombine(ISD::ATOMIC_LOAD);
831   setTargetDAGCombine(ISD::ATOMIC_STORE);
832   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
833   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
834   setTargetDAGCombine(ISD::ATOMIC_SWAP);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
845   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
846   setTargetDAGCombine(ISD::INTRINSIC_VOID);
847   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
848 
849   // FIXME: In other contexts we pretend this is a per-function property.
850   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
851 
852   setSchedulingPreference(Sched::RegPressure);
853 }
854 
855 const GCNSubtarget *SITargetLowering::getSubtarget() const {
856   return Subtarget;
857 }
858 
859 //===----------------------------------------------------------------------===//
860 // TargetLowering queries
861 //===----------------------------------------------------------------------===//
862 
863 // v_mad_mix* support a conversion from f16 to f32.
864 //
865 // There is only one special case when denormals are enabled we don't currently,
866 // where this is OK to use.
867 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
868                                        EVT DestVT, EVT SrcVT) const {
869   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
870           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
871     DestVT.getScalarType() == MVT::f32 &&
872     SrcVT.getScalarType() == MVT::f16 &&
873     // TODO: This probably only requires no input flushing?
874     !hasFP32Denormals(DAG.getMachineFunction());
875 }
876 
877 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
878   // SI has some legal vector types, but no legal vector operations. Say no
879   // shuffles are legal in order to prefer scalarizing some vector operations.
880   return false;
881 }
882 
883 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
884                                                     CallingConv::ID CC,
885                                                     EVT VT) const {
886   if (CC == CallingConv::AMDGPU_KERNEL)
887     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
888 
889   if (VT.isVector()) {
890     EVT ScalarVT = VT.getScalarType();
891     unsigned Size = ScalarVT.getSizeInBits();
892     if (Size == 16) {
893       if (Subtarget->has16BitInsts())
894         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
895       return VT.isInteger() ? MVT::i32 : MVT::f32;
896     }
897 
898     if (Size < 16)
899       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
900     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
901   }
902 
903   if (VT.getSizeInBits() > 32)
904     return MVT::i32;
905 
906   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
907 }
908 
909 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
910                                                          CallingConv::ID CC,
911                                                          EVT VT) const {
912   if (CC == CallingConv::AMDGPU_KERNEL)
913     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
914 
915   if (VT.isVector()) {
916     unsigned NumElts = VT.getVectorNumElements();
917     EVT ScalarVT = VT.getScalarType();
918     unsigned Size = ScalarVT.getSizeInBits();
919 
920     // FIXME: Should probably promote 8-bit vectors to i16.
921     if (Size == 16 && Subtarget->has16BitInsts())
922       return (NumElts + 1) / 2;
923 
924     if (Size <= 32)
925       return NumElts;
926 
927     if (Size > 32)
928       return NumElts * ((Size + 31) / 32);
929   } else if (VT.getSizeInBits() > 32)
930     return (VT.getSizeInBits() + 31) / 32;
931 
932   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
933 }
934 
935 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
936   LLVMContext &Context, CallingConv::ID CC,
937   EVT VT, EVT &IntermediateVT,
938   unsigned &NumIntermediates, MVT &RegisterVT) const {
939   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
940     unsigned NumElts = VT.getVectorNumElements();
941     EVT ScalarVT = VT.getScalarType();
942     unsigned Size = ScalarVT.getSizeInBits();
943     // FIXME: We should fix the ABI to be the same on targets without 16-bit
944     // support, but unless we can properly handle 3-vectors, it will be still be
945     // inconsistent.
946     if (Size == 16 && Subtarget->has16BitInsts()) {
947       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
948       IntermediateVT = RegisterVT;
949       NumIntermediates = (NumElts + 1) / 2;
950       return NumIntermediates;
951     }
952 
953     if (Size == 32) {
954       RegisterVT = ScalarVT.getSimpleVT();
955       IntermediateVT = RegisterVT;
956       NumIntermediates = NumElts;
957       return NumIntermediates;
958     }
959 
960     if (Size < 16 && Subtarget->has16BitInsts()) {
961       // FIXME: Should probably form v2i16 pieces
962       RegisterVT = MVT::i16;
963       IntermediateVT = ScalarVT;
964       NumIntermediates = NumElts;
965       return NumIntermediates;
966     }
967 
968 
969     if (Size != 16 && Size <= 32) {
970       RegisterVT = MVT::i32;
971       IntermediateVT = ScalarVT;
972       NumIntermediates = NumElts;
973       return NumIntermediates;
974     }
975 
976     if (Size > 32) {
977       RegisterVT = MVT::i32;
978       IntermediateVT = RegisterVT;
979       NumIntermediates = NumElts * ((Size + 31) / 32);
980       return NumIntermediates;
981     }
982   }
983 
984   return TargetLowering::getVectorTypeBreakdownForCallingConv(
985     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
986 }
987 
988 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
989   assert(DMaskLanes != 0);
990 
991   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
992     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
993     return EVT::getVectorVT(Ty->getContext(),
994                             EVT::getEVT(VT->getElementType()),
995                             NumElts);
996   }
997 
998   return EVT::getEVT(Ty);
999 }
1000 
1001 // Peek through TFE struct returns to only use the data size.
1002 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1003   auto *ST = dyn_cast<StructType>(Ty);
1004   if (!ST)
1005     return memVTFromImageData(Ty, DMaskLanes);
1006 
1007   // Some intrinsics return an aggregate type - special case to work out the
1008   // correct memVT.
1009   //
1010   // Only limited forms of aggregate type currently expected.
1011   if (ST->getNumContainedTypes() != 2 ||
1012       !ST->getContainedType(1)->isIntegerTy(32))
1013     return EVT();
1014   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1015 }
1016 
1017 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1018                                           const CallInst &CI,
1019                                           MachineFunction &MF,
1020                                           unsigned IntrID) const {
1021   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1022           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1023     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1024                                                   (Intrinsic::ID)IntrID);
1025     if (Attr.hasFnAttribute(Attribute::ReadNone))
1026       return false;
1027 
1028     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1029 
1030     if (RsrcIntr->IsImage) {
1031       Info.ptrVal =
1032           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1033       Info.align.reset();
1034     } else {
1035       Info.ptrVal =
1036           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1037     }
1038 
1039     Info.flags = MachineMemOperand::MODereferenceable;
1040     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1041       unsigned DMaskLanes = 4;
1042 
1043       if (RsrcIntr->IsImage) {
1044         const AMDGPU::ImageDimIntrinsicInfo *Intr
1045           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1046         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1047           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1048 
1049         if (!BaseOpcode->Gather4) {
1050           // If this isn't a gather, we may have excess loaded elements in the
1051           // IR type. Check the dmask for the real number of elements loaded.
1052           unsigned DMask
1053             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1054           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1055         }
1056 
1057         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1058       } else
1059         Info.memVT = EVT::getEVT(CI.getType());
1060 
1061       // FIXME: What does alignment mean for an image?
1062       Info.opc = ISD::INTRINSIC_W_CHAIN;
1063       Info.flags |= MachineMemOperand::MOLoad;
1064     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1065       Info.opc = ISD::INTRINSIC_VOID;
1066 
1067       Type *DataTy = CI.getArgOperand(0)->getType();
1068       if (RsrcIntr->IsImage) {
1069         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1070         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1071         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1072       } else
1073         Info.memVT = EVT::getEVT(DataTy);
1074 
1075       Info.flags |= MachineMemOperand::MOStore;
1076     } else {
1077       // Atomic
1078       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1079                                             ISD::INTRINSIC_W_CHAIN;
1080       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1081       Info.flags = MachineMemOperand::MOLoad |
1082                    MachineMemOperand::MOStore |
1083                    MachineMemOperand::MODereferenceable;
1084 
1085       // XXX - Should this be volatile without known ordering?
1086       Info.flags |= MachineMemOperand::MOVolatile;
1087     }
1088     return true;
1089   }
1090 
1091   switch (IntrID) {
1092   case Intrinsic::amdgcn_atomic_inc:
1093   case Intrinsic::amdgcn_atomic_dec:
1094   case Intrinsic::amdgcn_ds_ordered_add:
1095   case Intrinsic::amdgcn_ds_ordered_swap:
1096   case Intrinsic::amdgcn_ds_fadd:
1097   case Intrinsic::amdgcn_ds_fmin:
1098   case Intrinsic::amdgcn_ds_fmax: {
1099     Info.opc = ISD::INTRINSIC_W_CHAIN;
1100     Info.memVT = MVT::getVT(CI.getType());
1101     Info.ptrVal = CI.getOperand(0);
1102     Info.align.reset();
1103     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1104 
1105     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1106     if (!Vol->isZero())
1107       Info.flags |= MachineMemOperand::MOVolatile;
1108 
1109     return true;
1110   }
1111   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1112     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1113 
1114     Info.opc = ISD::INTRINSIC_W_CHAIN;
1115     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1116     Info.ptrVal =
1117         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1118     Info.align.reset();
1119     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1120 
1121     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1122     if (!Vol || !Vol->isZero())
1123       Info.flags |= MachineMemOperand::MOVolatile;
1124 
1125     return true;
1126   }
1127   case Intrinsic::amdgcn_ds_append:
1128   case Intrinsic::amdgcn_ds_consume: {
1129     Info.opc = ISD::INTRINSIC_W_CHAIN;
1130     Info.memVT = MVT::getVT(CI.getType());
1131     Info.ptrVal = CI.getOperand(0);
1132     Info.align.reset();
1133     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1134 
1135     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1136     if (!Vol->isZero())
1137       Info.flags |= MachineMemOperand::MOVolatile;
1138 
1139     return true;
1140   }
1141   case Intrinsic::amdgcn_global_atomic_csub: {
1142     Info.opc = ISD::INTRINSIC_W_CHAIN;
1143     Info.memVT = MVT::getVT(CI.getType());
1144     Info.ptrVal = CI.getOperand(0);
1145     Info.align.reset();
1146     Info.flags = MachineMemOperand::MOLoad |
1147                  MachineMemOperand::MOStore |
1148                  MachineMemOperand::MOVolatile;
1149     return true;
1150   }
1151   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1152     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1153     Info.opc = ISD::INTRINSIC_W_CHAIN;
1154     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1155     Info.ptrVal =
1156         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1157     Info.align.reset();
1158     Info.flags = MachineMemOperand::MOLoad |
1159                  MachineMemOperand::MODereferenceable;
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_global_atomic_fadd:
1163   case Intrinsic::amdgcn_global_atomic_fmin:
1164   case Intrinsic::amdgcn_global_atomic_fmax:
1165   case Intrinsic::amdgcn_flat_atomic_fadd:
1166   case Intrinsic::amdgcn_flat_atomic_fmin:
1167   case Intrinsic::amdgcn_flat_atomic_fmax: {
1168     Info.opc = ISD::INTRINSIC_W_CHAIN;
1169     Info.memVT = MVT::getVT(CI.getType());
1170     Info.ptrVal = CI.getOperand(0);
1171     Info.align.reset();
1172     Info.flags = MachineMemOperand::MOLoad |
1173                  MachineMemOperand::MOStore |
1174                  MachineMemOperand::MODereferenceable |
1175                  MachineMemOperand::MOVolatile;
1176     return true;
1177   }
1178   case Intrinsic::amdgcn_ds_gws_init:
1179   case Intrinsic::amdgcn_ds_gws_barrier:
1180   case Intrinsic::amdgcn_ds_gws_sema_v:
1181   case Intrinsic::amdgcn_ds_gws_sema_br:
1182   case Intrinsic::amdgcn_ds_gws_sema_p:
1183   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1184     Info.opc = ISD::INTRINSIC_VOID;
1185 
1186     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1187     Info.ptrVal =
1188         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1189 
1190     // This is an abstract access, but we need to specify a type and size.
1191     Info.memVT = MVT::i32;
1192     Info.size = 4;
1193     Info.align = Align(4);
1194 
1195     Info.flags = MachineMemOperand::MOStore;
1196     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1197       Info.flags = MachineMemOperand::MOLoad;
1198     return true;
1199   }
1200   default:
1201     return false;
1202   }
1203 }
1204 
1205 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1206                                             SmallVectorImpl<Value*> &Ops,
1207                                             Type *&AccessTy) const {
1208   switch (II->getIntrinsicID()) {
1209   case Intrinsic::amdgcn_atomic_inc:
1210   case Intrinsic::amdgcn_atomic_dec:
1211   case Intrinsic::amdgcn_ds_ordered_add:
1212   case Intrinsic::amdgcn_ds_ordered_swap:
1213   case Intrinsic::amdgcn_ds_append:
1214   case Intrinsic::amdgcn_ds_consume:
1215   case Intrinsic::amdgcn_ds_fadd:
1216   case Intrinsic::amdgcn_ds_fmin:
1217   case Intrinsic::amdgcn_ds_fmax:
1218   case Intrinsic::amdgcn_global_atomic_fadd:
1219   case Intrinsic::amdgcn_flat_atomic_fadd:
1220   case Intrinsic::amdgcn_flat_atomic_fmin:
1221   case Intrinsic::amdgcn_flat_atomic_fmax:
1222   case Intrinsic::amdgcn_global_atomic_csub: {
1223     Value *Ptr = II->getArgOperand(0);
1224     AccessTy = II->getType();
1225     Ops.push_back(Ptr);
1226     return true;
1227   }
1228   default:
1229     return false;
1230   }
1231 }
1232 
1233 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1234   if (!Subtarget->hasFlatInstOffsets()) {
1235     // Flat instructions do not have offsets, and only have the register
1236     // address.
1237     return AM.BaseOffs == 0 && AM.Scale == 0;
1238   }
1239 
1240   return AM.Scale == 0 &&
1241          (AM.BaseOffs == 0 ||
1242           Subtarget->getInstrInfo()->isLegalFLATOffset(
1243               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1244 }
1245 
1246 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1247   if (Subtarget->hasFlatGlobalInsts())
1248     return AM.Scale == 0 &&
1249            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1250                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1251                                     SIInstrFlags::FlatGlobal));
1252 
1253   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1254       // Assume the we will use FLAT for all global memory accesses
1255       // on VI.
1256       // FIXME: This assumption is currently wrong.  On VI we still use
1257       // MUBUF instructions for the r + i addressing mode.  As currently
1258       // implemented, the MUBUF instructions only work on buffer < 4GB.
1259       // It may be possible to support > 4GB buffers with MUBUF instructions,
1260       // by setting the stride value in the resource descriptor which would
1261       // increase the size limit to (stride * 4GB).  However, this is risky,
1262       // because it has never been validated.
1263     return isLegalFlatAddressingMode(AM);
1264   }
1265 
1266   return isLegalMUBUFAddressingMode(AM);
1267 }
1268 
1269 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1270   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1271   // additionally can do r + r + i with addr64. 32-bit has more addressing
1272   // mode options. Depending on the resource constant, it can also do
1273   // (i64 r0) + (i32 r1) * (i14 i).
1274   //
1275   // Private arrays end up using a scratch buffer most of the time, so also
1276   // assume those use MUBUF instructions. Scratch loads / stores are currently
1277   // implemented as mubuf instructions with offen bit set, so slightly
1278   // different than the normal addr64.
1279   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1280     return false;
1281 
1282   // FIXME: Since we can split immediate into soffset and immediate offset,
1283   // would it make sense to allow any immediate?
1284 
1285   switch (AM.Scale) {
1286   case 0: // r + i or just i, depending on HasBaseReg.
1287     return true;
1288   case 1:
1289     return true; // We have r + r or r + i.
1290   case 2:
1291     if (AM.HasBaseReg) {
1292       // Reject 2 * r + r.
1293       return false;
1294     }
1295 
1296     // Allow 2 * r as r + r
1297     // Or  2 * r + i is allowed as r + r + i.
1298     return true;
1299   default: // Don't allow n * r
1300     return false;
1301   }
1302 }
1303 
1304 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1305                                              const AddrMode &AM, Type *Ty,
1306                                              unsigned AS, Instruction *I) const {
1307   // No global is ever allowed as a base.
1308   if (AM.BaseGV)
1309     return false;
1310 
1311   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1312     return isLegalGlobalAddressingMode(AM);
1313 
1314   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1315       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1316       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1317     // If the offset isn't a multiple of 4, it probably isn't going to be
1318     // correctly aligned.
1319     // FIXME: Can we get the real alignment here?
1320     if (AM.BaseOffs % 4 != 0)
1321       return isLegalMUBUFAddressingMode(AM);
1322 
1323     // There are no SMRD extloads, so if we have to do a small type access we
1324     // will use a MUBUF load.
1325     // FIXME?: We also need to do this if unaligned, but we don't know the
1326     // alignment here.
1327     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1328       return isLegalGlobalAddressingMode(AM);
1329 
1330     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1331       // SMRD instructions have an 8-bit, dword offset on SI.
1332       if (!isUInt<8>(AM.BaseOffs / 4))
1333         return false;
1334     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1335       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1336       // in 8-bits, it can use a smaller encoding.
1337       if (!isUInt<32>(AM.BaseOffs / 4))
1338         return false;
1339     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1340       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1341       if (!isUInt<20>(AM.BaseOffs))
1342         return false;
1343     } else
1344       llvm_unreachable("unhandled generation");
1345 
1346     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1347       return true;
1348 
1349     if (AM.Scale == 1 && AM.HasBaseReg)
1350       return true;
1351 
1352     return false;
1353 
1354   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1355     return isLegalMUBUFAddressingMode(AM);
1356   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1357              AS == AMDGPUAS::REGION_ADDRESS) {
1358     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1359     // field.
1360     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1361     // an 8-bit dword offset but we don't know the alignment here.
1362     if (!isUInt<16>(AM.BaseOffs))
1363       return false;
1364 
1365     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1366       return true;
1367 
1368     if (AM.Scale == 1 && AM.HasBaseReg)
1369       return true;
1370 
1371     return false;
1372   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1373              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1374     // For an unknown address space, this usually means that this is for some
1375     // reason being used for pure arithmetic, and not based on some addressing
1376     // computation. We don't have instructions that compute pointers with any
1377     // addressing modes, so treat them as having no offset like flat
1378     // instructions.
1379     return isLegalFlatAddressingMode(AM);
1380   }
1381 
1382   // Assume a user alias of global for unknown address spaces.
1383   return isLegalGlobalAddressingMode(AM);
1384 }
1385 
1386 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1387                                         const SelectionDAG &DAG) const {
1388   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1389     return (MemVT.getSizeInBits() <= 4 * 32);
1390   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1391     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1392     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1393   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1394     return (MemVT.getSizeInBits() <= 2 * 32);
1395   }
1396   return true;
1397 }
1398 
1399 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1400     unsigned Size, unsigned AddrSpace, Align Alignment,
1401     MachineMemOperand::Flags Flags, bool *IsFast) const {
1402   if (IsFast)
1403     *IsFast = false;
1404 
1405   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1406       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1407     // Check if alignment requirements for ds_read/write instructions are
1408     // disabled.
1409     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1410         !Subtarget->hasLDSMisalignedBug()) {
1411       if (IsFast)
1412         *IsFast = Alignment != Align(2);
1413       return true;
1414     }
1415 
1416     // Either, the alignment requirements are "enabled", or there is an
1417     // unaligned LDS access related hardware bug though alignment requirements
1418     // are "disabled". In either case, we need to check for proper alignment
1419     // requirements.
1420     //
1421     if (Size == 64) {
1422       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1423       // can do a 4 byte aligned, 8 byte access in a single operation using
1424       // ds_read2/write2_b32 with adjacent offsets.
1425       bool AlignedBy4 = Alignment >= Align(4);
1426       if (IsFast)
1427         *IsFast = AlignedBy4;
1428 
1429       return AlignedBy4;
1430     }
1431     if (Size == 96) {
1432       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1433       // gfx8 and older.
1434       bool AlignedBy16 = Alignment >= Align(16);
1435       if (IsFast)
1436         *IsFast = AlignedBy16;
1437 
1438       return AlignedBy16;
1439     }
1440     if (Size == 128) {
1441       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1442       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1443       // single operation using ds_read2/write2_b64.
1444       bool AlignedBy8 = Alignment >= Align(8);
1445       if (IsFast)
1446         *IsFast = AlignedBy8;
1447 
1448       return AlignedBy8;
1449     }
1450   }
1451 
1452   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1453     bool AlignedBy4 = Alignment >= Align(4);
1454     if (IsFast)
1455       *IsFast = AlignedBy4;
1456 
1457     return AlignedBy4 ||
1458            Subtarget->enableFlatScratch() ||
1459            Subtarget->hasUnalignedScratchAccess();
1460   }
1461 
1462   // FIXME: We have to be conservative here and assume that flat operations
1463   // will access scratch.  If we had access to the IR function, then we
1464   // could determine if any private memory was used in the function.
1465   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1466       !Subtarget->hasUnalignedScratchAccess()) {
1467     bool AlignedBy4 = Alignment >= Align(4);
1468     if (IsFast)
1469       *IsFast = AlignedBy4;
1470 
1471     return AlignedBy4;
1472   }
1473 
1474   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1475       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1476         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1477     // If we have an uniform constant load, it still requires using a slow
1478     // buffer instruction if unaligned.
1479     if (IsFast) {
1480       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1481       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1482       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1483                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1484         Alignment >= Align(4) : Alignment != Align(2);
1485     }
1486 
1487     return true;
1488   }
1489 
1490   // Smaller than dword value must be aligned.
1491   if (Size < 32)
1492     return false;
1493 
1494   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1495   // byte-address are ignored, thus forcing Dword alignment.
1496   // This applies to private, global, and constant memory.
1497   if (IsFast)
1498     *IsFast = true;
1499 
1500   return Size >= 32 && Alignment >= Align(4);
1501 }
1502 
1503 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1504     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1505     bool *IsFast) const {
1506   if (IsFast)
1507     *IsFast = false;
1508 
1509   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1510   // which isn't a simple VT.
1511   // Until MVT is extended to handle this, simply check for the size and
1512   // rely on the condition below: allow accesses if the size is a multiple of 4.
1513   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1514                            VT.getStoreSize() > 16)) {
1515     return false;
1516   }
1517 
1518   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1519                                             Alignment, Flags, IsFast);
1520 }
1521 
1522 EVT SITargetLowering::getOptimalMemOpType(
1523     const MemOp &Op, const AttributeList &FuncAttributes) const {
1524   // FIXME: Should account for address space here.
1525 
1526   // The default fallback uses the private pointer size as a guess for a type to
1527   // use. Make sure we switch these to 64-bit accesses.
1528 
1529   if (Op.size() >= 16 &&
1530       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1531     return MVT::v4i32;
1532 
1533   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1534     return MVT::v2i32;
1535 
1536   // Use the default.
1537   return MVT::Other;
1538 }
1539 
1540 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1541   const MemSDNode *MemNode = cast<MemSDNode>(N);
1542   const Value *Ptr = MemNode->getMemOperand()->getValue();
1543   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1544   return I && I->getMetadata("amdgpu.noclobber");
1545 }
1546 
1547 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1548   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1549          AS == AMDGPUAS::PRIVATE_ADDRESS;
1550 }
1551 
1552 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1553                                            unsigned DestAS) const {
1554   // Flat -> private/local is a simple truncate.
1555   // Flat -> global is no-op
1556   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1557     return true;
1558 
1559   const GCNTargetMachine &TM =
1560       static_cast<const GCNTargetMachine &>(getTargetMachine());
1561   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1562 }
1563 
1564 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1565   const MemSDNode *MemNode = cast<MemSDNode>(N);
1566 
1567   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1568 }
1569 
1570 TargetLoweringBase::LegalizeTypeAction
1571 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1572   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1573       VT.getScalarType().bitsLE(MVT::i16))
1574     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1575   return TargetLoweringBase::getPreferredVectorAction(VT);
1576 }
1577 
1578 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1579                                                          Type *Ty) const {
1580   // FIXME: Could be smarter if called for vector constants.
1581   return true;
1582 }
1583 
1584 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1585   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1586     switch (Op) {
1587     case ISD::LOAD:
1588     case ISD::STORE:
1589 
1590     // These operations are done with 32-bit instructions anyway.
1591     case ISD::AND:
1592     case ISD::OR:
1593     case ISD::XOR:
1594     case ISD::SELECT:
1595       // TODO: Extensions?
1596       return true;
1597     default:
1598       return false;
1599     }
1600   }
1601 
1602   // SimplifySetCC uses this function to determine whether or not it should
1603   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1604   if (VT == MVT::i1 && Op == ISD::SETCC)
1605     return false;
1606 
1607   return TargetLowering::isTypeDesirableForOp(Op, VT);
1608 }
1609 
1610 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1611                                                    const SDLoc &SL,
1612                                                    SDValue Chain,
1613                                                    uint64_t Offset) const {
1614   const DataLayout &DL = DAG.getDataLayout();
1615   MachineFunction &MF = DAG.getMachineFunction();
1616   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1617 
1618   const ArgDescriptor *InputPtrReg;
1619   const TargetRegisterClass *RC;
1620   LLT ArgTy;
1621 
1622   std::tie(InputPtrReg, RC, ArgTy) =
1623       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1624 
1625   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1626   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1627   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1628     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1629 
1630   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1631 }
1632 
1633 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1634                                             const SDLoc &SL) const {
1635   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1636                                                FIRST_IMPLICIT);
1637   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1638 }
1639 
1640 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1641                                          const SDLoc &SL, SDValue Val,
1642                                          bool Signed,
1643                                          const ISD::InputArg *Arg) const {
1644   // First, if it is a widened vector, narrow it.
1645   if (VT.isVector() &&
1646       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1647     EVT NarrowedVT =
1648         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1649                          VT.getVectorNumElements());
1650     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1651                       DAG.getConstant(0, SL, MVT::i32));
1652   }
1653 
1654   // Then convert the vector elements or scalar value.
1655   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1656       VT.bitsLT(MemVT)) {
1657     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1658     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1659   }
1660 
1661   if (MemVT.isFloatingPoint())
1662     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1663   else if (Signed)
1664     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1665   else
1666     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1667 
1668   return Val;
1669 }
1670 
1671 SDValue SITargetLowering::lowerKernargMemParameter(
1672     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1673     uint64_t Offset, Align Alignment, bool Signed,
1674     const ISD::InputArg *Arg) const {
1675   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1676 
1677   // Try to avoid using an extload by loading earlier than the argument address,
1678   // and extracting the relevant bits. The load should hopefully be merged with
1679   // the previous argument.
1680   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1681     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1682     int64_t AlignDownOffset = alignDown(Offset, 4);
1683     int64_t OffsetDiff = Offset - AlignDownOffset;
1684 
1685     EVT IntVT = MemVT.changeTypeToInteger();
1686 
1687     // TODO: If we passed in the base kernel offset we could have a better
1688     // alignment than 4, but we don't really need it.
1689     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1690     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1691                                MachineMemOperand::MODereferenceable |
1692                                    MachineMemOperand::MOInvariant);
1693 
1694     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1695     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1696 
1697     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1698     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1699     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1700 
1701 
1702     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1703   }
1704 
1705   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1706   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1707                              MachineMemOperand::MODereferenceable |
1708                                  MachineMemOperand::MOInvariant);
1709 
1710   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1711   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1712 }
1713 
1714 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1715                                               const SDLoc &SL, SDValue Chain,
1716                                               const ISD::InputArg &Arg) const {
1717   MachineFunction &MF = DAG.getMachineFunction();
1718   MachineFrameInfo &MFI = MF.getFrameInfo();
1719 
1720   if (Arg.Flags.isByVal()) {
1721     unsigned Size = Arg.Flags.getByValSize();
1722     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1723     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1724   }
1725 
1726   unsigned ArgOffset = VA.getLocMemOffset();
1727   unsigned ArgSize = VA.getValVT().getStoreSize();
1728 
1729   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1730 
1731   // Create load nodes to retrieve arguments from the stack.
1732   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1733   SDValue ArgValue;
1734 
1735   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1736   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1737   MVT MemVT = VA.getValVT();
1738 
1739   switch (VA.getLocInfo()) {
1740   default:
1741     break;
1742   case CCValAssign::BCvt:
1743     MemVT = VA.getLocVT();
1744     break;
1745   case CCValAssign::SExt:
1746     ExtType = ISD::SEXTLOAD;
1747     break;
1748   case CCValAssign::ZExt:
1749     ExtType = ISD::ZEXTLOAD;
1750     break;
1751   case CCValAssign::AExt:
1752     ExtType = ISD::EXTLOAD;
1753     break;
1754   }
1755 
1756   ArgValue = DAG.getExtLoad(
1757     ExtType, SL, VA.getLocVT(), Chain, FIN,
1758     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1759     MemVT);
1760   return ArgValue;
1761 }
1762 
1763 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1764   const SIMachineFunctionInfo &MFI,
1765   EVT VT,
1766   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1767   const ArgDescriptor *Reg;
1768   const TargetRegisterClass *RC;
1769   LLT Ty;
1770 
1771   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1772   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1773 }
1774 
1775 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1776                                CallingConv::ID CallConv,
1777                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1778                                FunctionType *FType,
1779                                SIMachineFunctionInfo *Info) {
1780   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1781     const ISD::InputArg *Arg = &Ins[I];
1782 
1783     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1784            "vector type argument should have been split");
1785 
1786     // First check if it's a PS input addr.
1787     if (CallConv == CallingConv::AMDGPU_PS &&
1788         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1789       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1790 
1791       // Inconveniently only the first part of the split is marked as isSplit,
1792       // so skip to the end. We only want to increment PSInputNum once for the
1793       // entire split argument.
1794       if (Arg->Flags.isSplit()) {
1795         while (!Arg->Flags.isSplitEnd()) {
1796           assert((!Arg->VT.isVector() ||
1797                   Arg->VT.getScalarSizeInBits() == 16) &&
1798                  "unexpected vector split in ps argument type");
1799           if (!SkipArg)
1800             Splits.push_back(*Arg);
1801           Arg = &Ins[++I];
1802         }
1803       }
1804 
1805       if (SkipArg) {
1806         // We can safely skip PS inputs.
1807         Skipped.set(Arg->getOrigArgIndex());
1808         ++PSInputNum;
1809         continue;
1810       }
1811 
1812       Info->markPSInputAllocated(PSInputNum);
1813       if (Arg->Used)
1814         Info->markPSInputEnabled(PSInputNum);
1815 
1816       ++PSInputNum;
1817     }
1818 
1819     Splits.push_back(*Arg);
1820   }
1821 }
1822 
1823 // Allocate special inputs passed in VGPRs.
1824 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1825                                                       MachineFunction &MF,
1826                                                       const SIRegisterInfo &TRI,
1827                                                       SIMachineFunctionInfo &Info) const {
1828   const LLT S32 = LLT::scalar(32);
1829   MachineRegisterInfo &MRI = MF.getRegInfo();
1830 
1831   if (Info.hasWorkItemIDX()) {
1832     Register Reg = AMDGPU::VGPR0;
1833     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1834 
1835     CCInfo.AllocateReg(Reg);
1836     unsigned Mask = (Subtarget->hasPackedTID() &&
1837                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1838     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1839   }
1840 
1841   if (Info.hasWorkItemIDY()) {
1842     assert(Info.hasWorkItemIDX());
1843     if (Subtarget->hasPackedTID()) {
1844       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1845                                                         0x3ff << 10));
1846     } else {
1847       unsigned Reg = AMDGPU::VGPR1;
1848       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1849 
1850       CCInfo.AllocateReg(Reg);
1851       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1852     }
1853   }
1854 
1855   if (Info.hasWorkItemIDZ()) {
1856     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1857     if (Subtarget->hasPackedTID()) {
1858       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1859                                                         0x3ff << 20));
1860     } else {
1861       unsigned Reg = AMDGPU::VGPR2;
1862       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1863 
1864       CCInfo.AllocateReg(Reg);
1865       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1866     }
1867   }
1868 }
1869 
1870 // Try to allocate a VGPR at the end of the argument list, or if no argument
1871 // VGPRs are left allocating a stack slot.
1872 // If \p Mask is is given it indicates bitfield position in the register.
1873 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1874 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1875                                          ArgDescriptor Arg = ArgDescriptor()) {
1876   if (Arg.isSet())
1877     return ArgDescriptor::createArg(Arg, Mask);
1878 
1879   ArrayRef<MCPhysReg> ArgVGPRs
1880     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1881   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1882   if (RegIdx == ArgVGPRs.size()) {
1883     // Spill to stack required.
1884     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1885 
1886     return ArgDescriptor::createStack(Offset, Mask);
1887   }
1888 
1889   unsigned Reg = ArgVGPRs[RegIdx];
1890   Reg = CCInfo.AllocateReg(Reg);
1891   assert(Reg != AMDGPU::NoRegister);
1892 
1893   MachineFunction &MF = CCInfo.getMachineFunction();
1894   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1895   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1896   return ArgDescriptor::createRegister(Reg, Mask);
1897 }
1898 
1899 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1900                                              const TargetRegisterClass *RC,
1901                                              unsigned NumArgRegs) {
1902   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1903   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1904   if (RegIdx == ArgSGPRs.size())
1905     report_fatal_error("ran out of SGPRs for arguments");
1906 
1907   unsigned Reg = ArgSGPRs[RegIdx];
1908   Reg = CCInfo.AllocateReg(Reg);
1909   assert(Reg != AMDGPU::NoRegister);
1910 
1911   MachineFunction &MF = CCInfo.getMachineFunction();
1912   MF.addLiveIn(Reg, RC);
1913   return ArgDescriptor::createRegister(Reg);
1914 }
1915 
1916 // If this has a fixed position, we still should allocate the register in the
1917 // CCInfo state. Technically we could get away with this for values passed
1918 // outside of the normal argument range.
1919 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1920                                        const TargetRegisterClass *RC,
1921                                        MCRegister Reg) {
1922   Reg = CCInfo.AllocateReg(Reg);
1923   assert(Reg != AMDGPU::NoRegister);
1924   MachineFunction &MF = CCInfo.getMachineFunction();
1925   MF.addLiveIn(Reg, RC);
1926 }
1927 
1928 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1929   if (Arg) {
1930     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1931                                Arg.getRegister());
1932   } else
1933     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1934 }
1935 
1936 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1937   if (Arg) {
1938     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1939                                Arg.getRegister());
1940   } else
1941     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1942 }
1943 
1944 /// Allocate implicit function VGPR arguments at the end of allocated user
1945 /// arguments.
1946 void SITargetLowering::allocateSpecialInputVGPRs(
1947   CCState &CCInfo, MachineFunction &MF,
1948   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1949   const unsigned Mask = 0x3ff;
1950   ArgDescriptor Arg;
1951 
1952   if (Info.hasWorkItemIDX()) {
1953     Arg = allocateVGPR32Input(CCInfo, Mask);
1954     Info.setWorkItemIDX(Arg);
1955   }
1956 
1957   if (Info.hasWorkItemIDY()) {
1958     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1959     Info.setWorkItemIDY(Arg);
1960   }
1961 
1962   if (Info.hasWorkItemIDZ())
1963     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1964 }
1965 
1966 /// Allocate implicit function VGPR arguments in fixed registers.
1967 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1968   CCState &CCInfo, MachineFunction &MF,
1969   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1970   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1971   if (!Reg)
1972     report_fatal_error("failed to allocated VGPR for implicit arguments");
1973 
1974   const unsigned Mask = 0x3ff;
1975   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1976   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1977   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1978 }
1979 
1980 void SITargetLowering::allocateSpecialInputSGPRs(
1981   CCState &CCInfo,
1982   MachineFunction &MF,
1983   const SIRegisterInfo &TRI,
1984   SIMachineFunctionInfo &Info) const {
1985   auto &ArgInfo = Info.getArgInfo();
1986 
1987   // TODO: Unify handling with private memory pointers.
1988 
1989   if (Info.hasDispatchPtr())
1990     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1991 
1992   if (Info.hasQueuePtr())
1993     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1994 
1995   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1996   // constant offset from the kernarg segment.
1997   if (Info.hasImplicitArgPtr())
1998     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1999 
2000   if (Info.hasDispatchID())
2001     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2002 
2003   // flat_scratch_init is not applicable for non-kernel functions.
2004 
2005   if (Info.hasWorkGroupIDX())
2006     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2007 
2008   if (Info.hasWorkGroupIDY())
2009     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2010 
2011   if (Info.hasWorkGroupIDZ())
2012     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2013 }
2014 
2015 // Allocate special inputs passed in user SGPRs.
2016 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2017                                             MachineFunction &MF,
2018                                             const SIRegisterInfo &TRI,
2019                                             SIMachineFunctionInfo &Info) const {
2020   if (Info.hasImplicitBufferPtr()) {
2021     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2022     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2023     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2024   }
2025 
2026   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2027   if (Info.hasPrivateSegmentBuffer()) {
2028     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2029     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2030     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2031   }
2032 
2033   if (Info.hasDispatchPtr()) {
2034     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2035     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2036     CCInfo.AllocateReg(DispatchPtrReg);
2037   }
2038 
2039   if (Info.hasQueuePtr()) {
2040     Register QueuePtrReg = Info.addQueuePtr(TRI);
2041     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2042     CCInfo.AllocateReg(QueuePtrReg);
2043   }
2044 
2045   if (Info.hasKernargSegmentPtr()) {
2046     MachineRegisterInfo &MRI = MF.getRegInfo();
2047     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2048     CCInfo.AllocateReg(InputPtrReg);
2049 
2050     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2051     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2052   }
2053 
2054   if (Info.hasDispatchID()) {
2055     Register DispatchIDReg = Info.addDispatchID(TRI);
2056     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2057     CCInfo.AllocateReg(DispatchIDReg);
2058   }
2059 
2060   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2061     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2062     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2063     CCInfo.AllocateReg(FlatScratchInitReg);
2064   }
2065 
2066   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2067   // these from the dispatch pointer.
2068 }
2069 
2070 // Allocate special input registers that are initialized per-wave.
2071 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2072                                            MachineFunction &MF,
2073                                            SIMachineFunctionInfo &Info,
2074                                            CallingConv::ID CallConv,
2075                                            bool IsShader) const {
2076   if (Info.hasWorkGroupIDX()) {
2077     Register Reg = Info.addWorkGroupIDX();
2078     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2079     CCInfo.AllocateReg(Reg);
2080   }
2081 
2082   if (Info.hasWorkGroupIDY()) {
2083     Register Reg = Info.addWorkGroupIDY();
2084     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2085     CCInfo.AllocateReg(Reg);
2086   }
2087 
2088   if (Info.hasWorkGroupIDZ()) {
2089     Register Reg = Info.addWorkGroupIDZ();
2090     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2091     CCInfo.AllocateReg(Reg);
2092   }
2093 
2094   if (Info.hasWorkGroupInfo()) {
2095     Register Reg = Info.addWorkGroupInfo();
2096     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2097     CCInfo.AllocateReg(Reg);
2098   }
2099 
2100   if (Info.hasPrivateSegmentWaveByteOffset()) {
2101     // Scratch wave offset passed in system SGPR.
2102     unsigned PrivateSegmentWaveByteOffsetReg;
2103 
2104     if (IsShader) {
2105       PrivateSegmentWaveByteOffsetReg =
2106         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2107 
2108       // This is true if the scratch wave byte offset doesn't have a fixed
2109       // location.
2110       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2111         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2112         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2113       }
2114     } else
2115       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2116 
2117     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2118     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2119   }
2120 }
2121 
2122 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2123                                      MachineFunction &MF,
2124                                      const SIRegisterInfo &TRI,
2125                                      SIMachineFunctionInfo &Info) {
2126   // Now that we've figured out where the scratch register inputs are, see if
2127   // should reserve the arguments and use them directly.
2128   MachineFrameInfo &MFI = MF.getFrameInfo();
2129   bool HasStackObjects = MFI.hasStackObjects();
2130   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2131 
2132   // Record that we know we have non-spill stack objects so we don't need to
2133   // check all stack objects later.
2134   if (HasStackObjects)
2135     Info.setHasNonSpillStackObjects(true);
2136 
2137   // Everything live out of a block is spilled with fast regalloc, so it's
2138   // almost certain that spilling will be required.
2139   if (TM.getOptLevel() == CodeGenOpt::None)
2140     HasStackObjects = true;
2141 
2142   // For now assume stack access is needed in any callee functions, so we need
2143   // the scratch registers to pass in.
2144   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2145 
2146   if (!ST.enableFlatScratch()) {
2147     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2148       // If we have stack objects, we unquestionably need the private buffer
2149       // resource. For the Code Object V2 ABI, this will be the first 4 user
2150       // SGPR inputs. We can reserve those and use them directly.
2151 
2152       Register PrivateSegmentBufferReg =
2153           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2154       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2155     } else {
2156       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2157       // We tentatively reserve the last registers (skipping the last registers
2158       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2159       // we'll replace these with the ones immediately after those which were
2160       // really allocated. In the prologue copies will be inserted from the
2161       // argument to these reserved registers.
2162 
2163       // Without HSA, relocations are used for the scratch pointer and the
2164       // buffer resource setup is always inserted in the prologue. Scratch wave
2165       // offset is still in an input SGPR.
2166       Info.setScratchRSrcReg(ReservedBufferReg);
2167     }
2168   }
2169 
2170   MachineRegisterInfo &MRI = MF.getRegInfo();
2171 
2172   // For entry functions we have to set up the stack pointer if we use it,
2173   // whereas non-entry functions get this "for free". This means there is no
2174   // intrinsic advantage to using S32 over S34 in cases where we do not have
2175   // calls but do need a frame pointer (i.e. if we are requested to have one
2176   // because frame pointer elimination is disabled). To keep things simple we
2177   // only ever use S32 as the call ABI stack pointer, and so using it does not
2178   // imply we need a separate frame pointer.
2179   //
2180   // Try to use s32 as the SP, but move it if it would interfere with input
2181   // arguments. This won't work with calls though.
2182   //
2183   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2184   // registers.
2185   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2186     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2187   } else {
2188     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2189 
2190     if (MFI.hasCalls())
2191       report_fatal_error("call in graphics shader with too many input SGPRs");
2192 
2193     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2194       if (!MRI.isLiveIn(Reg)) {
2195         Info.setStackPtrOffsetReg(Reg);
2196         break;
2197       }
2198     }
2199 
2200     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2201       report_fatal_error("failed to find register for SP");
2202   }
2203 
2204   // hasFP should be accurate for entry functions even before the frame is
2205   // finalized, because it does not rely on the known stack size, only
2206   // properties like whether variable sized objects are present.
2207   if (ST.getFrameLowering()->hasFP(MF)) {
2208     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2209   }
2210 }
2211 
2212 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2213   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2214   return !Info->isEntryFunction();
2215 }
2216 
2217 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2218 
2219 }
2220 
2221 void SITargetLowering::insertCopiesSplitCSR(
2222   MachineBasicBlock *Entry,
2223   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2224   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2225 
2226   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2227   if (!IStart)
2228     return;
2229 
2230   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2231   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2232   MachineBasicBlock::iterator MBBI = Entry->begin();
2233   for (const MCPhysReg *I = IStart; *I; ++I) {
2234     const TargetRegisterClass *RC = nullptr;
2235     if (AMDGPU::SReg_64RegClass.contains(*I))
2236       RC = &AMDGPU::SGPR_64RegClass;
2237     else if (AMDGPU::SReg_32RegClass.contains(*I))
2238       RC = &AMDGPU::SGPR_32RegClass;
2239     else
2240       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2241 
2242     Register NewVR = MRI->createVirtualRegister(RC);
2243     // Create copy from CSR to a virtual register.
2244     Entry->addLiveIn(*I);
2245     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2246       .addReg(*I);
2247 
2248     // Insert the copy-back instructions right before the terminator.
2249     for (auto *Exit : Exits)
2250       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2251               TII->get(TargetOpcode::COPY), *I)
2252         .addReg(NewVR);
2253   }
2254 }
2255 
2256 SDValue SITargetLowering::LowerFormalArguments(
2257     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2258     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2259     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2260   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2261 
2262   MachineFunction &MF = DAG.getMachineFunction();
2263   const Function &Fn = MF.getFunction();
2264   FunctionType *FType = MF.getFunction().getFunctionType();
2265   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2266 
2267   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2268     DiagnosticInfoUnsupported NoGraphicsHSA(
2269         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2270     DAG.getContext()->diagnose(NoGraphicsHSA);
2271     return DAG.getEntryNode();
2272   }
2273 
2274   Info->allocateModuleLDSGlobal(Fn.getParent());
2275 
2276   SmallVector<ISD::InputArg, 16> Splits;
2277   SmallVector<CCValAssign, 16> ArgLocs;
2278   BitVector Skipped(Ins.size());
2279   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2280                  *DAG.getContext());
2281 
2282   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2283   bool IsKernel = AMDGPU::isKernel(CallConv);
2284   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2285 
2286   if (IsGraphics) {
2287     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2288            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2289            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2290            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2291            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2292            !Info->hasWorkItemIDZ());
2293   }
2294 
2295   if (CallConv == CallingConv::AMDGPU_PS) {
2296     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2297 
2298     // At least one interpolation mode must be enabled or else the GPU will
2299     // hang.
2300     //
2301     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2302     // set PSInputAddr, the user wants to enable some bits after the compilation
2303     // based on run-time states. Since we can't know what the final PSInputEna
2304     // will look like, so we shouldn't do anything here and the user should take
2305     // responsibility for the correct programming.
2306     //
2307     // Otherwise, the following restrictions apply:
2308     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2309     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2310     //   enabled too.
2311     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2312         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2313       CCInfo.AllocateReg(AMDGPU::VGPR0);
2314       CCInfo.AllocateReg(AMDGPU::VGPR1);
2315       Info->markPSInputAllocated(0);
2316       Info->markPSInputEnabled(0);
2317     }
2318     if (Subtarget->isAmdPalOS()) {
2319       // For isAmdPalOS, the user does not enable some bits after compilation
2320       // based on run-time states; the register values being generated here are
2321       // the final ones set in hardware. Therefore we need to apply the
2322       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2323       // a bit is set in PSInputAddr but not PSInputEnable is where the
2324       // frontend set up an input arg for a particular interpolation mode, but
2325       // nothing uses that input arg. Really we should have an earlier pass
2326       // that removes such an arg.)
2327       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2328       if ((PsInputBits & 0x7F) == 0 ||
2329           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2330         Info->markPSInputEnabled(
2331             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2332     }
2333   } else if (IsKernel) {
2334     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2335   } else {
2336     Splits.append(Ins.begin(), Ins.end());
2337   }
2338 
2339   if (IsEntryFunc) {
2340     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2341     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2342   } else {
2343     // For the fixed ABI, pass workitem IDs in the last argument register.
2344     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2345       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2346   }
2347 
2348   if (IsKernel) {
2349     analyzeFormalArgumentsCompute(CCInfo, Ins);
2350   } else {
2351     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2352     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2353   }
2354 
2355   SmallVector<SDValue, 16> Chains;
2356 
2357   // FIXME: This is the minimum kernel argument alignment. We should improve
2358   // this to the maximum alignment of the arguments.
2359   //
2360   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2361   // kern arg offset.
2362   const Align KernelArgBaseAlign = Align(16);
2363 
2364   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2365     const ISD::InputArg &Arg = Ins[i];
2366     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2367       InVals.push_back(DAG.getUNDEF(Arg.VT));
2368       continue;
2369     }
2370 
2371     CCValAssign &VA = ArgLocs[ArgIdx++];
2372     MVT VT = VA.getLocVT();
2373 
2374     if (IsEntryFunc && VA.isMemLoc()) {
2375       VT = Ins[i].VT;
2376       EVT MemVT = VA.getLocVT();
2377 
2378       const uint64_t Offset = VA.getLocMemOffset();
2379       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2380 
2381       if (Arg.Flags.isByRef()) {
2382         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2383 
2384         const GCNTargetMachine &TM =
2385             static_cast<const GCNTargetMachine &>(getTargetMachine());
2386         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2387                                     Arg.Flags.getPointerAddrSpace())) {
2388           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2389                                      Arg.Flags.getPointerAddrSpace());
2390         }
2391 
2392         InVals.push_back(Ptr);
2393         continue;
2394       }
2395 
2396       SDValue Arg = lowerKernargMemParameter(
2397         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2398       Chains.push_back(Arg.getValue(1));
2399 
2400       auto *ParamTy =
2401         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2402       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2403           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2404                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2405         // On SI local pointers are just offsets into LDS, so they are always
2406         // less than 16-bits.  On CI and newer they could potentially be
2407         // real pointers, so we can't guarantee their size.
2408         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2409                           DAG.getValueType(MVT::i16));
2410       }
2411 
2412       InVals.push_back(Arg);
2413       continue;
2414     } else if (!IsEntryFunc && VA.isMemLoc()) {
2415       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2416       InVals.push_back(Val);
2417       if (!Arg.Flags.isByVal())
2418         Chains.push_back(Val.getValue(1));
2419       continue;
2420     }
2421 
2422     assert(VA.isRegLoc() && "Parameter must be in a register!");
2423 
2424     Register Reg = VA.getLocReg();
2425     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2426     EVT ValVT = VA.getValVT();
2427 
2428     Reg = MF.addLiveIn(Reg, RC);
2429     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2430 
2431     if (Arg.Flags.isSRet()) {
2432       // The return object should be reasonably addressable.
2433 
2434       // FIXME: This helps when the return is a real sret. If it is a
2435       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2436       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2437       unsigned NumBits
2438         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2439       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2440         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2441     }
2442 
2443     // If this is an 8 or 16-bit value, it is really passed promoted
2444     // to 32 bits. Insert an assert[sz]ext to capture this, then
2445     // truncate to the right size.
2446     switch (VA.getLocInfo()) {
2447     case CCValAssign::Full:
2448       break;
2449     case CCValAssign::BCvt:
2450       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2451       break;
2452     case CCValAssign::SExt:
2453       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2454                         DAG.getValueType(ValVT));
2455       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2456       break;
2457     case CCValAssign::ZExt:
2458       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2459                         DAG.getValueType(ValVT));
2460       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2461       break;
2462     case CCValAssign::AExt:
2463       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2464       break;
2465     default:
2466       llvm_unreachable("Unknown loc info!");
2467     }
2468 
2469     InVals.push_back(Val);
2470   }
2471 
2472   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2473     // Special inputs come after user arguments.
2474     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2475   }
2476 
2477   // Start adding system SGPRs.
2478   if (IsEntryFunc) {
2479     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2480   } else {
2481     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2482     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2483   }
2484 
2485   auto &ArgUsageInfo =
2486     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2487   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2488 
2489   unsigned StackArgSize = CCInfo.getNextStackOffset();
2490   Info->setBytesInStackArgArea(StackArgSize);
2491 
2492   return Chains.empty() ? Chain :
2493     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2494 }
2495 
2496 // TODO: If return values can't fit in registers, we should return as many as
2497 // possible in registers before passing on stack.
2498 bool SITargetLowering::CanLowerReturn(
2499   CallingConv::ID CallConv,
2500   MachineFunction &MF, bool IsVarArg,
2501   const SmallVectorImpl<ISD::OutputArg> &Outs,
2502   LLVMContext &Context) const {
2503   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2504   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2505   // for shaders. Vector types should be explicitly handled by CC.
2506   if (AMDGPU::isEntryFunctionCC(CallConv))
2507     return true;
2508 
2509   SmallVector<CCValAssign, 16> RVLocs;
2510   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2511   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2512 }
2513 
2514 SDValue
2515 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2516                               bool isVarArg,
2517                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2518                               const SmallVectorImpl<SDValue> &OutVals,
2519                               const SDLoc &DL, SelectionDAG &DAG) const {
2520   MachineFunction &MF = DAG.getMachineFunction();
2521   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2522 
2523   if (AMDGPU::isKernel(CallConv)) {
2524     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2525                                              OutVals, DL, DAG);
2526   }
2527 
2528   bool IsShader = AMDGPU::isShader(CallConv);
2529 
2530   Info->setIfReturnsVoid(Outs.empty());
2531   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2532 
2533   // CCValAssign - represent the assignment of the return value to a location.
2534   SmallVector<CCValAssign, 48> RVLocs;
2535   SmallVector<ISD::OutputArg, 48> Splits;
2536 
2537   // CCState - Info about the registers and stack slots.
2538   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2539                  *DAG.getContext());
2540 
2541   // Analyze outgoing return values.
2542   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2543 
2544   SDValue Flag;
2545   SmallVector<SDValue, 48> RetOps;
2546   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2547 
2548   // Add return address for callable functions.
2549   if (!Info->isEntryFunction()) {
2550     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2551     SDValue ReturnAddrReg = CreateLiveInRegister(
2552       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2553 
2554     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2555         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2556         MVT::i64);
2557     Chain =
2558         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2559     Flag = Chain.getValue(1);
2560     RetOps.push_back(ReturnAddrVirtualReg);
2561   }
2562 
2563   // Copy the result values into the output registers.
2564   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2565        ++I, ++RealRVLocIdx) {
2566     CCValAssign &VA = RVLocs[I];
2567     assert(VA.isRegLoc() && "Can only return in registers!");
2568     // TODO: Partially return in registers if return values don't fit.
2569     SDValue Arg = OutVals[RealRVLocIdx];
2570 
2571     // Copied from other backends.
2572     switch (VA.getLocInfo()) {
2573     case CCValAssign::Full:
2574       break;
2575     case CCValAssign::BCvt:
2576       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2577       break;
2578     case CCValAssign::SExt:
2579       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2580       break;
2581     case CCValAssign::ZExt:
2582       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2583       break;
2584     case CCValAssign::AExt:
2585       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2586       break;
2587     default:
2588       llvm_unreachable("Unknown loc info!");
2589     }
2590 
2591     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2592     Flag = Chain.getValue(1);
2593     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2594   }
2595 
2596   // FIXME: Does sret work properly?
2597   if (!Info->isEntryFunction()) {
2598     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2599     const MCPhysReg *I =
2600       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2601     if (I) {
2602       for (; *I; ++I) {
2603         if (AMDGPU::SReg_64RegClass.contains(*I))
2604           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2605         else if (AMDGPU::SReg_32RegClass.contains(*I))
2606           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2607         else
2608           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2609       }
2610     }
2611   }
2612 
2613   // Update chain and glue.
2614   RetOps[0] = Chain;
2615   if (Flag.getNode())
2616     RetOps.push_back(Flag);
2617 
2618   unsigned Opc = AMDGPUISD::ENDPGM;
2619   if (!IsWaveEnd)
2620     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2621   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2622 }
2623 
2624 SDValue SITargetLowering::LowerCallResult(
2625     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2626     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2627     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2628     SDValue ThisVal) const {
2629   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2630 
2631   // Assign locations to each value returned by this call.
2632   SmallVector<CCValAssign, 16> RVLocs;
2633   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2634                  *DAG.getContext());
2635   CCInfo.AnalyzeCallResult(Ins, RetCC);
2636 
2637   // Copy all of the result registers out of their specified physreg.
2638   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2639     CCValAssign VA = RVLocs[i];
2640     SDValue Val;
2641 
2642     if (VA.isRegLoc()) {
2643       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2644       Chain = Val.getValue(1);
2645       InFlag = Val.getValue(2);
2646     } else if (VA.isMemLoc()) {
2647       report_fatal_error("TODO: return values in memory");
2648     } else
2649       llvm_unreachable("unknown argument location type");
2650 
2651     switch (VA.getLocInfo()) {
2652     case CCValAssign::Full:
2653       break;
2654     case CCValAssign::BCvt:
2655       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2656       break;
2657     case CCValAssign::ZExt:
2658       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2659                         DAG.getValueType(VA.getValVT()));
2660       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2661       break;
2662     case CCValAssign::SExt:
2663       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2664                         DAG.getValueType(VA.getValVT()));
2665       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2666       break;
2667     case CCValAssign::AExt:
2668       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2669       break;
2670     default:
2671       llvm_unreachable("Unknown loc info!");
2672     }
2673 
2674     InVals.push_back(Val);
2675   }
2676 
2677   return Chain;
2678 }
2679 
2680 // Add code to pass special inputs required depending on used features separate
2681 // from the explicit user arguments present in the IR.
2682 void SITargetLowering::passSpecialInputs(
2683     CallLoweringInfo &CLI,
2684     CCState &CCInfo,
2685     const SIMachineFunctionInfo &Info,
2686     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2687     SmallVectorImpl<SDValue> &MemOpChains,
2688     SDValue Chain) const {
2689   // If we don't have a call site, this was a call inserted by
2690   // legalization. These can never use special inputs.
2691   if (!CLI.CB)
2692     return;
2693 
2694   SelectionDAG &DAG = CLI.DAG;
2695   const SDLoc &DL = CLI.DL;
2696 
2697   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2698   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2699 
2700   const AMDGPUFunctionArgInfo *CalleeArgInfo
2701     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2702   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2703     auto &ArgUsageInfo =
2704       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2705     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2706   }
2707 
2708   // TODO: Unify with private memory register handling. This is complicated by
2709   // the fact that at least in kernels, the input argument is not necessarily
2710   // in the same location as the input.
2711   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2712     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2713     AMDGPUFunctionArgInfo::QUEUE_PTR,
2714     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2715     AMDGPUFunctionArgInfo::DISPATCH_ID,
2716     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2717     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2718     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2719   };
2720 
2721   for (auto InputID : InputRegs) {
2722     const ArgDescriptor *OutgoingArg;
2723     const TargetRegisterClass *ArgRC;
2724     LLT ArgTy;
2725 
2726     std::tie(OutgoingArg, ArgRC, ArgTy) =
2727         CalleeArgInfo->getPreloadedValue(InputID);
2728     if (!OutgoingArg)
2729       continue;
2730 
2731     const ArgDescriptor *IncomingArg;
2732     const TargetRegisterClass *IncomingArgRC;
2733     LLT Ty;
2734     std::tie(IncomingArg, IncomingArgRC, Ty) =
2735         CallerArgInfo.getPreloadedValue(InputID);
2736     assert(IncomingArgRC == ArgRC);
2737 
2738     // All special arguments are ints for now.
2739     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2740     SDValue InputReg;
2741 
2742     if (IncomingArg) {
2743       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2744     } else {
2745       // The implicit arg ptr is special because it doesn't have a corresponding
2746       // input for kernels, and is computed from the kernarg segment pointer.
2747       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2748       InputReg = getImplicitArgPtr(DAG, DL);
2749     }
2750 
2751     if (OutgoingArg->isRegister()) {
2752       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2753       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2754         report_fatal_error("failed to allocate implicit input argument");
2755     } else {
2756       unsigned SpecialArgOffset =
2757           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2758       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2759                                               SpecialArgOffset);
2760       MemOpChains.push_back(ArgStore);
2761     }
2762   }
2763 
2764   // Pack workitem IDs into a single register or pass it as is if already
2765   // packed.
2766   const ArgDescriptor *OutgoingArg;
2767   const TargetRegisterClass *ArgRC;
2768   LLT Ty;
2769 
2770   std::tie(OutgoingArg, ArgRC, Ty) =
2771       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2772   if (!OutgoingArg)
2773     std::tie(OutgoingArg, ArgRC, Ty) =
2774         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2775   if (!OutgoingArg)
2776     std::tie(OutgoingArg, ArgRC, Ty) =
2777         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2778   if (!OutgoingArg)
2779     return;
2780 
2781   const ArgDescriptor *IncomingArgX = std::get<0>(
2782       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2783   const ArgDescriptor *IncomingArgY = std::get<0>(
2784       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2785   const ArgDescriptor *IncomingArgZ = std::get<0>(
2786       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2787 
2788   SDValue InputReg;
2789   SDLoc SL;
2790 
2791   // If incoming ids are not packed we need to pack them.
2792   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2793     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2794 
2795   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2796     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2797     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2798                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2799     InputReg = InputReg.getNode() ?
2800                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2801   }
2802 
2803   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2804     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2805     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2806                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2807     InputReg = InputReg.getNode() ?
2808                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2809   }
2810 
2811   if (!InputReg.getNode()) {
2812     // Workitem ids are already packed, any of present incoming arguments
2813     // will carry all required fields.
2814     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2815       IncomingArgX ? *IncomingArgX :
2816       IncomingArgY ? *IncomingArgY :
2817                      *IncomingArgZ, ~0u);
2818     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2819   }
2820 
2821   if (OutgoingArg->isRegister()) {
2822     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2823     CCInfo.AllocateReg(OutgoingArg->getRegister());
2824   } else {
2825     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2826     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2827                                             SpecialArgOffset);
2828     MemOpChains.push_back(ArgStore);
2829   }
2830 }
2831 
2832 static bool canGuaranteeTCO(CallingConv::ID CC) {
2833   return CC == CallingConv::Fast;
2834 }
2835 
2836 /// Return true if we might ever do TCO for calls with this calling convention.
2837 static bool mayTailCallThisCC(CallingConv::ID CC) {
2838   switch (CC) {
2839   case CallingConv::C:
2840   case CallingConv::AMDGPU_Gfx:
2841     return true;
2842   default:
2843     return canGuaranteeTCO(CC);
2844   }
2845 }
2846 
2847 bool SITargetLowering::isEligibleForTailCallOptimization(
2848     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2849     const SmallVectorImpl<ISD::OutputArg> &Outs,
2850     const SmallVectorImpl<SDValue> &OutVals,
2851     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2852   if (!mayTailCallThisCC(CalleeCC))
2853     return false;
2854 
2855   // For a divergent call target, we need to do a waterfall loop over the
2856   // possible callees which precludes us from using a simple jump.
2857   if (Callee->isDivergent())
2858     return false;
2859 
2860   MachineFunction &MF = DAG.getMachineFunction();
2861   const Function &CallerF = MF.getFunction();
2862   CallingConv::ID CallerCC = CallerF.getCallingConv();
2863   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2864   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2865 
2866   // Kernels aren't callable, and don't have a live in return address so it
2867   // doesn't make sense to do a tail call with entry functions.
2868   if (!CallerPreserved)
2869     return false;
2870 
2871   bool CCMatch = CallerCC == CalleeCC;
2872 
2873   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2874     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2875       return true;
2876     return false;
2877   }
2878 
2879   // TODO: Can we handle var args?
2880   if (IsVarArg)
2881     return false;
2882 
2883   for (const Argument &Arg : CallerF.args()) {
2884     if (Arg.hasByValAttr())
2885       return false;
2886   }
2887 
2888   LLVMContext &Ctx = *DAG.getContext();
2889 
2890   // Check that the call results are passed in the same way.
2891   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2892                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2893                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2894     return false;
2895 
2896   // The callee has to preserve all registers the caller needs to preserve.
2897   if (!CCMatch) {
2898     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2899     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2900       return false;
2901   }
2902 
2903   // Nothing more to check if the callee is taking no arguments.
2904   if (Outs.empty())
2905     return true;
2906 
2907   SmallVector<CCValAssign, 16> ArgLocs;
2908   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2909 
2910   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2911 
2912   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2913   // If the stack arguments for this call do not fit into our own save area then
2914   // the call cannot be made tail.
2915   // TODO: Is this really necessary?
2916   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2917     return false;
2918 
2919   const MachineRegisterInfo &MRI = MF.getRegInfo();
2920   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2921 }
2922 
2923 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2924   if (!CI->isTailCall())
2925     return false;
2926 
2927   const Function *ParentFn = CI->getParent()->getParent();
2928   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2929     return false;
2930   return true;
2931 }
2932 
2933 // The wave scratch offset register is used as the global base pointer.
2934 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2935                                     SmallVectorImpl<SDValue> &InVals) const {
2936   SelectionDAG &DAG = CLI.DAG;
2937   const SDLoc &DL = CLI.DL;
2938   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2939   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2940   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2941   SDValue Chain = CLI.Chain;
2942   SDValue Callee = CLI.Callee;
2943   bool &IsTailCall = CLI.IsTailCall;
2944   CallingConv::ID CallConv = CLI.CallConv;
2945   bool IsVarArg = CLI.IsVarArg;
2946   bool IsSibCall = false;
2947   bool IsThisReturn = false;
2948   MachineFunction &MF = DAG.getMachineFunction();
2949 
2950   if (Callee.isUndef() || isNullConstant(Callee)) {
2951     if (!CLI.IsTailCall) {
2952       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2953         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2954     }
2955 
2956     return Chain;
2957   }
2958 
2959   if (IsVarArg) {
2960     return lowerUnhandledCall(CLI, InVals,
2961                               "unsupported call to variadic function ");
2962   }
2963 
2964   if (!CLI.CB)
2965     report_fatal_error("unsupported libcall legalization");
2966 
2967   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2968     return lowerUnhandledCall(CLI, InVals,
2969                               "unsupported required tail call to function ");
2970   }
2971 
2972   if (AMDGPU::isShader(CallConv)) {
2973     // Note the issue is with the CC of the called function, not of the call
2974     // itself.
2975     return lowerUnhandledCall(CLI, InVals,
2976                               "unsupported call to a shader function ");
2977   }
2978 
2979   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2980       CallConv != CallingConv::AMDGPU_Gfx) {
2981     // Only allow calls with specific calling conventions.
2982     return lowerUnhandledCall(CLI, InVals,
2983                               "unsupported calling convention for call from "
2984                               "graphics shader of function ");
2985   }
2986 
2987   if (IsTailCall) {
2988     IsTailCall = isEligibleForTailCallOptimization(
2989       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2990     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2991       report_fatal_error("failed to perform tail call elimination on a call "
2992                          "site marked musttail");
2993     }
2994 
2995     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2996 
2997     // A sibling call is one where we're under the usual C ABI and not planning
2998     // to change that but can still do a tail call:
2999     if (!TailCallOpt && IsTailCall)
3000       IsSibCall = true;
3001 
3002     if (IsTailCall)
3003       ++NumTailCalls;
3004   }
3005 
3006   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3007   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3008   SmallVector<SDValue, 8> MemOpChains;
3009 
3010   // Analyze operands of the call, assigning locations to each operand.
3011   SmallVector<CCValAssign, 16> ArgLocs;
3012   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3013   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3014 
3015   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3016       CallConv != CallingConv::AMDGPU_Gfx) {
3017     // With a fixed ABI, allocate fixed registers before user arguments.
3018     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3019   }
3020 
3021   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3022 
3023   // Get a count of how many bytes are to be pushed on the stack.
3024   unsigned NumBytes = CCInfo.getNextStackOffset();
3025 
3026   if (IsSibCall) {
3027     // Since we're not changing the ABI to make this a tail call, the memory
3028     // operands are already available in the caller's incoming argument space.
3029     NumBytes = 0;
3030   }
3031 
3032   // FPDiff is the byte offset of the call's argument area from the callee's.
3033   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3034   // by this amount for a tail call. In a sibling call it must be 0 because the
3035   // caller will deallocate the entire stack and the callee still expects its
3036   // arguments to begin at SP+0. Completely unused for non-tail calls.
3037   int32_t FPDiff = 0;
3038   MachineFrameInfo &MFI = MF.getFrameInfo();
3039 
3040   // Adjust the stack pointer for the new arguments...
3041   // These operations are automatically eliminated by the prolog/epilog pass
3042   if (!IsSibCall) {
3043     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3044 
3045     if (!Subtarget->enableFlatScratch()) {
3046       SmallVector<SDValue, 4> CopyFromChains;
3047 
3048       // In the HSA case, this should be an identity copy.
3049       SDValue ScratchRSrcReg
3050         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3051       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3052       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3053       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3054     }
3055   }
3056 
3057   MVT PtrVT = MVT::i32;
3058 
3059   // Walk the register/memloc assignments, inserting copies/loads.
3060   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3061     CCValAssign &VA = ArgLocs[i];
3062     SDValue Arg = OutVals[i];
3063 
3064     // Promote the value if needed.
3065     switch (VA.getLocInfo()) {
3066     case CCValAssign::Full:
3067       break;
3068     case CCValAssign::BCvt:
3069       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3070       break;
3071     case CCValAssign::ZExt:
3072       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3073       break;
3074     case CCValAssign::SExt:
3075       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3076       break;
3077     case CCValAssign::AExt:
3078       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3079       break;
3080     case CCValAssign::FPExt:
3081       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3082       break;
3083     default:
3084       llvm_unreachable("Unknown loc info!");
3085     }
3086 
3087     if (VA.isRegLoc()) {
3088       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3089     } else {
3090       assert(VA.isMemLoc());
3091 
3092       SDValue DstAddr;
3093       MachinePointerInfo DstInfo;
3094 
3095       unsigned LocMemOffset = VA.getLocMemOffset();
3096       int32_t Offset = LocMemOffset;
3097 
3098       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3099       MaybeAlign Alignment;
3100 
3101       if (IsTailCall) {
3102         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3103         unsigned OpSize = Flags.isByVal() ?
3104           Flags.getByValSize() : VA.getValVT().getStoreSize();
3105 
3106         // FIXME: We can have better than the minimum byval required alignment.
3107         Alignment =
3108             Flags.isByVal()
3109                 ? Flags.getNonZeroByValAlign()
3110                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3111 
3112         Offset = Offset + FPDiff;
3113         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3114 
3115         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3116         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3117 
3118         // Make sure any stack arguments overlapping with where we're storing
3119         // are loaded before this eventual operation. Otherwise they'll be
3120         // clobbered.
3121 
3122         // FIXME: Why is this really necessary? This seems to just result in a
3123         // lot of code to copy the stack and write them back to the same
3124         // locations, which are supposed to be immutable?
3125         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3126       } else {
3127         // Stores to the argument stack area are relative to the stack pointer.
3128         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3129                                         MVT::i32);
3130         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3131         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3132         Alignment =
3133             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3134       }
3135 
3136       if (Outs[i].Flags.isByVal()) {
3137         SDValue SizeNode =
3138             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3139         SDValue Cpy =
3140             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3141                           Outs[i].Flags.getNonZeroByValAlign(),
3142                           /*isVol = */ false, /*AlwaysInline = */ true,
3143                           /*isTailCall = */ false, DstInfo,
3144                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3145 
3146         MemOpChains.push_back(Cpy);
3147       } else {
3148         SDValue Store =
3149             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3150         MemOpChains.push_back(Store);
3151       }
3152     }
3153   }
3154 
3155   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3156       CallConv != CallingConv::AMDGPU_Gfx) {
3157     // Copy special input registers after user input arguments.
3158     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3159   }
3160 
3161   if (!MemOpChains.empty())
3162     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3163 
3164   // Build a sequence of copy-to-reg nodes chained together with token chain
3165   // and flag operands which copy the outgoing args into the appropriate regs.
3166   SDValue InFlag;
3167   for (auto &RegToPass : RegsToPass) {
3168     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3169                              RegToPass.second, InFlag);
3170     InFlag = Chain.getValue(1);
3171   }
3172 
3173 
3174   SDValue PhysReturnAddrReg;
3175   if (IsTailCall) {
3176     // Since the return is being combined with the call, we need to pass on the
3177     // return address.
3178 
3179     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3180     SDValue ReturnAddrReg = CreateLiveInRegister(
3181       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3182 
3183     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3184                                         MVT::i64);
3185     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3186     InFlag = Chain.getValue(1);
3187   }
3188 
3189   // We don't usually want to end the call-sequence here because we would tidy
3190   // the frame up *after* the call, however in the ABI-changing tail-call case
3191   // we've carefully laid out the parameters so that when sp is reset they'll be
3192   // in the correct location.
3193   if (IsTailCall && !IsSibCall) {
3194     Chain = DAG.getCALLSEQ_END(Chain,
3195                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3196                                DAG.getTargetConstant(0, DL, MVT::i32),
3197                                InFlag, DL);
3198     InFlag = Chain.getValue(1);
3199   }
3200 
3201   std::vector<SDValue> Ops;
3202   Ops.push_back(Chain);
3203   Ops.push_back(Callee);
3204   // Add a redundant copy of the callee global which will not be legalized, as
3205   // we need direct access to the callee later.
3206   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3207     const GlobalValue *GV = GSD->getGlobal();
3208     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3209   } else {
3210     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3211   }
3212 
3213   if (IsTailCall) {
3214     // Each tail call may have to adjust the stack by a different amount, so
3215     // this information must travel along with the operation for eventual
3216     // consumption by emitEpilogue.
3217     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3218 
3219     Ops.push_back(PhysReturnAddrReg);
3220   }
3221 
3222   // Add argument registers to the end of the list so that they are known live
3223   // into the call.
3224   for (auto &RegToPass : RegsToPass) {
3225     Ops.push_back(DAG.getRegister(RegToPass.first,
3226                                   RegToPass.second.getValueType()));
3227   }
3228 
3229   // Add a register mask operand representing the call-preserved registers.
3230 
3231   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3232   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3233   assert(Mask && "Missing call preserved mask for calling convention");
3234   Ops.push_back(DAG.getRegisterMask(Mask));
3235 
3236   if (InFlag.getNode())
3237     Ops.push_back(InFlag);
3238 
3239   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3240 
3241   // If we're doing a tall call, use a TC_RETURN here rather than an
3242   // actual call instruction.
3243   if (IsTailCall) {
3244     MFI.setHasTailCall();
3245     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3246   }
3247 
3248   // Returns a chain and a flag for retval copy to use.
3249   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3250   Chain = Call.getValue(0);
3251   InFlag = Call.getValue(1);
3252 
3253   uint64_t CalleePopBytes = NumBytes;
3254   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3255                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3256                              InFlag, DL);
3257   if (!Ins.empty())
3258     InFlag = Chain.getValue(1);
3259 
3260   // Handle result values, copying them out of physregs into vregs that we
3261   // return.
3262   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3263                          InVals, IsThisReturn,
3264                          IsThisReturn ? OutVals[0] : SDValue());
3265 }
3266 
3267 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3268 // except for applying the wave size scale to the increment amount.
3269 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3270     SDValue Op, SelectionDAG &DAG) const {
3271   const MachineFunction &MF = DAG.getMachineFunction();
3272   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3273 
3274   SDLoc dl(Op);
3275   EVT VT = Op.getValueType();
3276   SDValue Tmp1 = Op;
3277   SDValue Tmp2 = Op.getValue(1);
3278   SDValue Tmp3 = Op.getOperand(2);
3279   SDValue Chain = Tmp1.getOperand(0);
3280 
3281   Register SPReg = Info->getStackPtrOffsetReg();
3282 
3283   // Chain the dynamic stack allocation so that it doesn't modify the stack
3284   // pointer when other instructions are using the stack.
3285   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3286 
3287   SDValue Size  = Tmp2.getOperand(1);
3288   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3289   Chain = SP.getValue(1);
3290   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3291   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3292   const TargetFrameLowering *TFL = ST.getFrameLowering();
3293   unsigned Opc =
3294     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3295     ISD::ADD : ISD::SUB;
3296 
3297   SDValue ScaledSize = DAG.getNode(
3298       ISD::SHL, dl, VT, Size,
3299       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3300 
3301   Align StackAlign = TFL->getStackAlign();
3302   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3303   if (Alignment && *Alignment > StackAlign) {
3304     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3305                        DAG.getConstant(-(uint64_t)Alignment->value()
3306                                            << ST.getWavefrontSizeLog2(),
3307                                        dl, VT));
3308   }
3309 
3310   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3311   Tmp2 = DAG.getCALLSEQ_END(
3312       Chain, DAG.getIntPtrConstant(0, dl, true),
3313       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3314 
3315   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3316 }
3317 
3318 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3319                                                   SelectionDAG &DAG) const {
3320   // We only handle constant sizes here to allow non-entry block, static sized
3321   // allocas. A truly dynamic value is more difficult to support because we
3322   // don't know if the size value is uniform or not. If the size isn't uniform,
3323   // we would need to do a wave reduction to get the maximum size to know how
3324   // much to increment the uniform stack pointer.
3325   SDValue Size = Op.getOperand(1);
3326   if (isa<ConstantSDNode>(Size))
3327       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3328 
3329   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3330 }
3331 
3332 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3333                                              const MachineFunction &MF) const {
3334   Register Reg = StringSwitch<Register>(RegName)
3335     .Case("m0", AMDGPU::M0)
3336     .Case("exec", AMDGPU::EXEC)
3337     .Case("exec_lo", AMDGPU::EXEC_LO)
3338     .Case("exec_hi", AMDGPU::EXEC_HI)
3339     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3340     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3341     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3342     .Default(Register());
3343 
3344   if (Reg == AMDGPU::NoRegister) {
3345     report_fatal_error(Twine("invalid register name \""
3346                              + StringRef(RegName)  + "\"."));
3347 
3348   }
3349 
3350   if (!Subtarget->hasFlatScrRegister() &&
3351        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3352     report_fatal_error(Twine("invalid register \""
3353                              + StringRef(RegName)  + "\" for subtarget."));
3354   }
3355 
3356   switch (Reg) {
3357   case AMDGPU::M0:
3358   case AMDGPU::EXEC_LO:
3359   case AMDGPU::EXEC_HI:
3360   case AMDGPU::FLAT_SCR_LO:
3361   case AMDGPU::FLAT_SCR_HI:
3362     if (VT.getSizeInBits() == 32)
3363       return Reg;
3364     break;
3365   case AMDGPU::EXEC:
3366   case AMDGPU::FLAT_SCR:
3367     if (VT.getSizeInBits() == 64)
3368       return Reg;
3369     break;
3370   default:
3371     llvm_unreachable("missing register type checking");
3372   }
3373 
3374   report_fatal_error(Twine("invalid type for register \""
3375                            + StringRef(RegName) + "\"."));
3376 }
3377 
3378 // If kill is not the last instruction, split the block so kill is always a
3379 // proper terminator.
3380 MachineBasicBlock *
3381 SITargetLowering::splitKillBlock(MachineInstr &MI,
3382                                  MachineBasicBlock *BB) const {
3383   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3384   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3385   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3386   return SplitBB;
3387 }
3388 
3389 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3390 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3391 // be the first instruction in the remainder block.
3392 //
3393 /// \returns { LoopBody, Remainder }
3394 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3395 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3396   MachineFunction *MF = MBB.getParent();
3397   MachineBasicBlock::iterator I(&MI);
3398 
3399   // To insert the loop we need to split the block. Move everything after this
3400   // point to a new block, and insert a new empty block between the two.
3401   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3402   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3403   MachineFunction::iterator MBBI(MBB);
3404   ++MBBI;
3405 
3406   MF->insert(MBBI, LoopBB);
3407   MF->insert(MBBI, RemainderBB);
3408 
3409   LoopBB->addSuccessor(LoopBB);
3410   LoopBB->addSuccessor(RemainderBB);
3411 
3412   // Move the rest of the block into a new block.
3413   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3414 
3415   if (InstInLoop) {
3416     auto Next = std::next(I);
3417 
3418     // Move instruction to loop body.
3419     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3420 
3421     // Move the rest of the block.
3422     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3423   } else {
3424     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3425   }
3426 
3427   MBB.addSuccessor(LoopBB);
3428 
3429   return std::make_pair(LoopBB, RemainderBB);
3430 }
3431 
3432 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3433 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3434   MachineBasicBlock *MBB = MI.getParent();
3435   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3436   auto I = MI.getIterator();
3437   auto E = std::next(I);
3438 
3439   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3440     .addImm(0);
3441 
3442   MIBundleBuilder Bundler(*MBB, I, E);
3443   finalizeBundle(*MBB, Bundler.begin());
3444 }
3445 
3446 MachineBasicBlock *
3447 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3448                                          MachineBasicBlock *BB) const {
3449   const DebugLoc &DL = MI.getDebugLoc();
3450 
3451   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3452 
3453   MachineBasicBlock *LoopBB;
3454   MachineBasicBlock *RemainderBB;
3455   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3456 
3457   // Apparently kill flags are only valid if the def is in the same block?
3458   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3459     Src->setIsKill(false);
3460 
3461   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3462 
3463   MachineBasicBlock::iterator I = LoopBB->end();
3464 
3465   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3466     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3467 
3468   // Clear TRAP_STS.MEM_VIOL
3469   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3470     .addImm(0)
3471     .addImm(EncodedReg);
3472 
3473   bundleInstWithWaitcnt(MI);
3474 
3475   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3476 
3477   // Load and check TRAP_STS.MEM_VIOL
3478   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3479     .addImm(EncodedReg);
3480 
3481   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3482   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3483     .addReg(Reg, RegState::Kill)
3484     .addImm(0);
3485   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3486     .addMBB(LoopBB);
3487 
3488   return RemainderBB;
3489 }
3490 
3491 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3492 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3493 // will only do one iteration. In the worst case, this will loop 64 times.
3494 //
3495 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3496 static MachineBasicBlock::iterator
3497 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3498                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3499                        const DebugLoc &DL, const MachineOperand &Idx,
3500                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3501                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3502                        Register &SGPRIdxReg) {
3503 
3504   MachineFunction *MF = OrigBB.getParent();
3505   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3506   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3507   MachineBasicBlock::iterator I = LoopBB.begin();
3508 
3509   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3510   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3511   Register NewExec = MRI.createVirtualRegister(BoolRC);
3512   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3513   Register CondReg = MRI.createVirtualRegister(BoolRC);
3514 
3515   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3516     .addReg(InitReg)
3517     .addMBB(&OrigBB)
3518     .addReg(ResultReg)
3519     .addMBB(&LoopBB);
3520 
3521   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3522     .addReg(InitSaveExecReg)
3523     .addMBB(&OrigBB)
3524     .addReg(NewExec)
3525     .addMBB(&LoopBB);
3526 
3527   // Read the next variant <- also loop target.
3528   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3529       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3530 
3531   // Compare the just read M0 value to all possible Idx values.
3532   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3533       .addReg(CurrentIdxReg)
3534       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3535 
3536   // Update EXEC, save the original EXEC value to VCC.
3537   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3538                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3539           NewExec)
3540     .addReg(CondReg, RegState::Kill);
3541 
3542   MRI.setSimpleHint(NewExec, CondReg);
3543 
3544   if (UseGPRIdxMode) {
3545     if (Offset == 0) {
3546       SGPRIdxReg = CurrentIdxReg;
3547     } else {
3548       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3549       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3550           .addReg(CurrentIdxReg, RegState::Kill)
3551           .addImm(Offset);
3552     }
3553   } else {
3554     // Move index from VCC into M0
3555     if (Offset == 0) {
3556       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3557         .addReg(CurrentIdxReg, RegState::Kill);
3558     } else {
3559       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3560         .addReg(CurrentIdxReg, RegState::Kill)
3561         .addImm(Offset);
3562     }
3563   }
3564 
3565   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3566   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3567   MachineInstr *InsertPt =
3568     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3569                                                   : AMDGPU::S_XOR_B64_term), Exec)
3570       .addReg(Exec)
3571       .addReg(NewExec);
3572 
3573   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3574   // s_cbranch_scc0?
3575 
3576   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3577   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3578     .addMBB(&LoopBB);
3579 
3580   return InsertPt->getIterator();
3581 }
3582 
3583 // This has slightly sub-optimal regalloc when the source vector is killed by
3584 // the read. The register allocator does not understand that the kill is
3585 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3586 // subregister from it, using 1 more VGPR than necessary. This was saved when
3587 // this was expanded after register allocation.
3588 static MachineBasicBlock::iterator
3589 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3590                unsigned InitResultReg, unsigned PhiReg, int Offset,
3591                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3592   MachineFunction *MF = MBB.getParent();
3593   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3594   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3595   MachineRegisterInfo &MRI = MF->getRegInfo();
3596   const DebugLoc &DL = MI.getDebugLoc();
3597   MachineBasicBlock::iterator I(&MI);
3598 
3599   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3600   Register DstReg = MI.getOperand(0).getReg();
3601   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3602   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3603   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3604   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3605 
3606   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3607 
3608   // Save the EXEC mask
3609   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3610     .addReg(Exec);
3611 
3612   MachineBasicBlock *LoopBB;
3613   MachineBasicBlock *RemainderBB;
3614   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3615 
3616   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3617 
3618   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3619                                       InitResultReg, DstReg, PhiReg, TmpExec,
3620                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3621 
3622   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3623   MachineFunction::iterator MBBI(LoopBB);
3624   ++MBBI;
3625   MF->insert(MBBI, LandingPad);
3626   LoopBB->removeSuccessor(RemainderBB);
3627   LandingPad->addSuccessor(RemainderBB);
3628   LoopBB->addSuccessor(LandingPad);
3629   MachineBasicBlock::iterator First = LandingPad->begin();
3630   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3631     .addReg(SaveExec);
3632 
3633   return InsPt;
3634 }
3635 
3636 // Returns subreg index, offset
3637 static std::pair<unsigned, int>
3638 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3639                             const TargetRegisterClass *SuperRC,
3640                             unsigned VecReg,
3641                             int Offset) {
3642   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3643 
3644   // Skip out of bounds offsets, or else we would end up using an undefined
3645   // register.
3646   if (Offset >= NumElts || Offset < 0)
3647     return std::make_pair(AMDGPU::sub0, Offset);
3648 
3649   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3650 }
3651 
3652 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3653                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3654                                  int Offset) {
3655   MachineBasicBlock *MBB = MI.getParent();
3656   const DebugLoc &DL = MI.getDebugLoc();
3657   MachineBasicBlock::iterator I(&MI);
3658 
3659   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3660 
3661   assert(Idx->getReg() != AMDGPU::NoRegister);
3662 
3663   if (Offset == 0) {
3664     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3665   } else {
3666     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3667         .add(*Idx)
3668         .addImm(Offset);
3669   }
3670 }
3671 
3672 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3673                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3674                                    int Offset) {
3675   MachineBasicBlock *MBB = MI.getParent();
3676   const DebugLoc &DL = MI.getDebugLoc();
3677   MachineBasicBlock::iterator I(&MI);
3678 
3679   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3680 
3681   if (Offset == 0)
3682     return Idx->getReg();
3683 
3684   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3685   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3686       .add(*Idx)
3687       .addImm(Offset);
3688   return Tmp;
3689 }
3690 
3691 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3692                                           MachineBasicBlock &MBB,
3693                                           const GCNSubtarget &ST) {
3694   const SIInstrInfo *TII = ST.getInstrInfo();
3695   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3696   MachineFunction *MF = MBB.getParent();
3697   MachineRegisterInfo &MRI = MF->getRegInfo();
3698 
3699   Register Dst = MI.getOperand(0).getReg();
3700   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3701   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3702   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3703 
3704   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3705   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3706 
3707   unsigned SubReg;
3708   std::tie(SubReg, Offset)
3709     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3710 
3711   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3712 
3713   // Check for a SGPR index.
3714   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3715     MachineBasicBlock::iterator I(&MI);
3716     const DebugLoc &DL = MI.getDebugLoc();
3717 
3718     if (UseGPRIdxMode) {
3719       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3720       // to avoid interfering with other uses, so probably requires a new
3721       // optimization pass.
3722       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3723 
3724       const MCInstrDesc &GPRIDXDesc =
3725           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3726       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3727           .addReg(SrcReg)
3728           .addReg(Idx)
3729           .addImm(SubReg);
3730     } else {
3731       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3732 
3733       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3734         .addReg(SrcReg, 0, SubReg)
3735         .addReg(SrcReg, RegState::Implicit);
3736     }
3737 
3738     MI.eraseFromParent();
3739 
3740     return &MBB;
3741   }
3742 
3743   // Control flow needs to be inserted if indexing with a VGPR.
3744   const DebugLoc &DL = MI.getDebugLoc();
3745   MachineBasicBlock::iterator I(&MI);
3746 
3747   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3748   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3749 
3750   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3751 
3752   Register SGPRIdxReg;
3753   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3754                               UseGPRIdxMode, SGPRIdxReg);
3755 
3756   MachineBasicBlock *LoopBB = InsPt->getParent();
3757 
3758   if (UseGPRIdxMode) {
3759     const MCInstrDesc &GPRIDXDesc =
3760         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3761 
3762     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3763         .addReg(SrcReg)
3764         .addReg(SGPRIdxReg)
3765         .addImm(SubReg);
3766   } else {
3767     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3768       .addReg(SrcReg, 0, SubReg)
3769       .addReg(SrcReg, RegState::Implicit);
3770   }
3771 
3772   MI.eraseFromParent();
3773 
3774   return LoopBB;
3775 }
3776 
3777 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3778                                           MachineBasicBlock &MBB,
3779                                           const GCNSubtarget &ST) {
3780   const SIInstrInfo *TII = ST.getInstrInfo();
3781   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3782   MachineFunction *MF = MBB.getParent();
3783   MachineRegisterInfo &MRI = MF->getRegInfo();
3784 
3785   Register Dst = MI.getOperand(0).getReg();
3786   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3787   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3788   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3789   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3790   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3791   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3792 
3793   // This can be an immediate, but will be folded later.
3794   assert(Val->getReg());
3795 
3796   unsigned SubReg;
3797   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3798                                                          SrcVec->getReg(),
3799                                                          Offset);
3800   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3801 
3802   if (Idx->getReg() == AMDGPU::NoRegister) {
3803     MachineBasicBlock::iterator I(&MI);
3804     const DebugLoc &DL = MI.getDebugLoc();
3805 
3806     assert(Offset == 0);
3807 
3808     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3809         .add(*SrcVec)
3810         .add(*Val)
3811         .addImm(SubReg);
3812 
3813     MI.eraseFromParent();
3814     return &MBB;
3815   }
3816 
3817   // Check for a SGPR index.
3818   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3819     MachineBasicBlock::iterator I(&MI);
3820     const DebugLoc &DL = MI.getDebugLoc();
3821 
3822     if (UseGPRIdxMode) {
3823       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3824 
3825       const MCInstrDesc &GPRIDXDesc =
3826           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3827       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3828           .addReg(SrcVec->getReg())
3829           .add(*Val)
3830           .addReg(Idx)
3831           .addImm(SubReg);
3832     } else {
3833       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3834 
3835       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3836           TRI.getRegSizeInBits(*VecRC), 32, false);
3837       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3838           .addReg(SrcVec->getReg())
3839           .add(*Val)
3840           .addImm(SubReg);
3841     }
3842     MI.eraseFromParent();
3843     return &MBB;
3844   }
3845 
3846   // Control flow needs to be inserted if indexing with a VGPR.
3847   if (Val->isReg())
3848     MRI.clearKillFlags(Val->getReg());
3849 
3850   const DebugLoc &DL = MI.getDebugLoc();
3851 
3852   Register PhiReg = MRI.createVirtualRegister(VecRC);
3853 
3854   Register SGPRIdxReg;
3855   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3856                               UseGPRIdxMode, SGPRIdxReg);
3857   MachineBasicBlock *LoopBB = InsPt->getParent();
3858 
3859   if (UseGPRIdxMode) {
3860     const MCInstrDesc &GPRIDXDesc =
3861         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3862 
3863     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3864         .addReg(PhiReg)
3865         .add(*Val)
3866         .addReg(SGPRIdxReg)
3867         .addImm(AMDGPU::sub0);
3868   } else {
3869     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3870         TRI.getRegSizeInBits(*VecRC), 32, false);
3871     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3872         .addReg(PhiReg)
3873         .add(*Val)
3874         .addImm(AMDGPU::sub0);
3875   }
3876 
3877   MI.eraseFromParent();
3878   return LoopBB;
3879 }
3880 
3881 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3882   MachineInstr &MI, MachineBasicBlock *BB) const {
3883 
3884   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3885   MachineFunction *MF = BB->getParent();
3886   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3887 
3888   switch (MI.getOpcode()) {
3889   case AMDGPU::S_UADDO_PSEUDO:
3890   case AMDGPU::S_USUBO_PSEUDO: {
3891     const DebugLoc &DL = MI.getDebugLoc();
3892     MachineOperand &Dest0 = MI.getOperand(0);
3893     MachineOperand &Dest1 = MI.getOperand(1);
3894     MachineOperand &Src0 = MI.getOperand(2);
3895     MachineOperand &Src1 = MI.getOperand(3);
3896 
3897     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3898                        ? AMDGPU::S_ADD_I32
3899                        : AMDGPU::S_SUB_I32;
3900     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3901 
3902     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3903         .addImm(1)
3904         .addImm(0);
3905 
3906     MI.eraseFromParent();
3907     return BB;
3908   }
3909   case AMDGPU::S_ADD_U64_PSEUDO:
3910   case AMDGPU::S_SUB_U64_PSEUDO: {
3911     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3912     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3913     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3914     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3915     const DebugLoc &DL = MI.getDebugLoc();
3916 
3917     MachineOperand &Dest = MI.getOperand(0);
3918     MachineOperand &Src0 = MI.getOperand(1);
3919     MachineOperand &Src1 = MI.getOperand(2);
3920 
3921     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3922     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3923 
3924     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3925         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3926     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3927         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3928 
3929     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3930         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3931     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3932         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3933 
3934     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3935 
3936     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3937     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3938     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3939     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3940     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3941         .addReg(DestSub0)
3942         .addImm(AMDGPU::sub0)
3943         .addReg(DestSub1)
3944         .addImm(AMDGPU::sub1);
3945     MI.eraseFromParent();
3946     return BB;
3947   }
3948   case AMDGPU::V_ADD_U64_PSEUDO:
3949   case AMDGPU::V_SUB_U64_PSEUDO: {
3950     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3951     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3952     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3953     const DebugLoc &DL = MI.getDebugLoc();
3954 
3955     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3956 
3957     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3958 
3959     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3960     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3961 
3962     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3963     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3964 
3965     MachineOperand &Dest = MI.getOperand(0);
3966     MachineOperand &Src0 = MI.getOperand(1);
3967     MachineOperand &Src1 = MI.getOperand(2);
3968 
3969     const TargetRegisterClass *Src0RC = Src0.isReg()
3970                                             ? MRI.getRegClass(Src0.getReg())
3971                                             : &AMDGPU::VReg_64RegClass;
3972     const TargetRegisterClass *Src1RC = Src1.isReg()
3973                                             ? MRI.getRegClass(Src1.getReg())
3974                                             : &AMDGPU::VReg_64RegClass;
3975 
3976     const TargetRegisterClass *Src0SubRC =
3977         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3978     const TargetRegisterClass *Src1SubRC =
3979         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3980 
3981     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3982         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3983     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3984         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3985 
3986     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3987         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3988     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3989         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3990 
3991     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3992     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3993                                .addReg(CarryReg, RegState::Define)
3994                                .add(SrcReg0Sub0)
3995                                .add(SrcReg1Sub0)
3996                                .addImm(0); // clamp bit
3997 
3998     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3999     MachineInstr *HiHalf =
4000         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4001             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4002             .add(SrcReg0Sub1)
4003             .add(SrcReg1Sub1)
4004             .addReg(CarryReg, RegState::Kill)
4005             .addImm(0); // clamp bit
4006 
4007     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4008         .addReg(DestSub0)
4009         .addImm(AMDGPU::sub0)
4010         .addReg(DestSub1)
4011         .addImm(AMDGPU::sub1);
4012     TII->legalizeOperands(*LoHalf);
4013     TII->legalizeOperands(*HiHalf);
4014     MI.eraseFromParent();
4015     return BB;
4016   }
4017   case AMDGPU::S_ADD_CO_PSEUDO:
4018   case AMDGPU::S_SUB_CO_PSEUDO: {
4019     // This pseudo has a chance to be selected
4020     // only from uniform add/subcarry node. All the VGPR operands
4021     // therefore assumed to be splat vectors.
4022     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4023     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4024     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4025     MachineBasicBlock::iterator MII = MI;
4026     const DebugLoc &DL = MI.getDebugLoc();
4027     MachineOperand &Dest = MI.getOperand(0);
4028     MachineOperand &CarryDest = MI.getOperand(1);
4029     MachineOperand &Src0 = MI.getOperand(2);
4030     MachineOperand &Src1 = MI.getOperand(3);
4031     MachineOperand &Src2 = MI.getOperand(4);
4032     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4033                        ? AMDGPU::S_ADDC_U32
4034                        : AMDGPU::S_SUBB_U32;
4035     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4036       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4037       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4038           .addReg(Src0.getReg());
4039       Src0.setReg(RegOp0);
4040     }
4041     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4042       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4043       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4044           .addReg(Src1.getReg());
4045       Src1.setReg(RegOp1);
4046     }
4047     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4048     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4049       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4050           .addReg(Src2.getReg());
4051       Src2.setReg(RegOp2);
4052     }
4053 
4054     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4055     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4056       if (ST.hasScalarCompareEq64()) {
4057         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4058             .addReg(Src2.getReg())
4059             .addImm(0);
4060       } else {
4061         const TargetRegisterClass *SubRC =
4062             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4063         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4064             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4065         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4066             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4067         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4068 
4069         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4070             .add(Src2Sub0)
4071             .add(Src2Sub1);
4072 
4073         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4074             .addReg(Src2_32, RegState::Kill)
4075             .addImm(0);
4076       }
4077     } else {
4078       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4079           .addReg(Src2.getReg())
4080           .addImm(0);
4081     }
4082 
4083     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4084 
4085     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4086       .addReg(AMDGPU::SCC);
4087     MI.eraseFromParent();
4088     return BB;
4089   }
4090   case AMDGPU::SI_INIT_M0: {
4091     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4092             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4093         .add(MI.getOperand(0));
4094     MI.eraseFromParent();
4095     return BB;
4096   }
4097   case AMDGPU::GET_GROUPSTATICSIZE: {
4098     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4099            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4100     DebugLoc DL = MI.getDebugLoc();
4101     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4102         .add(MI.getOperand(0))
4103         .addImm(MFI->getLDSSize());
4104     MI.eraseFromParent();
4105     return BB;
4106   }
4107   case AMDGPU::SI_INDIRECT_SRC_V1:
4108   case AMDGPU::SI_INDIRECT_SRC_V2:
4109   case AMDGPU::SI_INDIRECT_SRC_V4:
4110   case AMDGPU::SI_INDIRECT_SRC_V8:
4111   case AMDGPU::SI_INDIRECT_SRC_V16:
4112   case AMDGPU::SI_INDIRECT_SRC_V32:
4113     return emitIndirectSrc(MI, *BB, *getSubtarget());
4114   case AMDGPU::SI_INDIRECT_DST_V1:
4115   case AMDGPU::SI_INDIRECT_DST_V2:
4116   case AMDGPU::SI_INDIRECT_DST_V4:
4117   case AMDGPU::SI_INDIRECT_DST_V8:
4118   case AMDGPU::SI_INDIRECT_DST_V16:
4119   case AMDGPU::SI_INDIRECT_DST_V32:
4120     return emitIndirectDst(MI, *BB, *getSubtarget());
4121   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4122   case AMDGPU::SI_KILL_I1_PSEUDO:
4123     return splitKillBlock(MI, BB);
4124   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4125     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4126     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4127     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4128 
4129     Register Dst = MI.getOperand(0).getReg();
4130     Register Src0 = MI.getOperand(1).getReg();
4131     Register Src1 = MI.getOperand(2).getReg();
4132     const DebugLoc &DL = MI.getDebugLoc();
4133     Register SrcCond = MI.getOperand(3).getReg();
4134 
4135     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4136     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4137     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4138     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4139 
4140     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4141       .addReg(SrcCond);
4142     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4143       .addImm(0)
4144       .addReg(Src0, 0, AMDGPU::sub0)
4145       .addImm(0)
4146       .addReg(Src1, 0, AMDGPU::sub0)
4147       .addReg(SrcCondCopy);
4148     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4149       .addImm(0)
4150       .addReg(Src0, 0, AMDGPU::sub1)
4151       .addImm(0)
4152       .addReg(Src1, 0, AMDGPU::sub1)
4153       .addReg(SrcCondCopy);
4154 
4155     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4156       .addReg(DstLo)
4157       .addImm(AMDGPU::sub0)
4158       .addReg(DstHi)
4159       .addImm(AMDGPU::sub1);
4160     MI.eraseFromParent();
4161     return BB;
4162   }
4163   case AMDGPU::SI_BR_UNDEF: {
4164     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4165     const DebugLoc &DL = MI.getDebugLoc();
4166     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4167                            .add(MI.getOperand(0));
4168     Br->getOperand(1).setIsUndef(true); // read undef SCC
4169     MI.eraseFromParent();
4170     return BB;
4171   }
4172   case AMDGPU::ADJCALLSTACKUP:
4173   case AMDGPU::ADJCALLSTACKDOWN: {
4174     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4175     MachineInstrBuilder MIB(*MF, &MI);
4176     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4177        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4178     return BB;
4179   }
4180   case AMDGPU::SI_CALL_ISEL: {
4181     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4182     const DebugLoc &DL = MI.getDebugLoc();
4183 
4184     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4185 
4186     MachineInstrBuilder MIB;
4187     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4188 
4189     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4190       MIB.add(MI.getOperand(I));
4191 
4192     MIB.cloneMemRefs(MI);
4193     MI.eraseFromParent();
4194     return BB;
4195   }
4196   case AMDGPU::V_ADD_CO_U32_e32:
4197   case AMDGPU::V_SUB_CO_U32_e32:
4198   case AMDGPU::V_SUBREV_CO_U32_e32: {
4199     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4200     const DebugLoc &DL = MI.getDebugLoc();
4201     unsigned Opc = MI.getOpcode();
4202 
4203     bool NeedClampOperand = false;
4204     if (TII->pseudoToMCOpcode(Opc) == -1) {
4205       Opc = AMDGPU::getVOPe64(Opc);
4206       NeedClampOperand = true;
4207     }
4208 
4209     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4210     if (TII->isVOP3(*I)) {
4211       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4212       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4213       I.addReg(TRI->getVCC(), RegState::Define);
4214     }
4215     I.add(MI.getOperand(1))
4216      .add(MI.getOperand(2));
4217     if (NeedClampOperand)
4218       I.addImm(0); // clamp bit for e64 encoding
4219 
4220     TII->legalizeOperands(*I);
4221 
4222     MI.eraseFromParent();
4223     return BB;
4224   }
4225   case AMDGPU::DS_GWS_INIT:
4226   case AMDGPU::DS_GWS_SEMA_BR:
4227   case AMDGPU::DS_GWS_BARRIER:
4228     if (Subtarget->needsAlignedVGPRs()) {
4229       // Add implicit aligned super-reg to force alignment on the data operand.
4230       const DebugLoc &DL = MI.getDebugLoc();
4231       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4232       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4233       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4234       Register DataReg = Op->getReg();
4235       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4236       Register Undef = MRI.createVirtualRegister(
4237           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4238       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4239       Register NewVR =
4240           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4241                                            : &AMDGPU::VReg_64_Align2RegClass);
4242       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4243           .addReg(DataReg, 0, Op->getSubReg())
4244           .addImm(AMDGPU::sub0)
4245           .addReg(Undef)
4246           .addImm(AMDGPU::sub1);
4247       Op->setReg(NewVR);
4248       Op->setSubReg(AMDGPU::sub0);
4249       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4250     }
4251     LLVM_FALLTHROUGH;
4252   case AMDGPU::DS_GWS_SEMA_V:
4253   case AMDGPU::DS_GWS_SEMA_P:
4254   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4255     // A s_waitcnt 0 is required to be the instruction immediately following.
4256     if (getSubtarget()->hasGWSAutoReplay()) {
4257       bundleInstWithWaitcnt(MI);
4258       return BB;
4259     }
4260 
4261     return emitGWSMemViolTestLoop(MI, BB);
4262   case AMDGPU::S_SETREG_B32: {
4263     // Try to optimize cases that only set the denormal mode or rounding mode.
4264     //
4265     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4266     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4267     // instead.
4268     //
4269     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4270     // allow you to have a no side effect instruction in the output of a
4271     // sideeffecting pattern.
4272     unsigned ID, Offset, Width;
4273     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4274     if (ID != AMDGPU::Hwreg::ID_MODE)
4275       return BB;
4276 
4277     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4278     const unsigned SetMask = WidthMask << Offset;
4279 
4280     if (getSubtarget()->hasDenormModeInst()) {
4281       unsigned SetDenormOp = 0;
4282       unsigned SetRoundOp = 0;
4283 
4284       // The dedicated instructions can only set the whole denorm or round mode
4285       // at once, not a subset of bits in either.
4286       if (SetMask ==
4287           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4288         // If this fully sets both the round and denorm mode, emit the two
4289         // dedicated instructions for these.
4290         SetRoundOp = AMDGPU::S_ROUND_MODE;
4291         SetDenormOp = AMDGPU::S_DENORM_MODE;
4292       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4293         SetRoundOp = AMDGPU::S_ROUND_MODE;
4294       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4295         SetDenormOp = AMDGPU::S_DENORM_MODE;
4296       }
4297 
4298       if (SetRoundOp || SetDenormOp) {
4299         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4300         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4301         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4302           unsigned ImmVal = Def->getOperand(1).getImm();
4303           if (SetRoundOp) {
4304             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4305                 .addImm(ImmVal & 0xf);
4306 
4307             // If we also have the denorm mode, get just the denorm mode bits.
4308             ImmVal >>= 4;
4309           }
4310 
4311           if (SetDenormOp) {
4312             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4313                 .addImm(ImmVal & 0xf);
4314           }
4315 
4316           MI.eraseFromParent();
4317           return BB;
4318         }
4319       }
4320     }
4321 
4322     // If only FP bits are touched, used the no side effects pseudo.
4323     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4324                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4325       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4326 
4327     return BB;
4328   }
4329   default:
4330     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4331   }
4332 }
4333 
4334 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4335   return isTypeLegal(VT.getScalarType());
4336 }
4337 
4338 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4339   // This currently forces unfolding various combinations of fsub into fma with
4340   // free fneg'd operands. As long as we have fast FMA (controlled by
4341   // isFMAFasterThanFMulAndFAdd), we should perform these.
4342 
4343   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4344   // most of these combines appear to be cycle neutral but save on instruction
4345   // count / code size.
4346   return true;
4347 }
4348 
4349 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4350                                          EVT VT) const {
4351   if (!VT.isVector()) {
4352     return MVT::i1;
4353   }
4354   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4355 }
4356 
4357 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4358   // TODO: Should i16 be used always if legal? For now it would force VALU
4359   // shifts.
4360   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4361 }
4362 
4363 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4364   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4365              ? Ty.changeElementSize(16)
4366              : Ty.changeElementSize(32);
4367 }
4368 
4369 // Answering this is somewhat tricky and depends on the specific device which
4370 // have different rates for fma or all f64 operations.
4371 //
4372 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4373 // regardless of which device (although the number of cycles differs between
4374 // devices), so it is always profitable for f64.
4375 //
4376 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4377 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4378 // which we can always do even without fused FP ops since it returns the same
4379 // result as the separate operations and since it is always full
4380 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4381 // however does not support denormals, so we do report fma as faster if we have
4382 // a fast fma device and require denormals.
4383 //
4384 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4385                                                   EVT VT) const {
4386   VT = VT.getScalarType();
4387 
4388   switch (VT.getSimpleVT().SimpleTy) {
4389   case MVT::f32: {
4390     // If mad is not available this depends only on if f32 fma is full rate.
4391     if (!Subtarget->hasMadMacF32Insts())
4392       return Subtarget->hasFastFMAF32();
4393 
4394     // Otherwise f32 mad is always full rate and returns the same result as
4395     // the separate operations so should be preferred over fma.
4396     // However does not support denomals.
4397     if (hasFP32Denormals(MF))
4398       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4399 
4400     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4401     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4402   }
4403   case MVT::f64:
4404     return true;
4405   case MVT::f16:
4406     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4407   default:
4408     break;
4409   }
4410 
4411   return false;
4412 }
4413 
4414 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4415                                    const SDNode *N) const {
4416   // TODO: Check future ftz flag
4417   // v_mad_f32/v_mac_f32 do not support denormals.
4418   EVT VT = N->getValueType(0);
4419   if (VT == MVT::f32)
4420     return Subtarget->hasMadMacF32Insts() &&
4421            !hasFP32Denormals(DAG.getMachineFunction());
4422   if (VT == MVT::f16) {
4423     return Subtarget->hasMadF16() &&
4424            !hasFP64FP16Denormals(DAG.getMachineFunction());
4425   }
4426 
4427   return false;
4428 }
4429 
4430 //===----------------------------------------------------------------------===//
4431 // Custom DAG Lowering Operations
4432 //===----------------------------------------------------------------------===//
4433 
4434 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4435 // wider vector type is legal.
4436 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4437                                              SelectionDAG &DAG) const {
4438   unsigned Opc = Op.getOpcode();
4439   EVT VT = Op.getValueType();
4440   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4441 
4442   SDValue Lo, Hi;
4443   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4444 
4445   SDLoc SL(Op);
4446   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4447                              Op->getFlags());
4448   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4449                              Op->getFlags());
4450 
4451   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4452 }
4453 
4454 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4455 // wider vector type is legal.
4456 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4457                                               SelectionDAG &DAG) const {
4458   unsigned Opc = Op.getOpcode();
4459   EVT VT = Op.getValueType();
4460   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4461          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4462 
4463   SDValue Lo0, Hi0;
4464   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4465   SDValue Lo1, Hi1;
4466   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4467 
4468   SDLoc SL(Op);
4469 
4470   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4471                              Op->getFlags());
4472   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4473                              Op->getFlags());
4474 
4475   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4476 }
4477 
4478 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4479                                               SelectionDAG &DAG) const {
4480   unsigned Opc = Op.getOpcode();
4481   EVT VT = Op.getValueType();
4482   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4483          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4484 
4485   SDValue Lo0, Hi0;
4486   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4487   SDValue Lo1, Hi1;
4488   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4489   SDValue Lo2, Hi2;
4490   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4491 
4492   SDLoc SL(Op);
4493 
4494   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4495                              Op->getFlags());
4496   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4497                              Op->getFlags());
4498 
4499   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4500 }
4501 
4502 
4503 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4504   switch (Op.getOpcode()) {
4505   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4506   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4507   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4508   case ISD::LOAD: {
4509     SDValue Result = LowerLOAD(Op, DAG);
4510     assert((!Result.getNode() ||
4511             Result.getNode()->getNumValues() == 2) &&
4512            "Load should return a value and a chain");
4513     return Result;
4514   }
4515 
4516   case ISD::FSIN:
4517   case ISD::FCOS:
4518     return LowerTrig(Op, DAG);
4519   case ISD::SELECT: return LowerSELECT(Op, DAG);
4520   case ISD::FDIV: return LowerFDIV(Op, DAG);
4521   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4522   case ISD::STORE: return LowerSTORE(Op, DAG);
4523   case ISD::GlobalAddress: {
4524     MachineFunction &MF = DAG.getMachineFunction();
4525     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4526     return LowerGlobalAddress(MFI, Op, DAG);
4527   }
4528   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4529   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4530   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4531   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4532   case ISD::INSERT_SUBVECTOR:
4533     return lowerINSERT_SUBVECTOR(Op, DAG);
4534   case ISD::INSERT_VECTOR_ELT:
4535     return lowerINSERT_VECTOR_ELT(Op, DAG);
4536   case ISD::EXTRACT_VECTOR_ELT:
4537     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4538   case ISD::VECTOR_SHUFFLE:
4539     return lowerVECTOR_SHUFFLE(Op, DAG);
4540   case ISD::BUILD_VECTOR:
4541     return lowerBUILD_VECTOR(Op, DAG);
4542   case ISD::FP_ROUND:
4543     return lowerFP_ROUND(Op, DAG);
4544   case ISD::TRAP:
4545     return lowerTRAP(Op, DAG);
4546   case ISD::DEBUGTRAP:
4547     return lowerDEBUGTRAP(Op, DAG);
4548   case ISD::FABS:
4549   case ISD::FNEG:
4550   case ISD::FCANONICALIZE:
4551   case ISD::BSWAP:
4552     return splitUnaryVectorOp(Op, DAG);
4553   case ISD::FMINNUM:
4554   case ISD::FMAXNUM:
4555     return lowerFMINNUM_FMAXNUM(Op, DAG);
4556   case ISD::FMA:
4557     return splitTernaryVectorOp(Op, DAG);
4558   case ISD::FP_TO_SINT:
4559   case ISD::FP_TO_UINT:
4560     return LowerFP_TO_INT(Op, DAG);
4561   case ISD::SHL:
4562   case ISD::SRA:
4563   case ISD::SRL:
4564   case ISD::ADD:
4565   case ISD::SUB:
4566   case ISD::MUL:
4567   case ISD::SMIN:
4568   case ISD::SMAX:
4569   case ISD::UMIN:
4570   case ISD::UMAX:
4571   case ISD::FADD:
4572   case ISD::FMUL:
4573   case ISD::FMINNUM_IEEE:
4574   case ISD::FMAXNUM_IEEE:
4575   case ISD::UADDSAT:
4576   case ISD::USUBSAT:
4577   case ISD::SADDSAT:
4578   case ISD::SSUBSAT:
4579     return splitBinaryVectorOp(Op, DAG);
4580   case ISD::SMULO:
4581   case ISD::UMULO:
4582     return lowerXMULO(Op, DAG);
4583   case ISD::DYNAMIC_STACKALLOC:
4584     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4585   }
4586   return SDValue();
4587 }
4588 
4589 // Used for D16: Casts the result of an instruction into the right vector,
4590 // packs values if loads return unpacked values.
4591 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4592                                        const SDLoc &DL,
4593                                        SelectionDAG &DAG, bool Unpacked) {
4594   if (!LoadVT.isVector())
4595     return Result;
4596 
4597   // Cast back to the original packed type or to a larger type that is a
4598   // multiple of 32 bit for D16. Widening the return type is a required for
4599   // legalization.
4600   EVT FittingLoadVT = LoadVT;
4601   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4602     FittingLoadVT =
4603         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4604                          LoadVT.getVectorNumElements() + 1);
4605   }
4606 
4607   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4608     // Truncate to v2i16/v4i16.
4609     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4610 
4611     // Workaround legalizer not scalarizing truncate after vector op
4612     // legalization but not creating intermediate vector trunc.
4613     SmallVector<SDValue, 4> Elts;
4614     DAG.ExtractVectorElements(Result, Elts);
4615     for (SDValue &Elt : Elts)
4616       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4617 
4618     // Pad illegal v1i16/v3fi6 to v4i16
4619     if ((LoadVT.getVectorNumElements() % 2) == 1)
4620       Elts.push_back(DAG.getUNDEF(MVT::i16));
4621 
4622     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4623 
4624     // Bitcast to original type (v2f16/v4f16).
4625     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4626   }
4627 
4628   // Cast back to the original packed type.
4629   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4630 }
4631 
4632 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4633                                               MemSDNode *M,
4634                                               SelectionDAG &DAG,
4635                                               ArrayRef<SDValue> Ops,
4636                                               bool IsIntrinsic) const {
4637   SDLoc DL(M);
4638 
4639   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4640   EVT LoadVT = M->getValueType(0);
4641 
4642   EVT EquivLoadVT = LoadVT;
4643   if (LoadVT.isVector()) {
4644     if (Unpacked) {
4645       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4646                                      LoadVT.getVectorNumElements());
4647     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4648       // Widen v3f16 to legal type
4649       EquivLoadVT =
4650           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4651                            LoadVT.getVectorNumElements() + 1);
4652     }
4653   }
4654 
4655   // Change from v4f16/v2f16 to EquivLoadVT.
4656   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4657 
4658   SDValue Load
4659     = DAG.getMemIntrinsicNode(
4660       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4661       VTList, Ops, M->getMemoryVT(),
4662       M->getMemOperand());
4663 
4664   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4665 
4666   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4667 }
4668 
4669 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4670                                              SelectionDAG &DAG,
4671                                              ArrayRef<SDValue> Ops) const {
4672   SDLoc DL(M);
4673   EVT LoadVT = M->getValueType(0);
4674   EVT EltType = LoadVT.getScalarType();
4675   EVT IntVT = LoadVT.changeTypeToInteger();
4676 
4677   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4678 
4679   unsigned Opc =
4680       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4681 
4682   if (IsD16) {
4683     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4684   }
4685 
4686   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4687   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4688     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4689 
4690   if (isTypeLegal(LoadVT)) {
4691     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4692                                M->getMemOperand(), DAG);
4693   }
4694 
4695   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4696   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4697   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4698                                         M->getMemOperand(), DAG);
4699   return DAG.getMergeValues(
4700       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4701       DL);
4702 }
4703 
4704 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4705                                   SDNode *N, SelectionDAG &DAG) {
4706   EVT VT = N->getValueType(0);
4707   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4708   unsigned CondCode = CD->getZExtValue();
4709   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4710     return DAG.getUNDEF(VT);
4711 
4712   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4713 
4714   SDValue LHS = N->getOperand(1);
4715   SDValue RHS = N->getOperand(2);
4716 
4717   SDLoc DL(N);
4718 
4719   EVT CmpVT = LHS.getValueType();
4720   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4721     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4722       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4723     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4724     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4725   }
4726 
4727   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4728 
4729   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4730   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4731 
4732   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4733                               DAG.getCondCode(CCOpcode));
4734   if (VT.bitsEq(CCVT))
4735     return SetCC;
4736   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4737 }
4738 
4739 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4740                                   SDNode *N, SelectionDAG &DAG) {
4741   EVT VT = N->getValueType(0);
4742   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4743 
4744   unsigned CondCode = CD->getZExtValue();
4745   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4746     return DAG.getUNDEF(VT);
4747 
4748   SDValue Src0 = N->getOperand(1);
4749   SDValue Src1 = N->getOperand(2);
4750   EVT CmpVT = Src0.getValueType();
4751   SDLoc SL(N);
4752 
4753   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4754     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4755     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4756   }
4757 
4758   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4759   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4760   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4761   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4762   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4763                               Src1, DAG.getCondCode(CCOpcode));
4764   if (VT.bitsEq(CCVT))
4765     return SetCC;
4766   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4767 }
4768 
4769 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4770                                     SelectionDAG &DAG) {
4771   EVT VT = N->getValueType(0);
4772   SDValue Src = N->getOperand(1);
4773   SDLoc SL(N);
4774 
4775   if (Src.getOpcode() == ISD::SETCC) {
4776     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4777     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4778                        Src.getOperand(1), Src.getOperand(2));
4779   }
4780   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4781     // (ballot 0) -> 0
4782     if (Arg->isNullValue())
4783       return DAG.getConstant(0, SL, VT);
4784 
4785     // (ballot 1) -> EXEC/EXEC_LO
4786     if (Arg->isOne()) {
4787       Register Exec;
4788       if (VT.getScalarSizeInBits() == 32)
4789         Exec = AMDGPU::EXEC_LO;
4790       else if (VT.getScalarSizeInBits() == 64)
4791         Exec = AMDGPU::EXEC;
4792       else
4793         return SDValue();
4794 
4795       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4796     }
4797   }
4798 
4799   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4800   // ISD::SETNE)
4801   return DAG.getNode(
4802       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4803       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4804 }
4805 
4806 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4807                                           SmallVectorImpl<SDValue> &Results,
4808                                           SelectionDAG &DAG) const {
4809   switch (N->getOpcode()) {
4810   case ISD::INSERT_VECTOR_ELT: {
4811     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4812       Results.push_back(Res);
4813     return;
4814   }
4815   case ISD::EXTRACT_VECTOR_ELT: {
4816     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4817       Results.push_back(Res);
4818     return;
4819   }
4820   case ISD::INTRINSIC_WO_CHAIN: {
4821     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4822     switch (IID) {
4823     case Intrinsic::amdgcn_cvt_pkrtz: {
4824       SDValue Src0 = N->getOperand(1);
4825       SDValue Src1 = N->getOperand(2);
4826       SDLoc SL(N);
4827       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4828                                 Src0, Src1);
4829       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4830       return;
4831     }
4832     case Intrinsic::amdgcn_cvt_pknorm_i16:
4833     case Intrinsic::amdgcn_cvt_pknorm_u16:
4834     case Intrinsic::amdgcn_cvt_pk_i16:
4835     case Intrinsic::amdgcn_cvt_pk_u16: {
4836       SDValue Src0 = N->getOperand(1);
4837       SDValue Src1 = N->getOperand(2);
4838       SDLoc SL(N);
4839       unsigned Opcode;
4840 
4841       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4842         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4843       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4844         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4845       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4846         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4847       else
4848         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4849 
4850       EVT VT = N->getValueType(0);
4851       if (isTypeLegal(VT))
4852         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4853       else {
4854         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4855         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4856       }
4857       return;
4858     }
4859     }
4860     break;
4861   }
4862   case ISD::INTRINSIC_W_CHAIN: {
4863     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4864       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4865         // FIXME: Hacky
4866         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4867           Results.push_back(Res.getOperand(I));
4868         }
4869       } else {
4870         Results.push_back(Res);
4871         Results.push_back(Res.getValue(1));
4872       }
4873       return;
4874     }
4875 
4876     break;
4877   }
4878   case ISD::SELECT: {
4879     SDLoc SL(N);
4880     EVT VT = N->getValueType(0);
4881     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4882     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4883     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4884 
4885     EVT SelectVT = NewVT;
4886     if (NewVT.bitsLT(MVT::i32)) {
4887       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4888       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4889       SelectVT = MVT::i32;
4890     }
4891 
4892     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4893                                     N->getOperand(0), LHS, RHS);
4894 
4895     if (NewVT != SelectVT)
4896       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4897     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4898     return;
4899   }
4900   case ISD::FNEG: {
4901     if (N->getValueType(0) != MVT::v2f16)
4902       break;
4903 
4904     SDLoc SL(N);
4905     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4906 
4907     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4908                              BC,
4909                              DAG.getConstant(0x80008000, SL, MVT::i32));
4910     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4911     return;
4912   }
4913   case ISD::FABS: {
4914     if (N->getValueType(0) != MVT::v2f16)
4915       break;
4916 
4917     SDLoc SL(N);
4918     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4919 
4920     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4921                              BC,
4922                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4923     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4924     return;
4925   }
4926   default:
4927     break;
4928   }
4929 }
4930 
4931 /// Helper function for LowerBRCOND
4932 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4933 
4934   SDNode *Parent = Value.getNode();
4935   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4936        I != E; ++I) {
4937 
4938     if (I.getUse().get() != Value)
4939       continue;
4940 
4941     if (I->getOpcode() == Opcode)
4942       return *I;
4943   }
4944   return nullptr;
4945 }
4946 
4947 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4948   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4949     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4950     case Intrinsic::amdgcn_if:
4951       return AMDGPUISD::IF;
4952     case Intrinsic::amdgcn_else:
4953       return AMDGPUISD::ELSE;
4954     case Intrinsic::amdgcn_loop:
4955       return AMDGPUISD::LOOP;
4956     case Intrinsic::amdgcn_end_cf:
4957       llvm_unreachable("should not occur");
4958     default:
4959       return 0;
4960     }
4961   }
4962 
4963   // break, if_break, else_break are all only used as inputs to loop, not
4964   // directly as branch conditions.
4965   return 0;
4966 }
4967 
4968 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4969   const Triple &TT = getTargetMachine().getTargetTriple();
4970   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4971           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4972          AMDGPU::shouldEmitConstantsToTextSection(TT);
4973 }
4974 
4975 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4976   // FIXME: Either avoid relying on address space here or change the default
4977   // address space for functions to avoid the explicit check.
4978   return (GV->getValueType()->isFunctionTy() ||
4979           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4980          !shouldEmitFixup(GV) &&
4981          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4982 }
4983 
4984 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4985   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4986 }
4987 
4988 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4989   if (!GV->hasExternalLinkage())
4990     return true;
4991 
4992   const auto OS = getTargetMachine().getTargetTriple().getOS();
4993   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4994 }
4995 
4996 /// This transforms the control flow intrinsics to get the branch destination as
4997 /// last parameter, also switches branch target with BR if the need arise
4998 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4999                                       SelectionDAG &DAG) const {
5000   SDLoc DL(BRCOND);
5001 
5002   SDNode *Intr = BRCOND.getOperand(1).getNode();
5003   SDValue Target = BRCOND.getOperand(2);
5004   SDNode *BR = nullptr;
5005   SDNode *SetCC = nullptr;
5006 
5007   if (Intr->getOpcode() == ISD::SETCC) {
5008     // As long as we negate the condition everything is fine
5009     SetCC = Intr;
5010     Intr = SetCC->getOperand(0).getNode();
5011 
5012   } else {
5013     // Get the target from BR if we don't negate the condition
5014     BR = findUser(BRCOND, ISD::BR);
5015     assert(BR && "brcond missing unconditional branch user");
5016     Target = BR->getOperand(1);
5017   }
5018 
5019   unsigned CFNode = isCFIntrinsic(Intr);
5020   if (CFNode == 0) {
5021     // This is a uniform branch so we don't need to legalize.
5022     return BRCOND;
5023   }
5024 
5025   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5026                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5027 
5028   assert(!SetCC ||
5029         (SetCC->getConstantOperandVal(1) == 1 &&
5030          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5031                                                              ISD::SETNE));
5032 
5033   // operands of the new intrinsic call
5034   SmallVector<SDValue, 4> Ops;
5035   if (HaveChain)
5036     Ops.push_back(BRCOND.getOperand(0));
5037 
5038   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5039   Ops.push_back(Target);
5040 
5041   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5042 
5043   // build the new intrinsic call
5044   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5045 
5046   if (!HaveChain) {
5047     SDValue Ops[] =  {
5048       SDValue(Result, 0),
5049       BRCOND.getOperand(0)
5050     };
5051 
5052     Result = DAG.getMergeValues(Ops, DL).getNode();
5053   }
5054 
5055   if (BR) {
5056     // Give the branch instruction our target
5057     SDValue Ops[] = {
5058       BR->getOperand(0),
5059       BRCOND.getOperand(2)
5060     };
5061     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5062     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5063   }
5064 
5065   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5066 
5067   // Copy the intrinsic results to registers
5068   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5069     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5070     if (!CopyToReg)
5071       continue;
5072 
5073     Chain = DAG.getCopyToReg(
5074       Chain, DL,
5075       CopyToReg->getOperand(1),
5076       SDValue(Result, i - 1),
5077       SDValue());
5078 
5079     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5080   }
5081 
5082   // Remove the old intrinsic from the chain
5083   DAG.ReplaceAllUsesOfValueWith(
5084     SDValue(Intr, Intr->getNumValues() - 1),
5085     Intr->getOperand(0));
5086 
5087   return Chain;
5088 }
5089 
5090 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5091                                           SelectionDAG &DAG) const {
5092   MVT VT = Op.getSimpleValueType();
5093   SDLoc DL(Op);
5094   // Checking the depth
5095   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5096     return DAG.getConstant(0, DL, VT);
5097 
5098   MachineFunction &MF = DAG.getMachineFunction();
5099   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5100   // Check for kernel and shader functions
5101   if (Info->isEntryFunction())
5102     return DAG.getConstant(0, DL, VT);
5103 
5104   MachineFrameInfo &MFI = MF.getFrameInfo();
5105   // There is a call to @llvm.returnaddress in this function
5106   MFI.setReturnAddressIsTaken(true);
5107 
5108   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5109   // Get the return address reg and mark it as an implicit live-in
5110   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5111 
5112   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5113 }
5114 
5115 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5116                                             SDValue Op,
5117                                             const SDLoc &DL,
5118                                             EVT VT) const {
5119   return Op.getValueType().bitsLE(VT) ?
5120       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5121     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5122                 DAG.getTargetConstant(0, DL, MVT::i32));
5123 }
5124 
5125 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5126   assert(Op.getValueType() == MVT::f16 &&
5127          "Do not know how to custom lower FP_ROUND for non-f16 type");
5128 
5129   SDValue Src = Op.getOperand(0);
5130   EVT SrcVT = Src.getValueType();
5131   if (SrcVT != MVT::f64)
5132     return Op;
5133 
5134   SDLoc DL(Op);
5135 
5136   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5137   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5138   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5139 }
5140 
5141 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5142                                                SelectionDAG &DAG) const {
5143   EVT VT = Op.getValueType();
5144   const MachineFunction &MF = DAG.getMachineFunction();
5145   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5146   bool IsIEEEMode = Info->getMode().IEEE;
5147 
5148   // FIXME: Assert during selection that this is only selected for
5149   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5150   // mode functions, but this happens to be OK since it's only done in cases
5151   // where there is known no sNaN.
5152   if (IsIEEEMode)
5153     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5154 
5155   if (VT == MVT::v4f16)
5156     return splitBinaryVectorOp(Op, DAG);
5157   return Op;
5158 }
5159 
5160 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5161   EVT VT = Op.getValueType();
5162   SDLoc SL(Op);
5163   SDValue LHS = Op.getOperand(0);
5164   SDValue RHS = Op.getOperand(1);
5165   bool isSigned = Op.getOpcode() == ISD::SMULO;
5166 
5167   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5168     const APInt &C = RHSC->getAPIntValue();
5169     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5170     if (C.isPowerOf2()) {
5171       // smulo(x, signed_min) is same as umulo(x, signed_min).
5172       bool UseArithShift = isSigned && !C.isMinSignedValue();
5173       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5174       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5175       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5176           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5177                       SL, VT, Result, ShiftAmt),
5178           LHS, ISD::SETNE);
5179       return DAG.getMergeValues({ Result, Overflow }, SL);
5180     }
5181   }
5182 
5183   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5184   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5185                             SL, VT, LHS, RHS);
5186 
5187   SDValue Sign = isSigned
5188     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5189                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5190     : DAG.getConstant(0, SL, VT);
5191   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5192 
5193   return DAG.getMergeValues({ Result, Overflow }, SL);
5194 }
5195 
5196 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5197   if (!Subtarget->isTrapHandlerEnabled() ||
5198       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5199     return lowerTrapEndpgm(Op, DAG);
5200 
5201   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5202     switch (*HsaAbiVer) {
5203     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5204     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5205       return lowerTrapHsaQueuePtr(Op, DAG);
5206     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5207       return Subtarget->supportsGetDoorbellID() ?
5208           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5209     }
5210   }
5211 
5212   llvm_unreachable("Unknown trap handler");
5213 }
5214 
5215 SDValue SITargetLowering::lowerTrapEndpgm(
5216     SDValue Op, SelectionDAG &DAG) const {
5217   SDLoc SL(Op);
5218   SDValue Chain = Op.getOperand(0);
5219   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5220 }
5221 
5222 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5223     SDValue Op, SelectionDAG &DAG) const {
5224   SDLoc SL(Op);
5225   SDValue Chain = Op.getOperand(0);
5226 
5227   MachineFunction &MF = DAG.getMachineFunction();
5228   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5229   Register UserSGPR = Info->getQueuePtrUserSGPR();
5230   assert(UserSGPR != AMDGPU::NoRegister);
5231   SDValue QueuePtr = CreateLiveInRegister(
5232     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5233   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5234   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5235                                    QueuePtr, SDValue());
5236 
5237   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5238   SDValue Ops[] = {
5239     ToReg,
5240     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5241     SGPR01,
5242     ToReg.getValue(1)
5243   };
5244   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5245 }
5246 
5247 SDValue SITargetLowering::lowerTrapHsa(
5248     SDValue Op, SelectionDAG &DAG) const {
5249   SDLoc SL(Op);
5250   SDValue Chain = Op.getOperand(0);
5251 
5252   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5253   SDValue Ops[] = {
5254     Chain,
5255     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5256   };
5257   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5258 }
5259 
5260 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5261   SDLoc SL(Op);
5262   SDValue Chain = Op.getOperand(0);
5263   MachineFunction &MF = DAG.getMachineFunction();
5264 
5265   if (!Subtarget->isTrapHandlerEnabled() ||
5266       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5267     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5268                                      "debugtrap handler not supported",
5269                                      Op.getDebugLoc(),
5270                                      DS_Warning);
5271     LLVMContext &Ctx = MF.getFunction().getContext();
5272     Ctx.diagnose(NoTrap);
5273     return Chain;
5274   }
5275 
5276   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5277   SDValue Ops[] = {
5278     Chain,
5279     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5280   };
5281   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5282 }
5283 
5284 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5285                                              SelectionDAG &DAG) const {
5286   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5287   if (Subtarget->hasApertureRegs()) {
5288     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5289         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5290         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5291     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5292         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5293         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5294     unsigned Encoding =
5295         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5296         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5297         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5298 
5299     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5300     SDValue ApertureReg = SDValue(
5301         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5302     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5303     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5304   }
5305 
5306   MachineFunction &MF = DAG.getMachineFunction();
5307   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5308   Register UserSGPR = Info->getQueuePtrUserSGPR();
5309   assert(UserSGPR != AMDGPU::NoRegister);
5310 
5311   SDValue QueuePtr = CreateLiveInRegister(
5312     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5313 
5314   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5315   // private_segment_aperture_base_hi.
5316   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5317 
5318   SDValue Ptr =
5319       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5320 
5321   // TODO: Use custom target PseudoSourceValue.
5322   // TODO: We should use the value from the IR intrinsic call, but it might not
5323   // be available and how do we get it?
5324   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5325   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5326                      commonAlignment(Align(64), StructOffset),
5327                      MachineMemOperand::MODereferenceable |
5328                          MachineMemOperand::MOInvariant);
5329 }
5330 
5331 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5332                                              SelectionDAG &DAG) const {
5333   SDLoc SL(Op);
5334   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5335 
5336   SDValue Src = ASC->getOperand(0);
5337   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5338 
5339   const AMDGPUTargetMachine &TM =
5340     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5341 
5342   // flat -> local/private
5343   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5344     unsigned DestAS = ASC->getDestAddressSpace();
5345 
5346     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5347         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5348       unsigned NullVal = TM.getNullPointerValue(DestAS);
5349       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5350       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5351       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5352 
5353       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5354                          NonNull, Ptr, SegmentNullPtr);
5355     }
5356   }
5357 
5358   // local/private -> flat
5359   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5360     unsigned SrcAS = ASC->getSrcAddressSpace();
5361 
5362     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5363         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5364       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5365       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5366 
5367       SDValue NonNull
5368         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5369 
5370       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5371       SDValue CvtPtr
5372         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5373 
5374       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5375                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5376                          FlatNullPtr);
5377     }
5378   }
5379 
5380   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5381       Src.getValueType() == MVT::i64)
5382     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5383 
5384   // global <-> flat are no-ops and never emitted.
5385 
5386   const MachineFunction &MF = DAG.getMachineFunction();
5387   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5388     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5389   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5390 
5391   return DAG.getUNDEF(ASC->getValueType(0));
5392 }
5393 
5394 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5395 // the small vector and inserting them into the big vector. That is better than
5396 // the default expansion of doing it via a stack slot. Even though the use of
5397 // the stack slot would be optimized away afterwards, the stack slot itself
5398 // remains.
5399 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5400                                                 SelectionDAG &DAG) const {
5401   SDValue Vec = Op.getOperand(0);
5402   SDValue Ins = Op.getOperand(1);
5403   SDValue Idx = Op.getOperand(2);
5404   EVT VecVT = Vec.getValueType();
5405   EVT InsVT = Ins.getValueType();
5406   EVT EltVT = VecVT.getVectorElementType();
5407   unsigned InsNumElts = InsVT.getVectorNumElements();
5408   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5409   SDLoc SL(Op);
5410 
5411   for (unsigned I = 0; I != InsNumElts; ++I) {
5412     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5413                               DAG.getConstant(I, SL, MVT::i32));
5414     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5415                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5416   }
5417   return Vec;
5418 }
5419 
5420 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5421                                                  SelectionDAG &DAG) const {
5422   SDValue Vec = Op.getOperand(0);
5423   SDValue InsVal = Op.getOperand(1);
5424   SDValue Idx = Op.getOperand(2);
5425   EVT VecVT = Vec.getValueType();
5426   EVT EltVT = VecVT.getVectorElementType();
5427   unsigned VecSize = VecVT.getSizeInBits();
5428   unsigned EltSize = EltVT.getSizeInBits();
5429 
5430 
5431   assert(VecSize <= 64);
5432 
5433   unsigned NumElts = VecVT.getVectorNumElements();
5434   SDLoc SL(Op);
5435   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5436 
5437   if (NumElts == 4 && EltSize == 16 && KIdx) {
5438     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5439 
5440     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5441                                  DAG.getConstant(0, SL, MVT::i32));
5442     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5443                                  DAG.getConstant(1, SL, MVT::i32));
5444 
5445     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5446     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5447 
5448     unsigned Idx = KIdx->getZExtValue();
5449     bool InsertLo = Idx < 2;
5450     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5451       InsertLo ? LoVec : HiVec,
5452       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5453       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5454 
5455     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5456 
5457     SDValue Concat = InsertLo ?
5458       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5459       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5460 
5461     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5462   }
5463 
5464   if (isa<ConstantSDNode>(Idx))
5465     return SDValue();
5466 
5467   MVT IntVT = MVT::getIntegerVT(VecSize);
5468 
5469   // Avoid stack access for dynamic indexing.
5470   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5471 
5472   // Create a congruent vector with the target value in each element so that
5473   // the required element can be masked and ORed into the target vector.
5474   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5475                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5476 
5477   assert(isPowerOf2_32(EltSize));
5478   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5479 
5480   // Convert vector index to bit-index.
5481   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5482 
5483   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5484   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5485                             DAG.getConstant(0xffff, SL, IntVT),
5486                             ScaledIdx);
5487 
5488   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5489   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5490                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5491 
5492   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5493   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5494 }
5495 
5496 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5497                                                   SelectionDAG &DAG) const {
5498   SDLoc SL(Op);
5499 
5500   EVT ResultVT = Op.getValueType();
5501   SDValue Vec = Op.getOperand(0);
5502   SDValue Idx = Op.getOperand(1);
5503   EVT VecVT = Vec.getValueType();
5504   unsigned VecSize = VecVT.getSizeInBits();
5505   EVT EltVT = VecVT.getVectorElementType();
5506   assert(VecSize <= 64);
5507 
5508   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5509 
5510   // Make sure we do any optimizations that will make it easier to fold
5511   // source modifiers before obscuring it with bit operations.
5512 
5513   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5514   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5515     return Combined;
5516 
5517   unsigned EltSize = EltVT.getSizeInBits();
5518   assert(isPowerOf2_32(EltSize));
5519 
5520   MVT IntVT = MVT::getIntegerVT(VecSize);
5521   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5522 
5523   // Convert vector index to bit-index (* EltSize)
5524   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5525 
5526   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5527   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5528 
5529   if (ResultVT == MVT::f16) {
5530     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5531     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5532   }
5533 
5534   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5535 }
5536 
5537 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5538   assert(Elt % 2 == 0);
5539   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5540 }
5541 
5542 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5543                                               SelectionDAG &DAG) const {
5544   SDLoc SL(Op);
5545   EVT ResultVT = Op.getValueType();
5546   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5547 
5548   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5549   EVT EltVT = PackVT.getVectorElementType();
5550   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5551 
5552   // vector_shuffle <0,1,6,7> lhs, rhs
5553   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5554   //
5555   // vector_shuffle <6,7,2,3> lhs, rhs
5556   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5557   //
5558   // vector_shuffle <6,7,0,1> lhs, rhs
5559   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5560 
5561   // Avoid scalarizing when both halves are reading from consecutive elements.
5562   SmallVector<SDValue, 4> Pieces;
5563   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5564     if (elementPairIsContiguous(SVN->getMask(), I)) {
5565       const int Idx = SVN->getMaskElt(I);
5566       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5567       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5568       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5569                                     PackVT, SVN->getOperand(VecIdx),
5570                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5571       Pieces.push_back(SubVec);
5572     } else {
5573       const int Idx0 = SVN->getMaskElt(I);
5574       const int Idx1 = SVN->getMaskElt(I + 1);
5575       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5576       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5577       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5578       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5579 
5580       SDValue Vec0 = SVN->getOperand(VecIdx0);
5581       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5582                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5583 
5584       SDValue Vec1 = SVN->getOperand(VecIdx1);
5585       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5586                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5587       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5588     }
5589   }
5590 
5591   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5592 }
5593 
5594 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5595                                             SelectionDAG &DAG) const {
5596   SDLoc SL(Op);
5597   EVT VT = Op.getValueType();
5598 
5599   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5600     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5601 
5602     // Turn into pair of packed build_vectors.
5603     // TODO: Special case for constants that can be materialized with s_mov_b64.
5604     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5605                                     { Op.getOperand(0), Op.getOperand(1) });
5606     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5607                                     { Op.getOperand(2), Op.getOperand(3) });
5608 
5609     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5610     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5611 
5612     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5613     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5614   }
5615 
5616   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5617   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5618 
5619   SDValue Lo = Op.getOperand(0);
5620   SDValue Hi = Op.getOperand(1);
5621 
5622   // Avoid adding defined bits with the zero_extend.
5623   if (Hi.isUndef()) {
5624     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5625     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5626     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5627   }
5628 
5629   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5630   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5631 
5632   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5633                               DAG.getConstant(16, SL, MVT::i32));
5634   if (Lo.isUndef())
5635     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5636 
5637   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5638   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5639 
5640   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5641   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5642 }
5643 
5644 bool
5645 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5646   // We can fold offsets for anything that doesn't require a GOT relocation.
5647   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5648           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5649           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5650          !shouldEmitGOTReloc(GA->getGlobal());
5651 }
5652 
5653 static SDValue
5654 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5655                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5656                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5657   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5658   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5659   // lowered to the following code sequence:
5660   //
5661   // For constant address space:
5662   //   s_getpc_b64 s[0:1]
5663   //   s_add_u32 s0, s0, $symbol
5664   //   s_addc_u32 s1, s1, 0
5665   //
5666   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5667   //   a fixup or relocation is emitted to replace $symbol with a literal
5668   //   constant, which is a pc-relative offset from the encoding of the $symbol
5669   //   operand to the global variable.
5670   //
5671   // For global address space:
5672   //   s_getpc_b64 s[0:1]
5673   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5674   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5675   //
5676   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5677   //   fixups or relocations are emitted to replace $symbol@*@lo and
5678   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5679   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5680   //   operand to the global variable.
5681   //
5682   // What we want here is an offset from the value returned by s_getpc
5683   // (which is the address of the s_add_u32 instruction) to the global
5684   // variable, but since the encoding of $symbol starts 4 bytes after the start
5685   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5686   // small. This requires us to add 4 to the global variable offset in order to
5687   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5688   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5689   // instruction.
5690   SDValue PtrLo =
5691       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5692   SDValue PtrHi;
5693   if (GAFlags == SIInstrInfo::MO_NONE) {
5694     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5695   } else {
5696     PtrHi =
5697         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5698   }
5699   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5700 }
5701 
5702 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5703                                              SDValue Op,
5704                                              SelectionDAG &DAG) const {
5705   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5706   SDLoc DL(GSD);
5707   EVT PtrVT = Op.getValueType();
5708 
5709   const GlobalValue *GV = GSD->getGlobal();
5710   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5711        shouldUseLDSConstAddress(GV)) ||
5712       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5713       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5714     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5715         GV->hasExternalLinkage()) {
5716       Type *Ty = GV->getValueType();
5717       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5718       // zero-sized type in other languages to declare the dynamic shared
5719       // memory which size is not known at the compile time. They will be
5720       // allocated by the runtime and placed directly after the static
5721       // allocated ones. They all share the same offset.
5722       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5723         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5724         // Adjust alignment for that dynamic shared memory array.
5725         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5726         return SDValue(
5727             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5728       }
5729     }
5730     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5731   }
5732 
5733   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5734     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5735                                             SIInstrInfo::MO_ABS32_LO);
5736     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5737   }
5738 
5739   if (shouldEmitFixup(GV))
5740     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5741   else if (shouldEmitPCReloc(GV))
5742     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5743                                    SIInstrInfo::MO_REL32);
5744 
5745   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5746                                             SIInstrInfo::MO_GOTPCREL32);
5747 
5748   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5749   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5750   const DataLayout &DataLayout = DAG.getDataLayout();
5751   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5752   MachinePointerInfo PtrInfo
5753     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5754 
5755   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5756                      MachineMemOperand::MODereferenceable |
5757                          MachineMemOperand::MOInvariant);
5758 }
5759 
5760 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5761                                    const SDLoc &DL, SDValue V) const {
5762   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5763   // the destination register.
5764   //
5765   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5766   // so we will end up with redundant moves to m0.
5767   //
5768   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5769 
5770   // A Null SDValue creates a glue result.
5771   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5772                                   V, Chain);
5773   return SDValue(M0, 0);
5774 }
5775 
5776 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5777                                                  SDValue Op,
5778                                                  MVT VT,
5779                                                  unsigned Offset) const {
5780   SDLoc SL(Op);
5781   SDValue Param = lowerKernargMemParameter(
5782       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5783   // The local size values will have the hi 16-bits as zero.
5784   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5785                      DAG.getValueType(VT));
5786 }
5787 
5788 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5789                                         EVT VT) {
5790   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5791                                       "non-hsa intrinsic with hsa target",
5792                                       DL.getDebugLoc());
5793   DAG.getContext()->diagnose(BadIntrin);
5794   return DAG.getUNDEF(VT);
5795 }
5796 
5797 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5798                                          EVT VT) {
5799   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5800                                       "intrinsic not supported on subtarget",
5801                                       DL.getDebugLoc());
5802   DAG.getContext()->diagnose(BadIntrin);
5803   return DAG.getUNDEF(VT);
5804 }
5805 
5806 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5807                                     ArrayRef<SDValue> Elts) {
5808   assert(!Elts.empty());
5809   MVT Type;
5810   unsigned NumElts;
5811 
5812   if (Elts.size() == 1) {
5813     Type = MVT::f32;
5814     NumElts = 1;
5815   } else if (Elts.size() == 2) {
5816     Type = MVT::v2f32;
5817     NumElts = 2;
5818   } else if (Elts.size() == 3) {
5819     Type = MVT::v3f32;
5820     NumElts = 3;
5821   } else if (Elts.size() <= 4) {
5822     Type = MVT::v4f32;
5823     NumElts = 4;
5824   } else if (Elts.size() <= 5) {
5825     Type = MVT::v5f32;
5826     NumElts = 5;
5827   } else if (Elts.size() <= 8) {
5828     Type = MVT::v8f32;
5829     NumElts = 8;
5830   } else {
5831     assert(Elts.size() <= 16);
5832     Type = MVT::v16f32;
5833     NumElts = 16;
5834   }
5835 
5836   SmallVector<SDValue, 16> VecElts(NumElts);
5837   for (unsigned i = 0; i < Elts.size(); ++i) {
5838     SDValue Elt = Elts[i];
5839     if (Elt.getValueType() != MVT::f32)
5840       Elt = DAG.getBitcast(MVT::f32, Elt);
5841     VecElts[i] = Elt;
5842   }
5843   for (unsigned i = Elts.size(); i < NumElts; ++i)
5844     VecElts[i] = DAG.getUNDEF(MVT::f32);
5845 
5846   if (NumElts == 1)
5847     return VecElts[0];
5848   return DAG.getBuildVector(Type, DL, VecElts);
5849 }
5850 
5851 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5852                               SDValue Src, int ExtraElts) {
5853   EVT SrcVT = Src.getValueType();
5854 
5855   SmallVector<SDValue, 8> Elts;
5856 
5857   if (SrcVT.isVector())
5858     DAG.ExtractVectorElements(Src, Elts);
5859   else
5860     Elts.push_back(Src);
5861 
5862   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5863   while (ExtraElts--)
5864     Elts.push_back(Undef);
5865 
5866   return DAG.getBuildVector(CastVT, DL, Elts);
5867 }
5868 
5869 // Re-construct the required return value for a image load intrinsic.
5870 // This is more complicated due to the optional use TexFailCtrl which means the required
5871 // return type is an aggregate
5872 static SDValue constructRetValue(SelectionDAG &DAG,
5873                                  MachineSDNode *Result,
5874                                  ArrayRef<EVT> ResultTypes,
5875                                  bool IsTexFail, bool Unpacked, bool IsD16,
5876                                  int DMaskPop, int NumVDataDwords,
5877                                  const SDLoc &DL) {
5878   // Determine the required return type. This is the same regardless of IsTexFail flag
5879   EVT ReqRetVT = ResultTypes[0];
5880   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5881   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5882     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5883 
5884   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5885     DMaskPop : (DMaskPop + 1) / 2;
5886 
5887   MVT DataDwordVT = NumDataDwords == 1 ?
5888     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5889 
5890   MVT MaskPopVT = MaskPopDwords == 1 ?
5891     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5892 
5893   SDValue Data(Result, 0);
5894   SDValue TexFail;
5895 
5896   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5897     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5898     if (MaskPopVT.isVector()) {
5899       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5900                          SDValue(Result, 0), ZeroIdx);
5901     } else {
5902       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5903                          SDValue(Result, 0), ZeroIdx);
5904     }
5905   }
5906 
5907   if (DataDwordVT.isVector())
5908     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5909                           NumDataDwords - MaskPopDwords);
5910 
5911   if (IsD16)
5912     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5913 
5914   EVT LegalReqRetVT = ReqRetVT;
5915   if (!ReqRetVT.isVector()) {
5916     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5917   } else {
5918     // We need to widen the return vector to a legal type
5919     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5920         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5921       LegalReqRetVT =
5922           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5923                            ReqRetVT.getVectorNumElements() + 1);
5924     }
5925   }
5926   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5927 
5928   if (IsTexFail) {
5929     TexFail =
5930         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5931                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5932 
5933     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5934   }
5935 
5936   if (Result->getNumValues() == 1)
5937     return Data;
5938 
5939   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5940 }
5941 
5942 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5943                          SDValue *LWE, bool &IsTexFail) {
5944   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5945 
5946   uint64_t Value = TexFailCtrlConst->getZExtValue();
5947   if (Value) {
5948     IsTexFail = true;
5949   }
5950 
5951   SDLoc DL(TexFailCtrlConst);
5952   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5953   Value &= ~(uint64_t)0x1;
5954   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5955   Value &= ~(uint64_t)0x2;
5956 
5957   return Value == 0;
5958 }
5959 
5960 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
5961                                       MVT PackVectorVT,
5962                                       SmallVectorImpl<SDValue> &PackedAddrs,
5963                                       unsigned DimIdx, unsigned EndIdx,
5964                                       unsigned NumGradients) {
5965   SDLoc DL(Op);
5966   for (unsigned I = DimIdx; I < EndIdx; I++) {
5967     SDValue Addr = Op.getOperand(I);
5968 
5969     // Gradients are packed with undef for each coordinate.
5970     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5971     // 1D: undef,dx/dh; undef,dx/dv
5972     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5973     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5974     if (((I + 1) >= EndIdx) ||
5975         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5976                                          I == DimIdx + NumGradients - 1))) {
5977       if (Addr.getValueType() != MVT::i16)
5978         Addr = DAG.getBitcast(MVT::i16, Addr);
5979       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5980     } else {
5981       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5982       I++;
5983     }
5984     Addr = DAG.getBitcast(MVT::f32, Addr);
5985     PackedAddrs.push_back(Addr);
5986   }
5987 }
5988 
5989 SDValue SITargetLowering::lowerImage(SDValue Op,
5990                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5991                                      SelectionDAG &DAG, bool WithChain) const {
5992   SDLoc DL(Op);
5993   MachineFunction &MF = DAG.getMachineFunction();
5994   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5995   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5996       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5997   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5998   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5999       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6000   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6001       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6002   unsigned IntrOpcode = Intr->BaseOpcode;
6003   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6004 
6005   SmallVector<EVT, 3> ResultTypes(Op->values());
6006   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6007   bool IsD16 = false;
6008   bool IsG16 = false;
6009   bool IsA16 = false;
6010   SDValue VData;
6011   int NumVDataDwords;
6012   bool AdjustRetType = false;
6013 
6014   // Offset of intrinsic arguments
6015   const unsigned ArgOffset = WithChain ? 2 : 1;
6016 
6017   unsigned DMask;
6018   unsigned DMaskLanes = 0;
6019 
6020   if (BaseOpcode->Atomic) {
6021     VData = Op.getOperand(2);
6022 
6023     bool Is64Bit = VData.getValueType() == MVT::i64;
6024     if (BaseOpcode->AtomicX2) {
6025       SDValue VData2 = Op.getOperand(3);
6026       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6027                                  {VData, VData2});
6028       if (Is64Bit)
6029         VData = DAG.getBitcast(MVT::v4i32, VData);
6030 
6031       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6032       DMask = Is64Bit ? 0xf : 0x3;
6033       NumVDataDwords = Is64Bit ? 4 : 2;
6034     } else {
6035       DMask = Is64Bit ? 0x3 : 0x1;
6036       NumVDataDwords = Is64Bit ? 2 : 1;
6037     }
6038   } else {
6039     auto *DMaskConst =
6040         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6041     DMask = DMaskConst->getZExtValue();
6042     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6043 
6044     if (BaseOpcode->Store) {
6045       VData = Op.getOperand(2);
6046 
6047       MVT StoreVT = VData.getSimpleValueType();
6048       if (StoreVT.getScalarType() == MVT::f16) {
6049         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6050           return Op; // D16 is unsupported for this instruction
6051 
6052         IsD16 = true;
6053         VData = handleD16VData(VData, DAG, true);
6054       }
6055 
6056       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6057     } else {
6058       // Work out the num dwords based on the dmask popcount and underlying type
6059       // and whether packing is supported.
6060       MVT LoadVT = ResultTypes[0].getSimpleVT();
6061       if (LoadVT.getScalarType() == MVT::f16) {
6062         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6063           return Op; // D16 is unsupported for this instruction
6064 
6065         IsD16 = true;
6066       }
6067 
6068       // Confirm that the return type is large enough for the dmask specified
6069       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6070           (!LoadVT.isVector() && DMaskLanes > 1))
6071           return Op;
6072 
6073       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6074       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6075       // instructions.
6076       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6077           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6078         NumVDataDwords = (DMaskLanes + 1) / 2;
6079       else
6080         NumVDataDwords = DMaskLanes;
6081 
6082       AdjustRetType = true;
6083     }
6084   }
6085 
6086   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6087   SmallVector<SDValue, 4> VAddrs;
6088 
6089   // Optimize _L to _LZ when _L is zero
6090   if (LZMappingInfo) {
6091     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6092             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6093       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6094         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6095         VAddrEnd--;                      // remove 'lod'
6096       }
6097     }
6098   }
6099 
6100   // Optimize _mip away, when 'lod' is zero
6101   if (MIPMappingInfo) {
6102     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6103             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6104       if (ConstantLod->isNullValue()) {
6105         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6106         VAddrEnd--;                           // remove 'mip'
6107       }
6108     }
6109   }
6110 
6111   // Push back extra arguments.
6112   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6113     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6114 
6115   // Check for 16 bit addresses or derivatives and pack if true.
6116   MVT VAddrVT =
6117       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6118   MVT VAddrScalarVT = VAddrVT.getScalarType();
6119   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6120   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6121 
6122   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6123   VAddrScalarVT = VAddrVT.getScalarType();
6124   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6125   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6126 
6127   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6128     // 16 bit gradients are supported, but are tied to the A16 control
6129     // so both gradients and addresses must be 16 bit
6130     LLVM_DEBUG(
6131         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6132                   "require 16 bit args for both gradients and addresses");
6133     return Op;
6134   }
6135 
6136   if (IsA16) {
6137     if (!ST->hasA16()) {
6138       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6139                            "support 16 bit addresses\n");
6140       return Op;
6141     }
6142   }
6143 
6144   // We've dealt with incorrect input so we know that if IsA16, IsG16
6145   // are set then we have to compress/pack operands (either address,
6146   // gradient or both)
6147   // In the case where a16 and gradients are tied (no G16 support) then we
6148   // have already verified that both IsA16 and IsG16 are true
6149   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6150     // Activate g16
6151     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6152         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6153     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6154   }
6155 
6156   // Add gradients (packed or unpacked)
6157   if (IsG16) {
6158     // Pack the gradients
6159     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6160     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6161                               ArgOffset + Intr->GradientStart,
6162                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6163   } else {
6164     for (unsigned I = ArgOffset + Intr->GradientStart;
6165          I < ArgOffset + Intr->CoordStart; I++)
6166       VAddrs.push_back(Op.getOperand(I));
6167   }
6168 
6169   // Add addresses (packed or unpacked)
6170   if (IsA16) {
6171     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6172                               ArgOffset + Intr->CoordStart, VAddrEnd,
6173                               0 /* No gradients */);
6174   } else {
6175     // Add uncompressed address
6176     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6177       VAddrs.push_back(Op.getOperand(I));
6178   }
6179 
6180   // If the register allocator cannot place the address registers contiguously
6181   // without introducing moves, then using the non-sequential address encoding
6182   // is always preferable, since it saves VALU instructions and is usually a
6183   // wash in terms of code size or even better.
6184   //
6185   // However, we currently have no way of hinting to the register allocator that
6186   // MIMG addresses should be placed contiguously when it is possible to do so,
6187   // so force non-NSA for the common 2-address case as a heuristic.
6188   //
6189   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6190   // allocation when possible.
6191   bool UseNSA =
6192       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6193   SDValue VAddr;
6194   if (!UseNSA)
6195     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6196 
6197   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6198   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6199   SDValue Unorm;
6200   if (!BaseOpcode->Sampler) {
6201     Unorm = True;
6202   } else {
6203     auto UnormConst =
6204         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6205 
6206     Unorm = UnormConst->getZExtValue() ? True : False;
6207   }
6208 
6209   SDValue TFE;
6210   SDValue LWE;
6211   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6212   bool IsTexFail = false;
6213   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6214     return Op;
6215 
6216   if (IsTexFail) {
6217     if (!DMaskLanes) {
6218       // Expecting to get an error flag since TFC is on - and dmask is 0
6219       // Force dmask to be at least 1 otherwise the instruction will fail
6220       DMask = 0x1;
6221       DMaskLanes = 1;
6222       NumVDataDwords = 1;
6223     }
6224     NumVDataDwords += 1;
6225     AdjustRetType = true;
6226   }
6227 
6228   // Has something earlier tagged that the return type needs adjusting
6229   // This happens if the instruction is a load or has set TexFailCtrl flags
6230   if (AdjustRetType) {
6231     // NumVDataDwords reflects the true number of dwords required in the return type
6232     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6233       // This is a no-op load. This can be eliminated
6234       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6235       if (isa<MemSDNode>(Op))
6236         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6237       return Undef;
6238     }
6239 
6240     EVT NewVT = NumVDataDwords > 1 ?
6241                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6242                 : MVT::i32;
6243 
6244     ResultTypes[0] = NewVT;
6245     if (ResultTypes.size() == 3) {
6246       // Original result was aggregate type used for TexFailCtrl results
6247       // The actual instruction returns as a vector type which has now been
6248       // created. Remove the aggregate result.
6249       ResultTypes.erase(&ResultTypes[1]);
6250     }
6251   }
6252 
6253   unsigned CPol = cast<ConstantSDNode>(
6254       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6255   if (BaseOpcode->Atomic)
6256     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6257   if (CPol & ~AMDGPU::CPol::ALL)
6258     return Op;
6259 
6260   SmallVector<SDValue, 26> Ops;
6261   if (BaseOpcode->Store || BaseOpcode->Atomic)
6262     Ops.push_back(VData); // vdata
6263   if (UseNSA)
6264     append_range(Ops, VAddrs);
6265   else
6266     Ops.push_back(VAddr);
6267   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6268   if (BaseOpcode->Sampler)
6269     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6270   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6271   if (IsGFX10Plus)
6272     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6273   Ops.push_back(Unorm);
6274   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6275   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6276                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6277   if (IsGFX10Plus)
6278     Ops.push_back(IsA16 ? True : False);
6279   if (!Subtarget->hasGFX90AInsts()) {
6280     Ops.push_back(TFE); //tfe
6281   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6282     report_fatal_error("TFE is not supported on this GPU");
6283   }
6284   Ops.push_back(LWE); // lwe
6285   if (!IsGFX10Plus)
6286     Ops.push_back(DimInfo->DA ? True : False);
6287   if (BaseOpcode->HasD16)
6288     Ops.push_back(IsD16 ? True : False);
6289   if (isa<MemSDNode>(Op))
6290     Ops.push_back(Op.getOperand(0)); // chain
6291 
6292   int NumVAddrDwords =
6293       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6294   int Opcode = -1;
6295 
6296   if (IsGFX10Plus) {
6297     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6298                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6299                                           : AMDGPU::MIMGEncGfx10Default,
6300                                    NumVDataDwords, NumVAddrDwords);
6301   } else {
6302     if (Subtarget->hasGFX90AInsts()) {
6303       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6304                                      NumVDataDwords, NumVAddrDwords);
6305       if (Opcode == -1)
6306         report_fatal_error(
6307             "requested image instruction is not supported on this GPU");
6308     }
6309     if (Opcode == -1 &&
6310         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6311       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6312                                      NumVDataDwords, NumVAddrDwords);
6313     if (Opcode == -1)
6314       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6315                                      NumVDataDwords, NumVAddrDwords);
6316   }
6317   assert(Opcode != -1);
6318 
6319   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6320   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6321     MachineMemOperand *MemRef = MemOp->getMemOperand();
6322     DAG.setNodeMemRefs(NewNode, {MemRef});
6323   }
6324 
6325   if (BaseOpcode->AtomicX2) {
6326     SmallVector<SDValue, 1> Elt;
6327     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6328     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6329   }
6330   if (BaseOpcode->Store)
6331     return SDValue(NewNode, 0);
6332   return constructRetValue(DAG, NewNode,
6333                            OrigResultTypes, IsTexFail,
6334                            Subtarget->hasUnpackedD16VMem(), IsD16,
6335                            DMaskLanes, NumVDataDwords, DL);
6336 }
6337 
6338 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6339                                        SDValue Offset, SDValue CachePolicy,
6340                                        SelectionDAG &DAG) const {
6341   MachineFunction &MF = DAG.getMachineFunction();
6342 
6343   const DataLayout &DataLayout = DAG.getDataLayout();
6344   Align Alignment =
6345       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6346 
6347   MachineMemOperand *MMO = MF.getMachineMemOperand(
6348       MachinePointerInfo(),
6349       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6350           MachineMemOperand::MOInvariant,
6351       VT.getStoreSize(), Alignment);
6352 
6353   if (!Offset->isDivergent()) {
6354     SDValue Ops[] = {
6355         Rsrc,
6356         Offset, // Offset
6357         CachePolicy
6358     };
6359 
6360     // Widen vec3 load to vec4.
6361     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6362       EVT WidenedVT =
6363           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6364       auto WidenedOp = DAG.getMemIntrinsicNode(
6365           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6366           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6367       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6368                                    DAG.getVectorIdxConstant(0, DL));
6369       return Subvector;
6370     }
6371 
6372     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6373                                    DAG.getVTList(VT), Ops, VT, MMO);
6374   }
6375 
6376   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6377   // assume that the buffer is unswizzled.
6378   SmallVector<SDValue, 4> Loads;
6379   unsigned NumLoads = 1;
6380   MVT LoadVT = VT.getSimpleVT();
6381   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6382   assert((LoadVT.getScalarType() == MVT::i32 ||
6383           LoadVT.getScalarType() == MVT::f32));
6384 
6385   if (NumElts == 8 || NumElts == 16) {
6386     NumLoads = NumElts / 4;
6387     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6388   }
6389 
6390   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6391   SDValue Ops[] = {
6392       DAG.getEntryNode(),                               // Chain
6393       Rsrc,                                             // rsrc
6394       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6395       {},                                               // voffset
6396       {},                                               // soffset
6397       {},                                               // offset
6398       CachePolicy,                                      // cachepolicy
6399       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6400   };
6401 
6402   // Use the alignment to ensure that the required offsets will fit into the
6403   // immediate offsets.
6404   setBufferOffsets(Offset, DAG, &Ops[3],
6405                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6406 
6407   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6408   for (unsigned i = 0; i < NumLoads; ++i) {
6409     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6410     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6411                                         LoadVT, MMO, DAG));
6412   }
6413 
6414   if (NumElts == 8 || NumElts == 16)
6415     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6416 
6417   return Loads[0];
6418 }
6419 
6420 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6421                                                   SelectionDAG &DAG) const {
6422   MachineFunction &MF = DAG.getMachineFunction();
6423   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6424 
6425   EVT VT = Op.getValueType();
6426   SDLoc DL(Op);
6427   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6428 
6429   // TODO: Should this propagate fast-math-flags?
6430 
6431   switch (IntrinsicID) {
6432   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6433     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6434       return emitNonHSAIntrinsicError(DAG, DL, VT);
6435     return getPreloadedValue(DAG, *MFI, VT,
6436                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6437   }
6438   case Intrinsic::amdgcn_dispatch_ptr:
6439   case Intrinsic::amdgcn_queue_ptr: {
6440     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6441       DiagnosticInfoUnsupported BadIntrin(
6442           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6443           DL.getDebugLoc());
6444       DAG.getContext()->diagnose(BadIntrin);
6445       return DAG.getUNDEF(VT);
6446     }
6447 
6448     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6449       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6450     return getPreloadedValue(DAG, *MFI, VT, RegID);
6451   }
6452   case Intrinsic::amdgcn_implicitarg_ptr: {
6453     if (MFI->isEntryFunction())
6454       return getImplicitArgPtr(DAG, DL);
6455     return getPreloadedValue(DAG, *MFI, VT,
6456                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6457   }
6458   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6459     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6460       // This only makes sense to call in a kernel, so just lower to null.
6461       return DAG.getConstant(0, DL, VT);
6462     }
6463 
6464     return getPreloadedValue(DAG, *MFI, VT,
6465                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6466   }
6467   case Intrinsic::amdgcn_dispatch_id: {
6468     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6469   }
6470   case Intrinsic::amdgcn_rcp:
6471     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6472   case Intrinsic::amdgcn_rsq:
6473     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6474   case Intrinsic::amdgcn_rsq_legacy:
6475     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6476       return emitRemovedIntrinsicError(DAG, DL, VT);
6477     return SDValue();
6478   case Intrinsic::amdgcn_rcp_legacy:
6479     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6480       return emitRemovedIntrinsicError(DAG, DL, VT);
6481     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6482   case Intrinsic::amdgcn_rsq_clamp: {
6483     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6484       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6485 
6486     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6487     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6488     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6489 
6490     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6491     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6492                               DAG.getConstantFP(Max, DL, VT));
6493     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6494                        DAG.getConstantFP(Min, DL, VT));
6495   }
6496   case Intrinsic::r600_read_ngroups_x:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6501                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6502                                     false);
6503   case Intrinsic::r600_read_ngroups_y:
6504     if (Subtarget->isAmdHsaOS())
6505       return emitNonHSAIntrinsicError(DAG, DL, VT);
6506 
6507     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6508                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6509                                     false);
6510   case Intrinsic::r600_read_ngroups_z:
6511     if (Subtarget->isAmdHsaOS())
6512       return emitNonHSAIntrinsicError(DAG, DL, VT);
6513 
6514     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6515                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6516                                     false);
6517   case Intrinsic::r600_read_global_size_x:
6518     if (Subtarget->isAmdHsaOS())
6519       return emitNonHSAIntrinsicError(DAG, DL, VT);
6520 
6521     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6522                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6523                                     Align(4), false);
6524   case Intrinsic::r600_read_global_size_y:
6525     if (Subtarget->isAmdHsaOS())
6526       return emitNonHSAIntrinsicError(DAG, DL, VT);
6527 
6528     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6529                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6530                                     Align(4), false);
6531   case Intrinsic::r600_read_global_size_z:
6532     if (Subtarget->isAmdHsaOS())
6533       return emitNonHSAIntrinsicError(DAG, DL, VT);
6534 
6535     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6536                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6537                                     Align(4), false);
6538   case Intrinsic::r600_read_local_size_x:
6539     if (Subtarget->isAmdHsaOS())
6540       return emitNonHSAIntrinsicError(DAG, DL, VT);
6541 
6542     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6543                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6544   case Intrinsic::r600_read_local_size_y:
6545     if (Subtarget->isAmdHsaOS())
6546       return emitNonHSAIntrinsicError(DAG, DL, VT);
6547 
6548     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6549                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6550   case Intrinsic::r600_read_local_size_z:
6551     if (Subtarget->isAmdHsaOS())
6552       return emitNonHSAIntrinsicError(DAG, DL, VT);
6553 
6554     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6555                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6556   case Intrinsic::amdgcn_workgroup_id_x:
6557     return getPreloadedValue(DAG, *MFI, VT,
6558                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6559   case Intrinsic::amdgcn_workgroup_id_y:
6560     return getPreloadedValue(DAG, *MFI, VT,
6561                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6562   case Intrinsic::amdgcn_workgroup_id_z:
6563     return getPreloadedValue(DAG, *MFI, VT,
6564                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6565   case Intrinsic::amdgcn_workitem_id_x:
6566     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6567                           SDLoc(DAG.getEntryNode()),
6568                           MFI->getArgInfo().WorkItemIDX);
6569   case Intrinsic::amdgcn_workitem_id_y:
6570     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6571                           SDLoc(DAG.getEntryNode()),
6572                           MFI->getArgInfo().WorkItemIDY);
6573   case Intrinsic::amdgcn_workitem_id_z:
6574     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6575                           SDLoc(DAG.getEntryNode()),
6576                           MFI->getArgInfo().WorkItemIDZ);
6577   case Intrinsic::amdgcn_wavefrontsize:
6578     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6579                            SDLoc(Op), MVT::i32);
6580   case Intrinsic::amdgcn_s_buffer_load: {
6581     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6582     if (CPol & ~AMDGPU::CPol::ALL)
6583       return Op;
6584     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6585                         DAG);
6586   }
6587   case Intrinsic::amdgcn_fdiv_fast:
6588     return lowerFDIV_FAST(Op, DAG);
6589   case Intrinsic::amdgcn_sin:
6590     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6591 
6592   case Intrinsic::amdgcn_cos:
6593     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6594 
6595   case Intrinsic::amdgcn_mul_u24:
6596     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6597   case Intrinsic::amdgcn_mul_i24:
6598     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6599 
6600   case Intrinsic::amdgcn_log_clamp: {
6601     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6602       return SDValue();
6603 
6604     return emitRemovedIntrinsicError(DAG, DL, VT);
6605   }
6606   case Intrinsic::amdgcn_ldexp:
6607     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6608                        Op.getOperand(1), Op.getOperand(2));
6609 
6610   case Intrinsic::amdgcn_fract:
6611     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6612 
6613   case Intrinsic::amdgcn_class:
6614     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6615                        Op.getOperand(1), Op.getOperand(2));
6616   case Intrinsic::amdgcn_div_fmas:
6617     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6618                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6619                        Op.getOperand(4));
6620 
6621   case Intrinsic::amdgcn_div_fixup:
6622     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6623                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6624 
6625   case Intrinsic::amdgcn_div_scale: {
6626     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6627 
6628     // Translate to the operands expected by the machine instruction. The
6629     // first parameter must be the same as the first instruction.
6630     SDValue Numerator = Op.getOperand(1);
6631     SDValue Denominator = Op.getOperand(2);
6632 
6633     // Note this order is opposite of the machine instruction's operations,
6634     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6635     // intrinsic has the numerator as the first operand to match a normal
6636     // division operation.
6637 
6638     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6639 
6640     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6641                        Denominator, Numerator);
6642   }
6643   case Intrinsic::amdgcn_icmp: {
6644     // There is a Pat that handles this variant, so return it as-is.
6645     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6646         Op.getConstantOperandVal(2) == 0 &&
6647         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6648       return Op;
6649     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6650   }
6651   case Intrinsic::amdgcn_fcmp: {
6652     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6653   }
6654   case Intrinsic::amdgcn_ballot:
6655     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6656   case Intrinsic::amdgcn_fmed3:
6657     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6658                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6659   case Intrinsic::amdgcn_fdot2:
6660     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6661                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6662                        Op.getOperand(4));
6663   case Intrinsic::amdgcn_fmul_legacy:
6664     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6665                        Op.getOperand(1), Op.getOperand(2));
6666   case Intrinsic::amdgcn_sffbh:
6667     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6668   case Intrinsic::amdgcn_sbfe:
6669     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6670                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6671   case Intrinsic::amdgcn_ubfe:
6672     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6673                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6674   case Intrinsic::amdgcn_cvt_pkrtz:
6675   case Intrinsic::amdgcn_cvt_pknorm_i16:
6676   case Intrinsic::amdgcn_cvt_pknorm_u16:
6677   case Intrinsic::amdgcn_cvt_pk_i16:
6678   case Intrinsic::amdgcn_cvt_pk_u16: {
6679     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6680     EVT VT = Op.getValueType();
6681     unsigned Opcode;
6682 
6683     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6684       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6685     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6686       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6687     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6688       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6689     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6690       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6691     else
6692       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6693 
6694     if (isTypeLegal(VT))
6695       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6696 
6697     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6698                                Op.getOperand(1), Op.getOperand(2));
6699     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6700   }
6701   case Intrinsic::amdgcn_fmad_ftz:
6702     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6703                        Op.getOperand(2), Op.getOperand(3));
6704 
6705   case Intrinsic::amdgcn_if_break:
6706     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6707                                       Op->getOperand(1), Op->getOperand(2)), 0);
6708 
6709   case Intrinsic::amdgcn_groupstaticsize: {
6710     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6711     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6712       return Op;
6713 
6714     const Module *M = MF.getFunction().getParent();
6715     const GlobalValue *GV =
6716         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6717     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6718                                             SIInstrInfo::MO_ABS32_LO);
6719     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6720   }
6721   case Intrinsic::amdgcn_is_shared:
6722   case Intrinsic::amdgcn_is_private: {
6723     SDLoc SL(Op);
6724     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6725       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6726     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6727     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6728                                  Op.getOperand(1));
6729 
6730     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6731                                 DAG.getConstant(1, SL, MVT::i32));
6732     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6733   }
6734   case Intrinsic::amdgcn_alignbit:
6735     return DAG.getNode(ISD::FSHR, DL, VT,
6736                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6737   case Intrinsic::amdgcn_perm:
6738     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6739                        Op.getOperand(2), Op.getOperand(3));
6740   case Intrinsic::amdgcn_reloc_constant: {
6741     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6742     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6743     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6744     auto RelocSymbol = cast<GlobalVariable>(
6745         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6746     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6747                                             SIInstrInfo::MO_ABS32_LO);
6748     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6749   }
6750   default:
6751     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6752             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6753       return lowerImage(Op, ImageDimIntr, DAG, false);
6754 
6755     return Op;
6756   }
6757 }
6758 
6759 // This function computes an appropriate offset to pass to
6760 // MachineMemOperand::setOffset() based on the offset inputs to
6761 // an intrinsic.  If any of the offsets are non-contstant or
6762 // if VIndex is non-zero then this function returns 0.  Otherwise,
6763 // it returns the sum of VOffset, SOffset, and Offset.
6764 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6765                                       SDValue SOffset,
6766                                       SDValue Offset,
6767                                       SDValue VIndex = SDValue()) {
6768 
6769   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6770       !isa<ConstantSDNode>(Offset))
6771     return 0;
6772 
6773   if (VIndex) {
6774     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6775       return 0;
6776   }
6777 
6778   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6779          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6780          cast<ConstantSDNode>(Offset)->getSExtValue();
6781 }
6782 
6783 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6784                                                      SelectionDAG &DAG,
6785                                                      unsigned NewOpcode) const {
6786   SDLoc DL(Op);
6787 
6788   SDValue VData = Op.getOperand(2);
6789   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6790   SDValue Ops[] = {
6791     Op.getOperand(0), // Chain
6792     VData,            // vdata
6793     Op.getOperand(3), // rsrc
6794     DAG.getConstant(0, DL, MVT::i32), // vindex
6795     Offsets.first,    // voffset
6796     Op.getOperand(5), // soffset
6797     Offsets.second,   // offset
6798     Op.getOperand(6), // cachepolicy
6799     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6800   };
6801 
6802   auto *M = cast<MemSDNode>(Op);
6803   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6804 
6805   EVT MemVT = VData.getValueType();
6806   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6807                                  M->getMemOperand());
6808 }
6809 
6810 SDValue
6811 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6812                                                 unsigned NewOpcode) const {
6813   SDLoc DL(Op);
6814 
6815   SDValue VData = Op.getOperand(2);
6816   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6817   SDValue Ops[] = {
6818     Op.getOperand(0), // Chain
6819     VData,            // vdata
6820     Op.getOperand(3), // rsrc
6821     Op.getOperand(4), // vindex
6822     Offsets.first,    // voffset
6823     Op.getOperand(6), // soffset
6824     Offsets.second,   // offset
6825     Op.getOperand(7), // cachepolicy
6826     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6827   };
6828 
6829   auto *M = cast<MemSDNode>(Op);
6830   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6831                                                       Ops[3]));
6832 
6833   EVT MemVT = VData.getValueType();
6834   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6835                                  M->getMemOperand());
6836 }
6837 
6838 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6839                                                  SelectionDAG &DAG) const {
6840   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6841   SDLoc DL(Op);
6842 
6843   switch (IntrID) {
6844   case Intrinsic::amdgcn_ds_ordered_add:
6845   case Intrinsic::amdgcn_ds_ordered_swap: {
6846     MemSDNode *M = cast<MemSDNode>(Op);
6847     SDValue Chain = M->getOperand(0);
6848     SDValue M0 = M->getOperand(2);
6849     SDValue Value = M->getOperand(3);
6850     unsigned IndexOperand = M->getConstantOperandVal(7);
6851     unsigned WaveRelease = M->getConstantOperandVal(8);
6852     unsigned WaveDone = M->getConstantOperandVal(9);
6853 
6854     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6855     IndexOperand &= ~0x3f;
6856     unsigned CountDw = 0;
6857 
6858     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6859       CountDw = (IndexOperand >> 24) & 0xf;
6860       IndexOperand &= ~(0xf << 24);
6861 
6862       if (CountDw < 1 || CountDw > 4) {
6863         report_fatal_error(
6864             "ds_ordered_count: dword count must be between 1 and 4");
6865       }
6866     }
6867 
6868     if (IndexOperand)
6869       report_fatal_error("ds_ordered_count: bad index operand");
6870 
6871     if (WaveDone && !WaveRelease)
6872       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6873 
6874     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6875     unsigned ShaderType =
6876         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6877     unsigned Offset0 = OrderedCountIndex << 2;
6878     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6879                        (Instruction << 4);
6880 
6881     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6882       Offset1 |= (CountDw - 1) << 6;
6883 
6884     unsigned Offset = Offset0 | (Offset1 << 8);
6885 
6886     SDValue Ops[] = {
6887       Chain,
6888       Value,
6889       DAG.getTargetConstant(Offset, DL, MVT::i16),
6890       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6891     };
6892     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6893                                    M->getVTList(), Ops, M->getMemoryVT(),
6894                                    M->getMemOperand());
6895   }
6896   case Intrinsic::amdgcn_ds_fadd: {
6897     MemSDNode *M = cast<MemSDNode>(Op);
6898     unsigned Opc;
6899     switch (IntrID) {
6900     case Intrinsic::amdgcn_ds_fadd:
6901       Opc = ISD::ATOMIC_LOAD_FADD;
6902       break;
6903     }
6904 
6905     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6906                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6907                          M->getMemOperand());
6908   }
6909   case Intrinsic::amdgcn_atomic_inc:
6910   case Intrinsic::amdgcn_atomic_dec:
6911   case Intrinsic::amdgcn_ds_fmin:
6912   case Intrinsic::amdgcn_ds_fmax: {
6913     MemSDNode *M = cast<MemSDNode>(Op);
6914     unsigned Opc;
6915     switch (IntrID) {
6916     case Intrinsic::amdgcn_atomic_inc:
6917       Opc = AMDGPUISD::ATOMIC_INC;
6918       break;
6919     case Intrinsic::amdgcn_atomic_dec:
6920       Opc = AMDGPUISD::ATOMIC_DEC;
6921       break;
6922     case Intrinsic::amdgcn_ds_fmin:
6923       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6924       break;
6925     case Intrinsic::amdgcn_ds_fmax:
6926       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6927       break;
6928     default:
6929       llvm_unreachable("Unknown intrinsic!");
6930     }
6931     SDValue Ops[] = {
6932       M->getOperand(0), // Chain
6933       M->getOperand(2), // Ptr
6934       M->getOperand(3)  // Value
6935     };
6936 
6937     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6938                                    M->getMemoryVT(), M->getMemOperand());
6939   }
6940   case Intrinsic::amdgcn_buffer_load:
6941   case Intrinsic::amdgcn_buffer_load_format: {
6942     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6943     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6944     unsigned IdxEn = 1;
6945     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6946       IdxEn = Idx->getZExtValue() != 0;
6947     SDValue Ops[] = {
6948       Op.getOperand(0), // Chain
6949       Op.getOperand(2), // rsrc
6950       Op.getOperand(3), // vindex
6951       SDValue(),        // voffset -- will be set by setBufferOffsets
6952       SDValue(),        // soffset -- will be set by setBufferOffsets
6953       SDValue(),        // offset -- will be set by setBufferOffsets
6954       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6955       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6956     };
6957 
6958     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6959     // We don't know the offset if vindex is non-zero, so clear it.
6960     if (IdxEn)
6961       Offset = 0;
6962 
6963     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6964         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6965 
6966     EVT VT = Op.getValueType();
6967     EVT IntVT = VT.changeTypeToInteger();
6968     auto *M = cast<MemSDNode>(Op);
6969     M->getMemOperand()->setOffset(Offset);
6970     EVT LoadVT = Op.getValueType();
6971 
6972     if (LoadVT.getScalarType() == MVT::f16)
6973       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6974                                  M, DAG, Ops);
6975 
6976     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6977     if (LoadVT.getScalarType() == MVT::i8 ||
6978         LoadVT.getScalarType() == MVT::i16)
6979       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6980 
6981     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6982                                M->getMemOperand(), DAG);
6983   }
6984   case Intrinsic::amdgcn_raw_buffer_load:
6985   case Intrinsic::amdgcn_raw_buffer_load_format: {
6986     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6987 
6988     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6989     SDValue Ops[] = {
6990       Op.getOperand(0), // Chain
6991       Op.getOperand(2), // rsrc
6992       DAG.getConstant(0, DL, MVT::i32), // vindex
6993       Offsets.first,    // voffset
6994       Op.getOperand(4), // soffset
6995       Offsets.second,   // offset
6996       Op.getOperand(5), // cachepolicy, swizzled buffer
6997       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6998     };
6999 
7000     auto *M = cast<MemSDNode>(Op);
7001     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
7002     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7003   }
7004   case Intrinsic::amdgcn_struct_buffer_load:
7005   case Intrinsic::amdgcn_struct_buffer_load_format: {
7006     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7007 
7008     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7009     SDValue Ops[] = {
7010       Op.getOperand(0), // Chain
7011       Op.getOperand(2), // rsrc
7012       Op.getOperand(3), // vindex
7013       Offsets.first,    // voffset
7014       Op.getOperand(5), // soffset
7015       Offsets.second,   // offset
7016       Op.getOperand(6), // cachepolicy, swizzled buffer
7017       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7018     };
7019 
7020     auto *M = cast<MemSDNode>(Op);
7021     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
7022                                                         Ops[2]));
7023     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7024   }
7025   case Intrinsic::amdgcn_tbuffer_load: {
7026     MemSDNode *M = cast<MemSDNode>(Op);
7027     EVT LoadVT = Op.getValueType();
7028 
7029     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7030     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7031     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7032     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7033     unsigned IdxEn = 1;
7034     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7035       IdxEn = Idx->getZExtValue() != 0;
7036     SDValue Ops[] = {
7037       Op.getOperand(0),  // Chain
7038       Op.getOperand(2),  // rsrc
7039       Op.getOperand(3),  // vindex
7040       Op.getOperand(4),  // voffset
7041       Op.getOperand(5),  // soffset
7042       Op.getOperand(6),  // offset
7043       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7044       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7045       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7046     };
7047 
7048     if (LoadVT.getScalarType() == MVT::f16)
7049       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7050                                  M, DAG, Ops);
7051     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7052                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7053                                DAG);
7054   }
7055   case Intrinsic::amdgcn_raw_tbuffer_load: {
7056     MemSDNode *M = cast<MemSDNode>(Op);
7057     EVT LoadVT = Op.getValueType();
7058     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7059 
7060     SDValue Ops[] = {
7061       Op.getOperand(0),  // Chain
7062       Op.getOperand(2),  // rsrc
7063       DAG.getConstant(0, DL, MVT::i32), // vindex
7064       Offsets.first,     // voffset
7065       Op.getOperand(4),  // soffset
7066       Offsets.second,    // offset
7067       Op.getOperand(5),  // format
7068       Op.getOperand(6),  // cachepolicy, swizzled buffer
7069       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7070     };
7071 
7072     if (LoadVT.getScalarType() == MVT::f16)
7073       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7074                                  M, DAG, Ops);
7075     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7076                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7077                                DAG);
7078   }
7079   case Intrinsic::amdgcn_struct_tbuffer_load: {
7080     MemSDNode *M = cast<MemSDNode>(Op);
7081     EVT LoadVT = Op.getValueType();
7082     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7083 
7084     SDValue Ops[] = {
7085       Op.getOperand(0),  // Chain
7086       Op.getOperand(2),  // rsrc
7087       Op.getOperand(3),  // vindex
7088       Offsets.first,     // voffset
7089       Op.getOperand(5),  // soffset
7090       Offsets.second,    // offset
7091       Op.getOperand(6),  // format
7092       Op.getOperand(7),  // cachepolicy, swizzled buffer
7093       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7094     };
7095 
7096     if (LoadVT.getScalarType() == MVT::f16)
7097       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7098                                  M, DAG, Ops);
7099     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7100                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7101                                DAG);
7102   }
7103   case Intrinsic::amdgcn_buffer_atomic_swap:
7104   case Intrinsic::amdgcn_buffer_atomic_add:
7105   case Intrinsic::amdgcn_buffer_atomic_sub:
7106   case Intrinsic::amdgcn_buffer_atomic_csub:
7107   case Intrinsic::amdgcn_buffer_atomic_smin:
7108   case Intrinsic::amdgcn_buffer_atomic_umin:
7109   case Intrinsic::amdgcn_buffer_atomic_smax:
7110   case Intrinsic::amdgcn_buffer_atomic_umax:
7111   case Intrinsic::amdgcn_buffer_atomic_and:
7112   case Intrinsic::amdgcn_buffer_atomic_or:
7113   case Intrinsic::amdgcn_buffer_atomic_xor:
7114   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7115     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7116     unsigned IdxEn = 1;
7117     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7118       IdxEn = Idx->getZExtValue() != 0;
7119     SDValue Ops[] = {
7120       Op.getOperand(0), // Chain
7121       Op.getOperand(2), // vdata
7122       Op.getOperand(3), // rsrc
7123       Op.getOperand(4), // vindex
7124       SDValue(),        // voffset -- will be set by setBufferOffsets
7125       SDValue(),        // soffset -- will be set by setBufferOffsets
7126       SDValue(),        // offset -- will be set by setBufferOffsets
7127       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7128       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7129     };
7130     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7131     // We don't know the offset if vindex is non-zero, so clear it.
7132     if (IdxEn)
7133       Offset = 0;
7134     EVT VT = Op.getValueType();
7135 
7136     auto *M = cast<MemSDNode>(Op);
7137     M->getMemOperand()->setOffset(Offset);
7138     unsigned Opcode = 0;
7139 
7140     switch (IntrID) {
7141     case Intrinsic::amdgcn_buffer_atomic_swap:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7143       break;
7144     case Intrinsic::amdgcn_buffer_atomic_add:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7146       break;
7147     case Intrinsic::amdgcn_buffer_atomic_sub:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7149       break;
7150     case Intrinsic::amdgcn_buffer_atomic_csub:
7151       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7152       break;
7153     case Intrinsic::amdgcn_buffer_atomic_smin:
7154       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7155       break;
7156     case Intrinsic::amdgcn_buffer_atomic_umin:
7157       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7158       break;
7159     case Intrinsic::amdgcn_buffer_atomic_smax:
7160       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7161       break;
7162     case Intrinsic::amdgcn_buffer_atomic_umax:
7163       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7164       break;
7165     case Intrinsic::amdgcn_buffer_atomic_and:
7166       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7167       break;
7168     case Intrinsic::amdgcn_buffer_atomic_or:
7169       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7170       break;
7171     case Intrinsic::amdgcn_buffer_atomic_xor:
7172       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7173       break;
7174     case Intrinsic::amdgcn_buffer_atomic_fadd:
7175       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7176         DiagnosticInfoUnsupported
7177           NoFpRet(DAG.getMachineFunction().getFunction(),
7178                   "return versions of fp atomics not supported",
7179                   DL.getDebugLoc(), DS_Error);
7180         DAG.getContext()->diagnose(NoFpRet);
7181         return SDValue();
7182       }
7183       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7184       break;
7185     default:
7186       llvm_unreachable("unhandled atomic opcode");
7187     }
7188 
7189     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7190                                    M->getMemOperand());
7191   }
7192   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7193     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7194   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7195     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7196   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7197     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7198   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7199     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7200   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7201     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7202   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7203     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7204   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7205     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7206   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7207     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7208   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7209     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7210   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7211     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7212   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7213     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7214   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7215     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7216   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7217     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7218   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7219     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7220   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7221     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7222   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7223     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7224   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7225     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7226   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7227     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7228   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7229     return lowerStructBufferAtomicIntrin(Op, DAG,
7230                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7231   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7232     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7233   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7234     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7235   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7236     return lowerStructBufferAtomicIntrin(Op, DAG,
7237                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7238   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7239     return lowerStructBufferAtomicIntrin(Op, DAG,
7240                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7241   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7242     return lowerStructBufferAtomicIntrin(Op, DAG,
7243                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7244   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7245     return lowerStructBufferAtomicIntrin(Op, DAG,
7246                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7247   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7248     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7249   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7250     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7251   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7252     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7253   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7254     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7255   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7256     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7257 
7258   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7259     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7260     unsigned IdxEn = 1;
7261     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7262       IdxEn = Idx->getZExtValue() != 0;
7263     SDValue Ops[] = {
7264       Op.getOperand(0), // Chain
7265       Op.getOperand(2), // src
7266       Op.getOperand(3), // cmp
7267       Op.getOperand(4), // rsrc
7268       Op.getOperand(5), // vindex
7269       SDValue(),        // voffset -- will be set by setBufferOffsets
7270       SDValue(),        // soffset -- will be set by setBufferOffsets
7271       SDValue(),        // offset -- will be set by setBufferOffsets
7272       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7273       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7274     };
7275     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7276     // We don't know the offset if vindex is non-zero, so clear it.
7277     if (IdxEn)
7278       Offset = 0;
7279     EVT VT = Op.getValueType();
7280     auto *M = cast<MemSDNode>(Op);
7281     M->getMemOperand()->setOffset(Offset);
7282 
7283     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7284                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7285   }
7286   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7287     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7288     SDValue Ops[] = {
7289       Op.getOperand(0), // Chain
7290       Op.getOperand(2), // src
7291       Op.getOperand(3), // cmp
7292       Op.getOperand(4), // rsrc
7293       DAG.getConstant(0, DL, MVT::i32), // vindex
7294       Offsets.first,    // voffset
7295       Op.getOperand(6), // soffset
7296       Offsets.second,   // offset
7297       Op.getOperand(7), // cachepolicy
7298       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7299     };
7300     EVT VT = Op.getValueType();
7301     auto *M = cast<MemSDNode>(Op);
7302     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7303 
7304     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7305                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7306   }
7307   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7308     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7309     SDValue Ops[] = {
7310       Op.getOperand(0), // Chain
7311       Op.getOperand(2), // src
7312       Op.getOperand(3), // cmp
7313       Op.getOperand(4), // rsrc
7314       Op.getOperand(5), // vindex
7315       Offsets.first,    // voffset
7316       Op.getOperand(7), // soffset
7317       Offsets.second,   // offset
7318       Op.getOperand(8), // cachepolicy
7319       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7320     };
7321     EVT VT = Op.getValueType();
7322     auto *M = cast<MemSDNode>(Op);
7323     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7324                                                         Ops[4]));
7325 
7326     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7327                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7328   }
7329   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7330     SDLoc DL(Op);
7331     MemSDNode *M = cast<MemSDNode>(Op);
7332     SDValue NodePtr = M->getOperand(2);
7333     SDValue RayExtent = M->getOperand(3);
7334     SDValue RayOrigin = M->getOperand(4);
7335     SDValue RayDir = M->getOperand(5);
7336     SDValue RayInvDir = M->getOperand(6);
7337     SDValue TDescr = M->getOperand(7);
7338 
7339     assert(NodePtr.getValueType() == MVT::i32 ||
7340            NodePtr.getValueType() == MVT::i64);
7341     assert(RayDir.getValueType() == MVT::v4f16 ||
7342            RayDir.getValueType() == MVT::v4f32);
7343 
7344     if (!Subtarget->hasGFX10_AEncoding()) {
7345       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7346       return SDValue();
7347     }
7348 
7349     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7350     bool Is64 = NodePtr.getValueType() == MVT::i64;
7351     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7352                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7353                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7354                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7355 
7356     SmallVector<SDValue, 16> Ops;
7357 
7358     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7359       SmallVector<SDValue, 3> Lanes;
7360       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7361       if (Lanes[0].getValueSizeInBits() == 32) {
7362         for (unsigned I = 0; I < 3; ++I)
7363           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7364       } else {
7365         if (IsAligned) {
7366           Ops.push_back(
7367             DAG.getBitcast(MVT::i32,
7368                            DAG.getBuildVector(MVT::v2f16, DL,
7369                                               { Lanes[0], Lanes[1] })));
7370           Ops.push_back(Lanes[2]);
7371         } else {
7372           SDValue Elt0 = Ops.pop_back_val();
7373           Ops.push_back(
7374             DAG.getBitcast(MVT::i32,
7375                            DAG.getBuildVector(MVT::v2f16, DL,
7376                                               { Elt0, Lanes[0] })));
7377           Ops.push_back(
7378             DAG.getBitcast(MVT::i32,
7379                            DAG.getBuildVector(MVT::v2f16, DL,
7380                                               { Lanes[1], Lanes[2] })));
7381         }
7382       }
7383     };
7384 
7385     if (Is64)
7386       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7387     else
7388       Ops.push_back(NodePtr);
7389 
7390     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7391     packLanes(RayOrigin, true);
7392     packLanes(RayDir, true);
7393     packLanes(RayInvDir, false);
7394     Ops.push_back(TDescr);
7395     if (IsA16)
7396       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7397     Ops.push_back(M->getChain());
7398 
7399     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7400     MachineMemOperand *MemRef = M->getMemOperand();
7401     DAG.setNodeMemRefs(NewNode, {MemRef});
7402     return SDValue(NewNode, 0);
7403   }
7404   case Intrinsic::amdgcn_global_atomic_fadd:
7405     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7406       DiagnosticInfoUnsupported
7407         NoFpRet(DAG.getMachineFunction().getFunction(),
7408                 "return versions of fp atomics not supported",
7409                 DL.getDebugLoc(), DS_Error);
7410       DAG.getContext()->diagnose(NoFpRet);
7411       return SDValue();
7412     }
7413     LLVM_FALLTHROUGH;
7414   case Intrinsic::amdgcn_global_atomic_fmin:
7415   case Intrinsic::amdgcn_global_atomic_fmax:
7416   case Intrinsic::amdgcn_flat_atomic_fadd:
7417   case Intrinsic::amdgcn_flat_atomic_fmin:
7418   case Intrinsic::amdgcn_flat_atomic_fmax: {
7419     MemSDNode *M = cast<MemSDNode>(Op);
7420     SDValue Ops[] = {
7421       M->getOperand(0), // Chain
7422       M->getOperand(2), // Ptr
7423       M->getOperand(3)  // Value
7424     };
7425     unsigned Opcode = 0;
7426     switch (IntrID) {
7427     case Intrinsic::amdgcn_global_atomic_fadd:
7428     case Intrinsic::amdgcn_flat_atomic_fadd: {
7429       EVT VT = Op.getOperand(3).getValueType();
7430       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7431                            DAG.getVTList(VT, MVT::Other), Ops,
7432                            M->getMemOperand());
7433     }
7434     case Intrinsic::amdgcn_global_atomic_fmin:
7435     case Intrinsic::amdgcn_flat_atomic_fmin: {
7436       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7437       break;
7438     }
7439     case Intrinsic::amdgcn_global_atomic_fmax:
7440     case Intrinsic::amdgcn_flat_atomic_fmax: {
7441       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7442       break;
7443     }
7444     default:
7445       llvm_unreachable("unhandled atomic opcode");
7446     }
7447     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7448                                    M->getVTList(), Ops, M->getMemoryVT(),
7449                                    M->getMemOperand());
7450   }
7451   default:
7452 
7453     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7454             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7455       return lowerImage(Op, ImageDimIntr, DAG, true);
7456 
7457     return SDValue();
7458   }
7459 }
7460 
7461 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7462 // dwordx4 if on SI.
7463 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7464                                               SDVTList VTList,
7465                                               ArrayRef<SDValue> Ops, EVT MemVT,
7466                                               MachineMemOperand *MMO,
7467                                               SelectionDAG &DAG) const {
7468   EVT VT = VTList.VTs[0];
7469   EVT WidenedVT = VT;
7470   EVT WidenedMemVT = MemVT;
7471   if (!Subtarget->hasDwordx3LoadStores() &&
7472       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7473     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7474                                  WidenedVT.getVectorElementType(), 4);
7475     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7476                                     WidenedMemVT.getVectorElementType(), 4);
7477     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7478   }
7479 
7480   assert(VTList.NumVTs == 2);
7481   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7482 
7483   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7484                                        WidenedMemVT, MMO);
7485   if (WidenedVT != VT) {
7486     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7487                                DAG.getVectorIdxConstant(0, DL));
7488     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7489   }
7490   return NewOp;
7491 }
7492 
7493 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7494                                          bool ImageStore) const {
7495   EVT StoreVT = VData.getValueType();
7496 
7497   // No change for f16 and legal vector D16 types.
7498   if (!StoreVT.isVector())
7499     return VData;
7500 
7501   SDLoc DL(VData);
7502   unsigned NumElements = StoreVT.getVectorNumElements();
7503 
7504   if (Subtarget->hasUnpackedD16VMem()) {
7505     // We need to unpack the packed data to store.
7506     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7507     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7508 
7509     EVT EquivStoreVT =
7510         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7511     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7512     return DAG.UnrollVectorOp(ZExt.getNode());
7513   }
7514 
7515   // The sq block of gfx8.1 does not estimate register use correctly for d16
7516   // image store instructions. The data operand is computed as if it were not a
7517   // d16 image instruction.
7518   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7519     // Bitcast to i16
7520     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7521     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7522 
7523     // Decompose into scalars
7524     SmallVector<SDValue, 4> Elts;
7525     DAG.ExtractVectorElements(IntVData, Elts);
7526 
7527     // Group pairs of i16 into v2i16 and bitcast to i32
7528     SmallVector<SDValue, 4> PackedElts;
7529     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7530       SDValue Pair =
7531           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7532       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7533       PackedElts.push_back(IntPair);
7534     }
7535     if ((NumElements % 2) == 1) {
7536       // Handle v3i16
7537       unsigned I = Elts.size() / 2;
7538       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7539                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7540       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7541       PackedElts.push_back(IntPair);
7542     }
7543 
7544     // Pad using UNDEF
7545     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7546 
7547     // Build final vector
7548     EVT VecVT =
7549         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7550     return DAG.getBuildVector(VecVT, DL, PackedElts);
7551   }
7552 
7553   if (NumElements == 3) {
7554     EVT IntStoreVT =
7555         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7556     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7557 
7558     EVT WidenedStoreVT = EVT::getVectorVT(
7559         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7560     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7561                                          WidenedStoreVT.getStoreSizeInBits());
7562     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7563     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7564   }
7565 
7566   assert(isTypeLegal(StoreVT));
7567   return VData;
7568 }
7569 
7570 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7571                                               SelectionDAG &DAG) const {
7572   SDLoc DL(Op);
7573   SDValue Chain = Op.getOperand(0);
7574   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7575   MachineFunction &MF = DAG.getMachineFunction();
7576 
7577   switch (IntrinsicID) {
7578   case Intrinsic::amdgcn_exp_compr: {
7579     SDValue Src0 = Op.getOperand(4);
7580     SDValue Src1 = Op.getOperand(5);
7581     // Hack around illegal type on SI by directly selecting it.
7582     if (isTypeLegal(Src0.getValueType()))
7583       return SDValue();
7584 
7585     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7586     SDValue Undef = DAG.getUNDEF(MVT::f32);
7587     const SDValue Ops[] = {
7588       Op.getOperand(2), // tgt
7589       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7590       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7591       Undef, // src2
7592       Undef, // src3
7593       Op.getOperand(7), // vm
7594       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7595       Op.getOperand(3), // en
7596       Op.getOperand(0) // Chain
7597     };
7598 
7599     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7600     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7601   }
7602   case Intrinsic::amdgcn_s_barrier: {
7603     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7604       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7605       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7606       if (WGSize <= ST.getWavefrontSize())
7607         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7608                                           Op.getOperand(0)), 0);
7609     }
7610     return SDValue();
7611   };
7612   case Intrinsic::amdgcn_tbuffer_store: {
7613     SDValue VData = Op.getOperand(2);
7614     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7615     if (IsD16)
7616       VData = handleD16VData(VData, DAG);
7617     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7618     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7619     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7620     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7621     unsigned IdxEn = 1;
7622     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7623       IdxEn = Idx->getZExtValue() != 0;
7624     SDValue Ops[] = {
7625       Chain,
7626       VData,             // vdata
7627       Op.getOperand(3),  // rsrc
7628       Op.getOperand(4),  // vindex
7629       Op.getOperand(5),  // voffset
7630       Op.getOperand(6),  // soffset
7631       Op.getOperand(7),  // offset
7632       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7633       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7634       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7635     };
7636     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7637                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7638     MemSDNode *M = cast<MemSDNode>(Op);
7639     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7640                                    M->getMemoryVT(), M->getMemOperand());
7641   }
7642 
7643   case Intrinsic::amdgcn_struct_tbuffer_store: {
7644     SDValue VData = Op.getOperand(2);
7645     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7646     if (IsD16)
7647       VData = handleD16VData(VData, DAG);
7648     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7649     SDValue Ops[] = {
7650       Chain,
7651       VData,             // vdata
7652       Op.getOperand(3),  // rsrc
7653       Op.getOperand(4),  // vindex
7654       Offsets.first,     // voffset
7655       Op.getOperand(6),  // soffset
7656       Offsets.second,    // offset
7657       Op.getOperand(7),  // format
7658       Op.getOperand(8),  // cachepolicy, swizzled buffer
7659       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7660     };
7661     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7662                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7663     MemSDNode *M = cast<MemSDNode>(Op);
7664     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7665                                    M->getMemoryVT(), M->getMemOperand());
7666   }
7667 
7668   case Intrinsic::amdgcn_raw_tbuffer_store: {
7669     SDValue VData = Op.getOperand(2);
7670     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7671     if (IsD16)
7672       VData = handleD16VData(VData, DAG);
7673     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7674     SDValue Ops[] = {
7675       Chain,
7676       VData,             // vdata
7677       Op.getOperand(3),  // rsrc
7678       DAG.getConstant(0, DL, MVT::i32), // vindex
7679       Offsets.first,     // voffset
7680       Op.getOperand(5),  // soffset
7681       Offsets.second,    // offset
7682       Op.getOperand(6),  // format
7683       Op.getOperand(7),  // cachepolicy, swizzled buffer
7684       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7685     };
7686     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7687                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7688     MemSDNode *M = cast<MemSDNode>(Op);
7689     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7690                                    M->getMemoryVT(), M->getMemOperand());
7691   }
7692 
7693   case Intrinsic::amdgcn_buffer_store:
7694   case Intrinsic::amdgcn_buffer_store_format: {
7695     SDValue VData = Op.getOperand(2);
7696     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7697     if (IsD16)
7698       VData = handleD16VData(VData, DAG);
7699     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7700     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7701     unsigned IdxEn = 1;
7702     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7703       IdxEn = Idx->getZExtValue() != 0;
7704     SDValue Ops[] = {
7705       Chain,
7706       VData,
7707       Op.getOperand(3), // rsrc
7708       Op.getOperand(4), // vindex
7709       SDValue(), // voffset -- will be set by setBufferOffsets
7710       SDValue(), // soffset -- will be set by setBufferOffsets
7711       SDValue(), // offset -- will be set by setBufferOffsets
7712       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7713       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7714     };
7715     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7716     // We don't know the offset if vindex is non-zero, so clear it.
7717     if (IdxEn)
7718       Offset = 0;
7719     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7720                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7721     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7722     MemSDNode *M = cast<MemSDNode>(Op);
7723     M->getMemOperand()->setOffset(Offset);
7724 
7725     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7726     EVT VDataType = VData.getValueType().getScalarType();
7727     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7728       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7729 
7730     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7731                                    M->getMemoryVT(), M->getMemOperand());
7732   }
7733 
7734   case Intrinsic::amdgcn_raw_buffer_store:
7735   case Intrinsic::amdgcn_raw_buffer_store_format: {
7736     const bool IsFormat =
7737         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7738 
7739     SDValue VData = Op.getOperand(2);
7740     EVT VDataVT = VData.getValueType();
7741     EVT EltType = VDataVT.getScalarType();
7742     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7743     if (IsD16) {
7744       VData = handleD16VData(VData, DAG);
7745       VDataVT = VData.getValueType();
7746     }
7747 
7748     if (!isTypeLegal(VDataVT)) {
7749       VData =
7750           DAG.getNode(ISD::BITCAST, DL,
7751                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7752     }
7753 
7754     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7755     SDValue Ops[] = {
7756       Chain,
7757       VData,
7758       Op.getOperand(3), // rsrc
7759       DAG.getConstant(0, DL, MVT::i32), // vindex
7760       Offsets.first,    // voffset
7761       Op.getOperand(5), // soffset
7762       Offsets.second,   // offset
7763       Op.getOperand(6), // cachepolicy, swizzled buffer
7764       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7765     };
7766     unsigned Opc =
7767         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7768     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7769     MemSDNode *M = cast<MemSDNode>(Op);
7770     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7771 
7772     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7773     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7774       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7775 
7776     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7777                                    M->getMemoryVT(), M->getMemOperand());
7778   }
7779 
7780   case Intrinsic::amdgcn_struct_buffer_store:
7781   case Intrinsic::amdgcn_struct_buffer_store_format: {
7782     const bool IsFormat =
7783         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7784 
7785     SDValue VData = Op.getOperand(2);
7786     EVT VDataVT = VData.getValueType();
7787     EVT EltType = VDataVT.getScalarType();
7788     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7789 
7790     if (IsD16) {
7791       VData = handleD16VData(VData, DAG);
7792       VDataVT = VData.getValueType();
7793     }
7794 
7795     if (!isTypeLegal(VDataVT)) {
7796       VData =
7797           DAG.getNode(ISD::BITCAST, DL,
7798                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7799     }
7800 
7801     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7802     SDValue Ops[] = {
7803       Chain,
7804       VData,
7805       Op.getOperand(3), // rsrc
7806       Op.getOperand(4), // vindex
7807       Offsets.first,    // voffset
7808       Op.getOperand(6), // soffset
7809       Offsets.second,   // offset
7810       Op.getOperand(7), // cachepolicy, swizzled buffer
7811       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7812     };
7813     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7814                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7815     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7816     MemSDNode *M = cast<MemSDNode>(Op);
7817     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7818                                                         Ops[3]));
7819 
7820     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7821     EVT VDataType = VData.getValueType().getScalarType();
7822     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7823       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7824 
7825     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7826                                    M->getMemoryVT(), M->getMemOperand());
7827   }
7828   case Intrinsic::amdgcn_end_cf:
7829     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7830                                       Op->getOperand(2), Chain), 0);
7831 
7832   default: {
7833     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7834             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7835       return lowerImage(Op, ImageDimIntr, DAG, true);
7836 
7837     return Op;
7838   }
7839   }
7840 }
7841 
7842 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7843 // offset (the offset that is included in bounds checking and swizzling, to be
7844 // split between the instruction's voffset and immoffset fields) and soffset
7845 // (the offset that is excluded from bounds checking and swizzling, to go in
7846 // the instruction's soffset field).  This function takes the first kind of
7847 // offset and figures out how to split it between voffset and immoffset.
7848 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7849     SDValue Offset, SelectionDAG &DAG) const {
7850   SDLoc DL(Offset);
7851   const unsigned MaxImm = 4095;
7852   SDValue N0 = Offset;
7853   ConstantSDNode *C1 = nullptr;
7854 
7855   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7856     N0 = SDValue();
7857   else if (DAG.isBaseWithConstantOffset(N0)) {
7858     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7859     N0 = N0.getOperand(0);
7860   }
7861 
7862   if (C1) {
7863     unsigned ImmOffset = C1->getZExtValue();
7864     // If the immediate value is too big for the immoffset field, put the value
7865     // and -4096 into the immoffset field so that the value that is copied/added
7866     // for the voffset field is a multiple of 4096, and it stands more chance
7867     // of being CSEd with the copy/add for another similar load/store.
7868     // However, do not do that rounding down to a multiple of 4096 if that is a
7869     // negative number, as it appears to be illegal to have a negative offset
7870     // in the vgpr, even if adding the immediate offset makes it positive.
7871     unsigned Overflow = ImmOffset & ~MaxImm;
7872     ImmOffset -= Overflow;
7873     if ((int32_t)Overflow < 0) {
7874       Overflow += ImmOffset;
7875       ImmOffset = 0;
7876     }
7877     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7878     if (Overflow) {
7879       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7880       if (!N0)
7881         N0 = OverflowVal;
7882       else {
7883         SDValue Ops[] = { N0, OverflowVal };
7884         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7885       }
7886     }
7887   }
7888   if (!N0)
7889     N0 = DAG.getConstant(0, DL, MVT::i32);
7890   if (!C1)
7891     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7892   return {N0, SDValue(C1, 0)};
7893 }
7894 
7895 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7896 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7897 // pointed to by Offsets.
7898 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7899                                             SelectionDAG &DAG, SDValue *Offsets,
7900                                             Align Alignment) const {
7901   SDLoc DL(CombinedOffset);
7902   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7903     uint32_t Imm = C->getZExtValue();
7904     uint32_t SOffset, ImmOffset;
7905     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7906                                  Alignment)) {
7907       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7908       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7909       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7910       return SOffset + ImmOffset;
7911     }
7912   }
7913   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7914     SDValue N0 = CombinedOffset.getOperand(0);
7915     SDValue N1 = CombinedOffset.getOperand(1);
7916     uint32_t SOffset, ImmOffset;
7917     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7918     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7919                                                 Subtarget, Alignment)) {
7920       Offsets[0] = N0;
7921       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7922       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7923       return 0;
7924     }
7925   }
7926   Offsets[0] = CombinedOffset;
7927   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7928   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7929   return 0;
7930 }
7931 
7932 // Handle 8 bit and 16 bit buffer loads
7933 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7934                                                      EVT LoadVT, SDLoc DL,
7935                                                      ArrayRef<SDValue> Ops,
7936                                                      MemSDNode *M) const {
7937   EVT IntVT = LoadVT.changeTypeToInteger();
7938   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7939          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7940 
7941   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7942   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7943                                                Ops, IntVT,
7944                                                M->getMemOperand());
7945   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7946   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7947 
7948   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7949 }
7950 
7951 // Handle 8 bit and 16 bit buffer stores
7952 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7953                                                       EVT VDataType, SDLoc DL,
7954                                                       SDValue Ops[],
7955                                                       MemSDNode *M) const {
7956   if (VDataType == MVT::f16)
7957     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7958 
7959   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7960   Ops[1] = BufferStoreExt;
7961   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7962                                  AMDGPUISD::BUFFER_STORE_SHORT;
7963   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7964   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7965                                      M->getMemOperand());
7966 }
7967 
7968 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7969                                  ISD::LoadExtType ExtType, SDValue Op,
7970                                  const SDLoc &SL, EVT VT) {
7971   if (VT.bitsLT(Op.getValueType()))
7972     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7973 
7974   switch (ExtType) {
7975   case ISD::SEXTLOAD:
7976     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7977   case ISD::ZEXTLOAD:
7978     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7979   case ISD::EXTLOAD:
7980     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7981   case ISD::NON_EXTLOAD:
7982     return Op;
7983   }
7984 
7985   llvm_unreachable("invalid ext type");
7986 }
7987 
7988 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7989   SelectionDAG &DAG = DCI.DAG;
7990   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7991     return SDValue();
7992 
7993   // FIXME: Constant loads should all be marked invariant.
7994   unsigned AS = Ld->getAddressSpace();
7995   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7996       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7997       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7998     return SDValue();
7999 
8000   // Don't do this early, since it may interfere with adjacent load merging for
8001   // illegal types. We can avoid losing alignment information for exotic types
8002   // pre-legalize.
8003   EVT MemVT = Ld->getMemoryVT();
8004   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8005       MemVT.getSizeInBits() >= 32)
8006     return SDValue();
8007 
8008   SDLoc SL(Ld);
8009 
8010   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8011          "unexpected vector extload");
8012 
8013   // TODO: Drop only high part of range.
8014   SDValue Ptr = Ld->getBasePtr();
8015   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8016                                 MVT::i32, SL, Ld->getChain(), Ptr,
8017                                 Ld->getOffset(),
8018                                 Ld->getPointerInfo(), MVT::i32,
8019                                 Ld->getAlignment(),
8020                                 Ld->getMemOperand()->getFlags(),
8021                                 Ld->getAAInfo(),
8022                                 nullptr); // Drop ranges
8023 
8024   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8025   if (MemVT.isFloatingPoint()) {
8026     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8027            "unexpected fp extload");
8028     TruncVT = MemVT.changeTypeToInteger();
8029   }
8030 
8031   SDValue Cvt = NewLoad;
8032   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8033     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8034                       DAG.getValueType(TruncVT));
8035   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8036              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8037     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8038   } else {
8039     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8040   }
8041 
8042   EVT VT = Ld->getValueType(0);
8043   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8044 
8045   DCI.AddToWorklist(Cvt.getNode());
8046 
8047   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8048   // the appropriate extension from the 32-bit load.
8049   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8050   DCI.AddToWorklist(Cvt.getNode());
8051 
8052   // Handle conversion back to floating point if necessary.
8053   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8054 
8055   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8056 }
8057 
8058 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8059   SDLoc DL(Op);
8060   LoadSDNode *Load = cast<LoadSDNode>(Op);
8061   ISD::LoadExtType ExtType = Load->getExtensionType();
8062   EVT MemVT = Load->getMemoryVT();
8063 
8064   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8065     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8066       return SDValue();
8067 
8068     // FIXME: Copied from PPC
8069     // First, load into 32 bits, then truncate to 1 bit.
8070 
8071     SDValue Chain = Load->getChain();
8072     SDValue BasePtr = Load->getBasePtr();
8073     MachineMemOperand *MMO = Load->getMemOperand();
8074 
8075     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8076 
8077     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8078                                    BasePtr, RealMemVT, MMO);
8079 
8080     if (!MemVT.isVector()) {
8081       SDValue Ops[] = {
8082         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8083         NewLD.getValue(1)
8084       };
8085 
8086       return DAG.getMergeValues(Ops, DL);
8087     }
8088 
8089     SmallVector<SDValue, 3> Elts;
8090     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8091       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8092                                 DAG.getConstant(I, DL, MVT::i32));
8093 
8094       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8095     }
8096 
8097     SDValue Ops[] = {
8098       DAG.getBuildVector(MemVT, DL, Elts),
8099       NewLD.getValue(1)
8100     };
8101 
8102     return DAG.getMergeValues(Ops, DL);
8103   }
8104 
8105   if (!MemVT.isVector())
8106     return SDValue();
8107 
8108   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8109          "Custom lowering for non-i32 vectors hasn't been implemented.");
8110 
8111   unsigned Alignment = Load->getAlignment();
8112   unsigned AS = Load->getAddressSpace();
8113   if (Subtarget->hasLDSMisalignedBug() &&
8114       AS == AMDGPUAS::FLAT_ADDRESS &&
8115       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8116     return SplitVectorLoad(Op, DAG);
8117   }
8118 
8119   MachineFunction &MF = DAG.getMachineFunction();
8120   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8121   // If there is a possibilty that flat instruction access scratch memory
8122   // then we need to use the same legalization rules we use for private.
8123   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8124       !Subtarget->hasMultiDwordFlatScratchAddressing())
8125     AS = MFI->hasFlatScratchInit() ?
8126          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8127 
8128   unsigned NumElements = MemVT.getVectorNumElements();
8129 
8130   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8131       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8132     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8133       if (MemVT.isPow2VectorType())
8134         return SDValue();
8135       return WidenOrSplitVectorLoad(Op, DAG);
8136     }
8137     // Non-uniform loads will be selected to MUBUF instructions, so they
8138     // have the same legalization requirements as global and private
8139     // loads.
8140     //
8141   }
8142 
8143   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8144       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8145       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8146     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8147         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8148         Alignment >= 4 && NumElements < 32) {
8149       if (MemVT.isPow2VectorType())
8150         return SDValue();
8151       return WidenOrSplitVectorLoad(Op, DAG);
8152     }
8153     // Non-uniform loads will be selected to MUBUF instructions, so they
8154     // have the same legalization requirements as global and private
8155     // loads.
8156     //
8157   }
8158   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8159       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8160       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8161       AS == AMDGPUAS::FLAT_ADDRESS) {
8162     if (NumElements > 4)
8163       return SplitVectorLoad(Op, DAG);
8164     // v3 loads not supported on SI.
8165     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8166       return WidenOrSplitVectorLoad(Op, DAG);
8167 
8168     // v3 and v4 loads are supported for private and global memory.
8169     return SDValue();
8170   }
8171   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8172     // Depending on the setting of the private_element_size field in the
8173     // resource descriptor, we can only make private accesses up to a certain
8174     // size.
8175     switch (Subtarget->getMaxPrivateElementSize()) {
8176     case 4: {
8177       SDValue Ops[2];
8178       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8179       return DAG.getMergeValues(Ops, DL);
8180     }
8181     case 8:
8182       if (NumElements > 2)
8183         return SplitVectorLoad(Op, DAG);
8184       return SDValue();
8185     case 16:
8186       // Same as global/flat
8187       if (NumElements > 4)
8188         return SplitVectorLoad(Op, DAG);
8189       // v3 loads not supported on SI.
8190       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8191         return WidenOrSplitVectorLoad(Op, DAG);
8192 
8193       return SDValue();
8194     default:
8195       llvm_unreachable("unsupported private_element_size");
8196     }
8197   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8198     // Use ds_read_b128 or ds_read_b96 when possible.
8199     if (Subtarget->hasDS96AndDS128() &&
8200         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8201          MemVT.getStoreSize() == 12) &&
8202         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8203                                            Load->getAlign()))
8204       return SDValue();
8205 
8206     if (NumElements > 2)
8207       return SplitVectorLoad(Op, DAG);
8208 
8209     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8210     // address is negative, then the instruction is incorrectly treated as
8211     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8212     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8213     // load later in the SILoadStoreOptimizer.
8214     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8215         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8216         Load->getAlignment() < 8) {
8217       return SplitVectorLoad(Op, DAG);
8218     }
8219   }
8220 
8221   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8222                                       MemVT, *Load->getMemOperand())) {
8223     SDValue Ops[2];
8224     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8225     return DAG.getMergeValues(Ops, DL);
8226   }
8227 
8228   return SDValue();
8229 }
8230 
8231 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8232   EVT VT = Op.getValueType();
8233   assert(VT.getSizeInBits() == 64);
8234 
8235   SDLoc DL(Op);
8236   SDValue Cond = Op.getOperand(0);
8237 
8238   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8239   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8240 
8241   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8242   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8243 
8244   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8245   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8246 
8247   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8248 
8249   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8250   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8251 
8252   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8253 
8254   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8255   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8256 }
8257 
8258 // Catch division cases where we can use shortcuts with rcp and rsq
8259 // instructions.
8260 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8261                                               SelectionDAG &DAG) const {
8262   SDLoc SL(Op);
8263   SDValue LHS = Op.getOperand(0);
8264   SDValue RHS = Op.getOperand(1);
8265   EVT VT = Op.getValueType();
8266   const SDNodeFlags Flags = Op->getFlags();
8267 
8268   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8269 
8270   // Without !fpmath accuracy information, we can't do more because we don't
8271   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8272   if (!AllowInaccurateRcp)
8273     return SDValue();
8274 
8275   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8276     if (CLHS->isExactlyValue(1.0)) {
8277       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8278       // the CI documentation has a worst case error of 1 ulp.
8279       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8280       // use it as long as we aren't trying to use denormals.
8281       //
8282       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8283 
8284       // 1.0 / sqrt(x) -> rsq(x)
8285 
8286       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8287       // error seems really high at 2^29 ULP.
8288       if (RHS.getOpcode() == ISD::FSQRT)
8289         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8290 
8291       // 1.0 / x -> rcp(x)
8292       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8293     }
8294 
8295     // Same as for 1.0, but expand the sign out of the constant.
8296     if (CLHS->isExactlyValue(-1.0)) {
8297       // -1.0 / x -> rcp (fneg x)
8298       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8299       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8300     }
8301   }
8302 
8303   // Turn into multiply by the reciprocal.
8304   // x / y -> x * (1.0 / y)
8305   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8306   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8307 }
8308 
8309 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8310                                                 SelectionDAG &DAG) const {
8311   SDLoc SL(Op);
8312   SDValue X = Op.getOperand(0);
8313   SDValue Y = Op.getOperand(1);
8314   EVT VT = Op.getValueType();
8315   const SDNodeFlags Flags = Op->getFlags();
8316 
8317   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8318                             DAG.getTarget().Options.UnsafeFPMath;
8319   if (!AllowInaccurateDiv)
8320     return SDValue();
8321 
8322   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8323   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8324 
8325   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8326   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8327 
8328   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8329   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8330   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8331   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8332   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8333   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8334 }
8335 
8336 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8337                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8338                           SDNodeFlags Flags) {
8339   if (GlueChain->getNumValues() <= 1) {
8340     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8341   }
8342 
8343   assert(GlueChain->getNumValues() == 3);
8344 
8345   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8346   switch (Opcode) {
8347   default: llvm_unreachable("no chain equivalent for opcode");
8348   case ISD::FMUL:
8349     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8350     break;
8351   }
8352 
8353   return DAG.getNode(Opcode, SL, VTList,
8354                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8355                      Flags);
8356 }
8357 
8358 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8359                            EVT VT, SDValue A, SDValue B, SDValue C,
8360                            SDValue GlueChain, SDNodeFlags Flags) {
8361   if (GlueChain->getNumValues() <= 1) {
8362     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8363   }
8364 
8365   assert(GlueChain->getNumValues() == 3);
8366 
8367   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8368   switch (Opcode) {
8369   default: llvm_unreachable("no chain equivalent for opcode");
8370   case ISD::FMA:
8371     Opcode = AMDGPUISD::FMA_W_CHAIN;
8372     break;
8373   }
8374 
8375   return DAG.getNode(Opcode, SL, VTList,
8376                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8377                      Flags);
8378 }
8379 
8380 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8381   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8382     return FastLowered;
8383 
8384   SDLoc SL(Op);
8385   SDValue Src0 = Op.getOperand(0);
8386   SDValue Src1 = Op.getOperand(1);
8387 
8388   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8389   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8390 
8391   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8392   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8393 
8394   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8395   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8396 
8397   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8398 }
8399 
8400 // Faster 2.5 ULP division that does not support denormals.
8401 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8402   SDLoc SL(Op);
8403   SDValue LHS = Op.getOperand(1);
8404   SDValue RHS = Op.getOperand(2);
8405 
8406   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8407 
8408   const APFloat K0Val(BitsToFloat(0x6f800000));
8409   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8410 
8411   const APFloat K1Val(BitsToFloat(0x2f800000));
8412   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8413 
8414   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8415 
8416   EVT SetCCVT =
8417     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8418 
8419   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8420 
8421   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8422 
8423   // TODO: Should this propagate fast-math-flags?
8424   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8425 
8426   // rcp does not support denormals.
8427   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8428 
8429   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8430 
8431   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8432 }
8433 
8434 // Returns immediate value for setting the F32 denorm mode when using the
8435 // S_DENORM_MODE instruction.
8436 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8437                                     const SDLoc &SL, const GCNSubtarget *ST) {
8438   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8439   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8440                                 ? FP_DENORM_FLUSH_NONE
8441                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8442 
8443   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8444   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8445 }
8446 
8447 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8448   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8449     return FastLowered;
8450 
8451   // The selection matcher assumes anything with a chain selecting to a
8452   // mayRaiseFPException machine instruction. Since we're introducing a chain
8453   // here, we need to explicitly report nofpexcept for the regular fdiv
8454   // lowering.
8455   SDNodeFlags Flags = Op->getFlags();
8456   Flags.setNoFPExcept(true);
8457 
8458   SDLoc SL(Op);
8459   SDValue LHS = Op.getOperand(0);
8460   SDValue RHS = Op.getOperand(1);
8461 
8462   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8463 
8464   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8465 
8466   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8467                                           {RHS, RHS, LHS}, Flags);
8468   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8469                                         {LHS, RHS, LHS}, Flags);
8470 
8471   // Denominator is scaled to not be denormal, so using rcp is ok.
8472   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8473                                   DenominatorScaled, Flags);
8474   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8475                                      DenominatorScaled, Flags);
8476 
8477   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8478                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8479                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8480   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8481 
8482   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8483 
8484   if (!HasFP32Denormals) {
8485     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8486     // lowering. The chain dependence is insufficient, and we need glue. We do
8487     // not need the glue variants in a strictfp function.
8488 
8489     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8490 
8491     SDNode *EnableDenorm;
8492     if (Subtarget->hasDenormModeInst()) {
8493       const SDValue EnableDenormValue =
8494           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8495 
8496       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8497                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8498     } else {
8499       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8500                                                         SL, MVT::i32);
8501       EnableDenorm =
8502           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8503                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8504     }
8505 
8506     SDValue Ops[3] = {
8507       NegDivScale0,
8508       SDValue(EnableDenorm, 0),
8509       SDValue(EnableDenorm, 1)
8510     };
8511 
8512     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8513   }
8514 
8515   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8516                              ApproxRcp, One, NegDivScale0, Flags);
8517 
8518   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8519                              ApproxRcp, Fma0, Flags);
8520 
8521   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8522                            Fma1, Fma1, Flags);
8523 
8524   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8525                              NumeratorScaled, Mul, Flags);
8526 
8527   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8528                              Fma2, Fma1, Mul, Fma2, Flags);
8529 
8530   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8531                              NumeratorScaled, Fma3, Flags);
8532 
8533   if (!HasFP32Denormals) {
8534     SDNode *DisableDenorm;
8535     if (Subtarget->hasDenormModeInst()) {
8536       const SDValue DisableDenormValue =
8537           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8538 
8539       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8540                                   Fma4.getValue(1), DisableDenormValue,
8541                                   Fma4.getValue(2)).getNode();
8542     } else {
8543       const SDValue DisableDenormValue =
8544           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8545 
8546       DisableDenorm = DAG.getMachineNode(
8547           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8548           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8549     }
8550 
8551     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8552                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8553     DAG.setRoot(OutputChain);
8554   }
8555 
8556   SDValue Scale = NumeratorScaled.getValue(1);
8557   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8558                              {Fma4, Fma1, Fma3, Scale}, Flags);
8559 
8560   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8561 }
8562 
8563 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8564   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8565     return FastLowered;
8566 
8567   SDLoc SL(Op);
8568   SDValue X = Op.getOperand(0);
8569   SDValue Y = Op.getOperand(1);
8570 
8571   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8572 
8573   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8574 
8575   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8576 
8577   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8578 
8579   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8580 
8581   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8582 
8583   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8584 
8585   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8586 
8587   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8588 
8589   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8590   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8591 
8592   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8593                              NegDivScale0, Mul, DivScale1);
8594 
8595   SDValue Scale;
8596 
8597   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8598     // Workaround a hardware bug on SI where the condition output from div_scale
8599     // is not usable.
8600 
8601     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8602 
8603     // Figure out if the scale to use for div_fmas.
8604     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8605     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8606     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8607     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8608 
8609     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8610     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8611 
8612     SDValue Scale0Hi
8613       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8614     SDValue Scale1Hi
8615       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8616 
8617     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8618     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8619     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8620   } else {
8621     Scale = DivScale1.getValue(1);
8622   }
8623 
8624   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8625                              Fma4, Fma3, Mul, Scale);
8626 
8627   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8628 }
8629 
8630 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8631   EVT VT = Op.getValueType();
8632 
8633   if (VT == MVT::f32)
8634     return LowerFDIV32(Op, DAG);
8635 
8636   if (VT == MVT::f64)
8637     return LowerFDIV64(Op, DAG);
8638 
8639   if (VT == MVT::f16)
8640     return LowerFDIV16(Op, DAG);
8641 
8642   llvm_unreachable("Unexpected type for fdiv");
8643 }
8644 
8645 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8646   SDLoc DL(Op);
8647   StoreSDNode *Store = cast<StoreSDNode>(Op);
8648   EVT VT = Store->getMemoryVT();
8649 
8650   if (VT == MVT::i1) {
8651     return DAG.getTruncStore(Store->getChain(), DL,
8652        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8653        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8654   }
8655 
8656   assert(VT.isVector() &&
8657          Store->getValue().getValueType().getScalarType() == MVT::i32);
8658 
8659   unsigned AS = Store->getAddressSpace();
8660   if (Subtarget->hasLDSMisalignedBug() &&
8661       AS == AMDGPUAS::FLAT_ADDRESS &&
8662       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8663     return SplitVectorStore(Op, DAG);
8664   }
8665 
8666   MachineFunction &MF = DAG.getMachineFunction();
8667   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8668   // If there is a possibilty that flat instruction access scratch memory
8669   // then we need to use the same legalization rules we use for private.
8670   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8671       !Subtarget->hasMultiDwordFlatScratchAddressing())
8672     AS = MFI->hasFlatScratchInit() ?
8673          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8674 
8675   unsigned NumElements = VT.getVectorNumElements();
8676   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8677       AS == AMDGPUAS::FLAT_ADDRESS) {
8678     if (NumElements > 4)
8679       return SplitVectorStore(Op, DAG);
8680     // v3 stores not supported on SI.
8681     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8682       return SplitVectorStore(Op, DAG);
8683 
8684     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8685                                         VT, *Store->getMemOperand()))
8686       return expandUnalignedStore(Store, DAG);
8687 
8688     return SDValue();
8689   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8690     switch (Subtarget->getMaxPrivateElementSize()) {
8691     case 4:
8692       return scalarizeVectorStore(Store, DAG);
8693     case 8:
8694       if (NumElements > 2)
8695         return SplitVectorStore(Op, DAG);
8696       return SDValue();
8697     case 16:
8698       if (NumElements > 4 ||
8699           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8700         return SplitVectorStore(Op, DAG);
8701       return SDValue();
8702     default:
8703       llvm_unreachable("unsupported private_element_size");
8704     }
8705   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8706     // Use ds_write_b128 or ds_write_b96 when possible.
8707     if (Subtarget->hasDS96AndDS128() &&
8708         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8709          (VT.getStoreSize() == 12)) &&
8710         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8711                                            Store->getAlign()))
8712       return SDValue();
8713 
8714     if (NumElements > 2)
8715       return SplitVectorStore(Op, DAG);
8716 
8717     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8718     // address is negative, then the instruction is incorrectly treated as
8719     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8720     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8721     // store later in the SILoadStoreOptimizer.
8722     if (!Subtarget->hasUsableDSOffset() &&
8723         NumElements == 2 && VT.getStoreSize() == 8 &&
8724         Store->getAlignment() < 8) {
8725       return SplitVectorStore(Op, DAG);
8726     }
8727 
8728     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8729                                         VT, *Store->getMemOperand())) {
8730       if (VT.isVector())
8731         return SplitVectorStore(Op, DAG);
8732       return expandUnalignedStore(Store, DAG);
8733     }
8734 
8735     return SDValue();
8736   } else {
8737     llvm_unreachable("unhandled address space");
8738   }
8739 }
8740 
8741 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8742   SDLoc DL(Op);
8743   EVT VT = Op.getValueType();
8744   SDValue Arg = Op.getOperand(0);
8745   SDValue TrigVal;
8746 
8747   // Propagate fast-math flags so that the multiply we introduce can be folded
8748   // if Arg is already the result of a multiply by constant.
8749   auto Flags = Op->getFlags();
8750 
8751   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8752 
8753   if (Subtarget->hasTrigReducedRange()) {
8754     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8755     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8756   } else {
8757     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8758   }
8759 
8760   switch (Op.getOpcode()) {
8761   case ISD::FCOS:
8762     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8763   case ISD::FSIN:
8764     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8765   default:
8766     llvm_unreachable("Wrong trig opcode");
8767   }
8768 }
8769 
8770 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8771   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8772   assert(AtomicNode->isCompareAndSwap());
8773   unsigned AS = AtomicNode->getAddressSpace();
8774 
8775   // No custom lowering required for local address space
8776   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8777     return Op;
8778 
8779   // Non-local address space requires custom lowering for atomic compare
8780   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8781   SDLoc DL(Op);
8782   SDValue ChainIn = Op.getOperand(0);
8783   SDValue Addr = Op.getOperand(1);
8784   SDValue Old = Op.getOperand(2);
8785   SDValue New = Op.getOperand(3);
8786   EVT VT = Op.getValueType();
8787   MVT SimpleVT = VT.getSimpleVT();
8788   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8789 
8790   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8791   SDValue Ops[] = { ChainIn, Addr, NewOld };
8792 
8793   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8794                                  Ops, VT, AtomicNode->getMemOperand());
8795 }
8796 
8797 //===----------------------------------------------------------------------===//
8798 // Custom DAG optimizations
8799 //===----------------------------------------------------------------------===//
8800 
8801 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8802                                                      DAGCombinerInfo &DCI) const {
8803   EVT VT = N->getValueType(0);
8804   EVT ScalarVT = VT.getScalarType();
8805   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8806     return SDValue();
8807 
8808   SelectionDAG &DAG = DCI.DAG;
8809   SDLoc DL(N);
8810 
8811   SDValue Src = N->getOperand(0);
8812   EVT SrcVT = Src.getValueType();
8813 
8814   // TODO: We could try to match extracting the higher bytes, which would be
8815   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8816   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8817   // about in practice.
8818   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8819     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8820       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8821       DCI.AddToWorklist(Cvt.getNode());
8822 
8823       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8824       if (ScalarVT != MVT::f32) {
8825         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8826                           DAG.getTargetConstant(0, DL, MVT::i32));
8827       }
8828       return Cvt;
8829     }
8830   }
8831 
8832   return SDValue();
8833 }
8834 
8835 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8836 
8837 // This is a variant of
8838 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8839 //
8840 // The normal DAG combiner will do this, but only if the add has one use since
8841 // that would increase the number of instructions.
8842 //
8843 // This prevents us from seeing a constant offset that can be folded into a
8844 // memory instruction's addressing mode. If we know the resulting add offset of
8845 // a pointer can be folded into an addressing offset, we can replace the pointer
8846 // operand with the add of new constant offset. This eliminates one of the uses,
8847 // and may allow the remaining use to also be simplified.
8848 //
8849 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8850                                                unsigned AddrSpace,
8851                                                EVT MemVT,
8852                                                DAGCombinerInfo &DCI) const {
8853   SDValue N0 = N->getOperand(0);
8854   SDValue N1 = N->getOperand(1);
8855 
8856   // We only do this to handle cases where it's profitable when there are
8857   // multiple uses of the add, so defer to the standard combine.
8858   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8859       N0->hasOneUse())
8860     return SDValue();
8861 
8862   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8863   if (!CN1)
8864     return SDValue();
8865 
8866   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8867   if (!CAdd)
8868     return SDValue();
8869 
8870   // If the resulting offset is too large, we can't fold it into the addressing
8871   // mode offset.
8872   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8873   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8874 
8875   AddrMode AM;
8876   AM.HasBaseReg = true;
8877   AM.BaseOffs = Offset.getSExtValue();
8878   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8879     return SDValue();
8880 
8881   SelectionDAG &DAG = DCI.DAG;
8882   SDLoc SL(N);
8883   EVT VT = N->getValueType(0);
8884 
8885   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8886   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8887 
8888   SDNodeFlags Flags;
8889   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8890                           (N0.getOpcode() == ISD::OR ||
8891                            N0->getFlags().hasNoUnsignedWrap()));
8892 
8893   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8894 }
8895 
8896 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8897 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8898 /// specific intrinsic, but they all place the pointer operand first.
8899 static unsigned getBasePtrIndex(const MemSDNode *N) {
8900   switch (N->getOpcode()) {
8901   case ISD::STORE:
8902   case ISD::INTRINSIC_W_CHAIN:
8903   case ISD::INTRINSIC_VOID:
8904     return 2;
8905   default:
8906     return 1;
8907   }
8908 }
8909 
8910 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8911                                                   DAGCombinerInfo &DCI) const {
8912   SelectionDAG &DAG = DCI.DAG;
8913   SDLoc SL(N);
8914 
8915   unsigned PtrIdx = getBasePtrIndex(N);
8916   SDValue Ptr = N->getOperand(PtrIdx);
8917 
8918   // TODO: We could also do this for multiplies.
8919   if (Ptr.getOpcode() == ISD::SHL) {
8920     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8921                                           N->getMemoryVT(), DCI);
8922     if (NewPtr) {
8923       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8924 
8925       NewOps[PtrIdx] = NewPtr;
8926       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8927     }
8928   }
8929 
8930   return SDValue();
8931 }
8932 
8933 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8934   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8935          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8936          (Opc == ISD::XOR && Val == 0);
8937 }
8938 
8939 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8940 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8941 // integer combine opportunities since most 64-bit operations are decomposed
8942 // this way.  TODO: We won't want this for SALU especially if it is an inline
8943 // immediate.
8944 SDValue SITargetLowering::splitBinaryBitConstantOp(
8945   DAGCombinerInfo &DCI,
8946   const SDLoc &SL,
8947   unsigned Opc, SDValue LHS,
8948   const ConstantSDNode *CRHS) const {
8949   uint64_t Val = CRHS->getZExtValue();
8950   uint32_t ValLo = Lo_32(Val);
8951   uint32_t ValHi = Hi_32(Val);
8952   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8953 
8954     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8955          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8956         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8957     // If we need to materialize a 64-bit immediate, it will be split up later
8958     // anyway. Avoid creating the harder to understand 64-bit immediate
8959     // materialization.
8960     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8961   }
8962 
8963   return SDValue();
8964 }
8965 
8966 // Returns true if argument is a boolean value which is not serialized into
8967 // memory or argument and does not require v_cndmask_b32 to be deserialized.
8968 static bool isBoolSGPR(SDValue V) {
8969   if (V.getValueType() != MVT::i1)
8970     return false;
8971   switch (V.getOpcode()) {
8972   default:
8973     break;
8974   case ISD::SETCC:
8975   case AMDGPUISD::FP_CLASS:
8976     return true;
8977   case ISD::AND:
8978   case ISD::OR:
8979   case ISD::XOR:
8980     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
8981   }
8982   return false;
8983 }
8984 
8985 // If a constant has all zeroes or all ones within each byte return it.
8986 // Otherwise return 0.
8987 static uint32_t getConstantPermuteMask(uint32_t C) {
8988   // 0xff for any zero byte in the mask
8989   uint32_t ZeroByteMask = 0;
8990   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8991   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8992   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8993   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8994   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8995   if ((NonZeroByteMask & C) != NonZeroByteMask)
8996     return 0; // Partial bytes selected.
8997   return C;
8998 }
8999 
9000 // Check if a node selects whole bytes from its operand 0 starting at a byte
9001 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9002 // or -1 if not succeeded.
9003 // Note byte select encoding:
9004 // value 0-3 selects corresponding source byte;
9005 // value 0xc selects zero;
9006 // value 0xff selects 0xff.
9007 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9008   assert(V.getValueSizeInBits() == 32);
9009 
9010   if (V.getNumOperands() != 2)
9011     return ~0;
9012 
9013   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9014   if (!N1)
9015     return ~0;
9016 
9017   uint32_t C = N1->getZExtValue();
9018 
9019   switch (V.getOpcode()) {
9020   default:
9021     break;
9022   case ISD::AND:
9023     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9024       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9025     }
9026     break;
9027 
9028   case ISD::OR:
9029     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9030       return (0x03020100 & ~ConstMask) | ConstMask;
9031     }
9032     break;
9033 
9034   case ISD::SHL:
9035     if (C % 8)
9036       return ~0;
9037 
9038     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9039 
9040   case ISD::SRL:
9041     if (C % 8)
9042       return ~0;
9043 
9044     return uint32_t(0x0c0c0c0c03020100ull >> C);
9045   }
9046 
9047   return ~0;
9048 }
9049 
9050 SDValue SITargetLowering::performAndCombine(SDNode *N,
9051                                             DAGCombinerInfo &DCI) const {
9052   if (DCI.isBeforeLegalize())
9053     return SDValue();
9054 
9055   SelectionDAG &DAG = DCI.DAG;
9056   EVT VT = N->getValueType(0);
9057   SDValue LHS = N->getOperand(0);
9058   SDValue RHS = N->getOperand(1);
9059 
9060 
9061   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9062   if (VT == MVT::i64 && CRHS) {
9063     if (SDValue Split
9064         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9065       return Split;
9066   }
9067 
9068   if (CRHS && VT == MVT::i32) {
9069     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9070     // nb = number of trailing zeroes in mask
9071     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9072     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9073     uint64_t Mask = CRHS->getZExtValue();
9074     unsigned Bits = countPopulation(Mask);
9075     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9076         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9077       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9078         unsigned Shift = CShift->getZExtValue();
9079         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9080         unsigned Offset = NB + Shift;
9081         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9082           SDLoc SL(N);
9083           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9084                                     LHS->getOperand(0),
9085                                     DAG.getConstant(Offset, SL, MVT::i32),
9086                                     DAG.getConstant(Bits, SL, MVT::i32));
9087           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9088           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9089                                     DAG.getValueType(NarrowVT));
9090           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9091                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9092           return Shl;
9093         }
9094       }
9095     }
9096 
9097     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9098     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9099         isa<ConstantSDNode>(LHS.getOperand(2))) {
9100       uint32_t Sel = getConstantPermuteMask(Mask);
9101       if (!Sel)
9102         return SDValue();
9103 
9104       // Select 0xc for all zero bytes
9105       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9106       SDLoc DL(N);
9107       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9108                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9109     }
9110   }
9111 
9112   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9113   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9114   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9115     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9116     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9117 
9118     SDValue X = LHS.getOperand(0);
9119     SDValue Y = RHS.getOperand(0);
9120     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9121       return SDValue();
9122 
9123     if (LCC == ISD::SETO) {
9124       if (X != LHS.getOperand(1))
9125         return SDValue();
9126 
9127       if (RCC == ISD::SETUNE) {
9128         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9129         if (!C1 || !C1->isInfinity() || C1->isNegative())
9130           return SDValue();
9131 
9132         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9133                               SIInstrFlags::N_SUBNORMAL |
9134                               SIInstrFlags::N_ZERO |
9135                               SIInstrFlags::P_ZERO |
9136                               SIInstrFlags::P_SUBNORMAL |
9137                               SIInstrFlags::P_NORMAL;
9138 
9139         static_assert(((~(SIInstrFlags::S_NAN |
9140                           SIInstrFlags::Q_NAN |
9141                           SIInstrFlags::N_INFINITY |
9142                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9143                       "mask not equal");
9144 
9145         SDLoc DL(N);
9146         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9147                            X, DAG.getConstant(Mask, DL, MVT::i32));
9148       }
9149     }
9150   }
9151 
9152   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9153     std::swap(LHS, RHS);
9154 
9155   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9156       RHS.hasOneUse()) {
9157     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9158     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9159     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9160     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9161     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9162         (RHS.getOperand(0) == LHS.getOperand(0) &&
9163          LHS.getOperand(0) == LHS.getOperand(1))) {
9164       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9165       unsigned NewMask = LCC == ISD::SETO ?
9166         Mask->getZExtValue() & ~OrdMask :
9167         Mask->getZExtValue() & OrdMask;
9168 
9169       SDLoc DL(N);
9170       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9171                          DAG.getConstant(NewMask, DL, MVT::i32));
9172     }
9173   }
9174 
9175   if (VT == MVT::i32 &&
9176       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9177     // and x, (sext cc from i1) => select cc, x, 0
9178     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9179       std::swap(LHS, RHS);
9180     if (isBoolSGPR(RHS.getOperand(0)))
9181       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9182                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9183   }
9184 
9185   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9186   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9187   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9188       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9189     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9190     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9191     if (LHSMask != ~0u && RHSMask != ~0u) {
9192       // Canonicalize the expression in an attempt to have fewer unique masks
9193       // and therefore fewer registers used to hold the masks.
9194       if (LHSMask > RHSMask) {
9195         std::swap(LHSMask, RHSMask);
9196         std::swap(LHS, RHS);
9197       }
9198 
9199       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9200       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9201       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9202       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9203 
9204       // Check of we need to combine values from two sources within a byte.
9205       if (!(LHSUsedLanes & RHSUsedLanes) &&
9206           // If we select high and lower word keep it for SDWA.
9207           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9208           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9209         // Each byte in each mask is either selector mask 0-3, or has higher
9210         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9211         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9212         // mask which is not 0xff wins. By anding both masks we have a correct
9213         // result except that 0x0c shall be corrected to give 0x0c only.
9214         uint32_t Mask = LHSMask & RHSMask;
9215         for (unsigned I = 0; I < 32; I += 8) {
9216           uint32_t ByteSel = 0xff << I;
9217           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9218             Mask &= (0x0c << I) & 0xffffffff;
9219         }
9220 
9221         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9222         // or 0x0c.
9223         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9224         SDLoc DL(N);
9225 
9226         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9227                            LHS.getOperand(0), RHS.getOperand(0),
9228                            DAG.getConstant(Sel, DL, MVT::i32));
9229       }
9230     }
9231   }
9232 
9233   return SDValue();
9234 }
9235 
9236 SDValue SITargetLowering::performOrCombine(SDNode *N,
9237                                            DAGCombinerInfo &DCI) const {
9238   SelectionDAG &DAG = DCI.DAG;
9239   SDValue LHS = N->getOperand(0);
9240   SDValue RHS = N->getOperand(1);
9241 
9242   EVT VT = N->getValueType(0);
9243   if (VT == MVT::i1) {
9244     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9245     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9246         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9247       SDValue Src = LHS.getOperand(0);
9248       if (Src != RHS.getOperand(0))
9249         return SDValue();
9250 
9251       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9252       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9253       if (!CLHS || !CRHS)
9254         return SDValue();
9255 
9256       // Only 10 bits are used.
9257       static const uint32_t MaxMask = 0x3ff;
9258 
9259       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9260       SDLoc DL(N);
9261       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9262                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9263     }
9264 
9265     return SDValue();
9266   }
9267 
9268   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9269   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9270       LHS.getOpcode() == AMDGPUISD::PERM &&
9271       isa<ConstantSDNode>(LHS.getOperand(2))) {
9272     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9273     if (!Sel)
9274       return SDValue();
9275 
9276     Sel |= LHS.getConstantOperandVal(2);
9277     SDLoc DL(N);
9278     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9279                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9280   }
9281 
9282   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9283   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9284   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9285       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9286     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9287     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9288     if (LHSMask != ~0u && RHSMask != ~0u) {
9289       // Canonicalize the expression in an attempt to have fewer unique masks
9290       // and therefore fewer registers used to hold the masks.
9291       if (LHSMask > RHSMask) {
9292         std::swap(LHSMask, RHSMask);
9293         std::swap(LHS, RHS);
9294       }
9295 
9296       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9297       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9298       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9299       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9300 
9301       // Check of we need to combine values from two sources within a byte.
9302       if (!(LHSUsedLanes & RHSUsedLanes) &&
9303           // If we select high and lower word keep it for SDWA.
9304           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9305           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9306         // Kill zero bytes selected by other mask. Zero value is 0xc.
9307         LHSMask &= ~RHSUsedLanes;
9308         RHSMask &= ~LHSUsedLanes;
9309         // Add 4 to each active LHS lane
9310         LHSMask |= LHSUsedLanes & 0x04040404;
9311         // Combine masks
9312         uint32_t Sel = LHSMask | RHSMask;
9313         SDLoc DL(N);
9314 
9315         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9316                            LHS.getOperand(0), RHS.getOperand(0),
9317                            DAG.getConstant(Sel, DL, MVT::i32));
9318       }
9319     }
9320   }
9321 
9322   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9323     return SDValue();
9324 
9325   // TODO: This could be a generic combine with a predicate for extracting the
9326   // high half of an integer being free.
9327 
9328   // (or i64:x, (zero_extend i32:y)) ->
9329   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9330   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9331       RHS.getOpcode() != ISD::ZERO_EXTEND)
9332     std::swap(LHS, RHS);
9333 
9334   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9335     SDValue ExtSrc = RHS.getOperand(0);
9336     EVT SrcVT = ExtSrc.getValueType();
9337     if (SrcVT == MVT::i32) {
9338       SDLoc SL(N);
9339       SDValue LowLHS, HiBits;
9340       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9341       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9342 
9343       DCI.AddToWorklist(LowOr.getNode());
9344       DCI.AddToWorklist(HiBits.getNode());
9345 
9346       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9347                                 LowOr, HiBits);
9348       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9349     }
9350   }
9351 
9352   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9353   if (CRHS) {
9354     if (SDValue Split
9355           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9356       return Split;
9357   }
9358 
9359   return SDValue();
9360 }
9361 
9362 SDValue SITargetLowering::performXorCombine(SDNode *N,
9363                                             DAGCombinerInfo &DCI) const {
9364   EVT VT = N->getValueType(0);
9365   if (VT != MVT::i64)
9366     return SDValue();
9367 
9368   SDValue LHS = N->getOperand(0);
9369   SDValue RHS = N->getOperand(1);
9370 
9371   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9372   if (CRHS) {
9373     if (SDValue Split
9374           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9375       return Split;
9376   }
9377 
9378   return SDValue();
9379 }
9380 
9381 // Instructions that will be lowered with a final instruction that zeros the
9382 // high result bits.
9383 // XXX - probably only need to list legal operations.
9384 static bool fp16SrcZerosHighBits(unsigned Opc) {
9385   switch (Opc) {
9386   case ISD::FADD:
9387   case ISD::FSUB:
9388   case ISD::FMUL:
9389   case ISD::FDIV:
9390   case ISD::FREM:
9391   case ISD::FMA:
9392   case ISD::FMAD:
9393   case ISD::FCANONICALIZE:
9394   case ISD::FP_ROUND:
9395   case ISD::UINT_TO_FP:
9396   case ISD::SINT_TO_FP:
9397   case ISD::FABS:
9398     // Fabs is lowered to a bit operation, but it's an and which will clear the
9399     // high bits anyway.
9400   case ISD::FSQRT:
9401   case ISD::FSIN:
9402   case ISD::FCOS:
9403   case ISD::FPOWI:
9404   case ISD::FPOW:
9405   case ISD::FLOG:
9406   case ISD::FLOG2:
9407   case ISD::FLOG10:
9408   case ISD::FEXP:
9409   case ISD::FEXP2:
9410   case ISD::FCEIL:
9411   case ISD::FTRUNC:
9412   case ISD::FRINT:
9413   case ISD::FNEARBYINT:
9414   case ISD::FROUND:
9415   case ISD::FFLOOR:
9416   case ISD::FMINNUM:
9417   case ISD::FMAXNUM:
9418   case AMDGPUISD::FRACT:
9419   case AMDGPUISD::CLAMP:
9420   case AMDGPUISD::COS_HW:
9421   case AMDGPUISD::SIN_HW:
9422   case AMDGPUISD::FMIN3:
9423   case AMDGPUISD::FMAX3:
9424   case AMDGPUISD::FMED3:
9425   case AMDGPUISD::FMAD_FTZ:
9426   case AMDGPUISD::RCP:
9427   case AMDGPUISD::RSQ:
9428   case AMDGPUISD::RCP_IFLAG:
9429   case AMDGPUISD::LDEXP:
9430     return true;
9431   default:
9432     // fcopysign, select and others may be lowered to 32-bit bit operations
9433     // which don't zero the high bits.
9434     return false;
9435   }
9436 }
9437 
9438 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9439                                                    DAGCombinerInfo &DCI) const {
9440   if (!Subtarget->has16BitInsts() ||
9441       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9442     return SDValue();
9443 
9444   EVT VT = N->getValueType(0);
9445   if (VT != MVT::i32)
9446     return SDValue();
9447 
9448   SDValue Src = N->getOperand(0);
9449   if (Src.getValueType() != MVT::i16)
9450     return SDValue();
9451 
9452   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9453   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9454   if (Src.getOpcode() == ISD::BITCAST) {
9455     SDValue BCSrc = Src.getOperand(0);
9456     if (BCSrc.getValueType() == MVT::f16 &&
9457         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9458       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9459   }
9460 
9461   return SDValue();
9462 }
9463 
9464 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9465                                                         DAGCombinerInfo &DCI)
9466                                                         const {
9467   SDValue Src = N->getOperand(0);
9468   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9469 
9470   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9471       VTSign->getVT() == MVT::i8) ||
9472       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9473       VTSign->getVT() == MVT::i16)) &&
9474       Src.hasOneUse()) {
9475     auto *M = cast<MemSDNode>(Src);
9476     SDValue Ops[] = {
9477       Src.getOperand(0), // Chain
9478       Src.getOperand(1), // rsrc
9479       Src.getOperand(2), // vindex
9480       Src.getOperand(3), // voffset
9481       Src.getOperand(4), // soffset
9482       Src.getOperand(5), // offset
9483       Src.getOperand(6),
9484       Src.getOperand(7)
9485     };
9486     // replace with BUFFER_LOAD_BYTE/SHORT
9487     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9488                                          Src.getOperand(0).getValueType());
9489     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9490                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9491     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9492                                                           ResList,
9493                                                           Ops, M->getMemoryVT(),
9494                                                           M->getMemOperand());
9495     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9496                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9497   }
9498   return SDValue();
9499 }
9500 
9501 SDValue SITargetLowering::performClassCombine(SDNode *N,
9502                                               DAGCombinerInfo &DCI) const {
9503   SelectionDAG &DAG = DCI.DAG;
9504   SDValue Mask = N->getOperand(1);
9505 
9506   // fp_class x, 0 -> false
9507   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9508     if (CMask->isNullValue())
9509       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9510   }
9511 
9512   if (N->getOperand(0).isUndef())
9513     return DAG.getUNDEF(MVT::i1);
9514 
9515   return SDValue();
9516 }
9517 
9518 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9519                                             DAGCombinerInfo &DCI) const {
9520   EVT VT = N->getValueType(0);
9521   SDValue N0 = N->getOperand(0);
9522 
9523   if (N0.isUndef())
9524     return N0;
9525 
9526   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9527                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9528     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9529                            N->getFlags());
9530   }
9531 
9532   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9533     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9534                            N0.getOperand(0), N->getFlags());
9535   }
9536 
9537   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9538 }
9539 
9540 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9541                                        unsigned MaxDepth) const {
9542   unsigned Opcode = Op.getOpcode();
9543   if (Opcode == ISD::FCANONICALIZE)
9544     return true;
9545 
9546   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9547     auto F = CFP->getValueAPF();
9548     if (F.isNaN() && F.isSignaling())
9549       return false;
9550     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9551   }
9552 
9553   // If source is a result of another standard FP operation it is already in
9554   // canonical form.
9555   if (MaxDepth == 0)
9556     return false;
9557 
9558   switch (Opcode) {
9559   // These will flush denorms if required.
9560   case ISD::FADD:
9561   case ISD::FSUB:
9562   case ISD::FMUL:
9563   case ISD::FCEIL:
9564   case ISD::FFLOOR:
9565   case ISD::FMA:
9566   case ISD::FMAD:
9567   case ISD::FSQRT:
9568   case ISD::FDIV:
9569   case ISD::FREM:
9570   case ISD::FP_ROUND:
9571   case ISD::FP_EXTEND:
9572   case AMDGPUISD::FMUL_LEGACY:
9573   case AMDGPUISD::FMAD_FTZ:
9574   case AMDGPUISD::RCP:
9575   case AMDGPUISD::RSQ:
9576   case AMDGPUISD::RSQ_CLAMP:
9577   case AMDGPUISD::RCP_LEGACY:
9578   case AMDGPUISD::RCP_IFLAG:
9579   case AMDGPUISD::DIV_SCALE:
9580   case AMDGPUISD::DIV_FMAS:
9581   case AMDGPUISD::DIV_FIXUP:
9582   case AMDGPUISD::FRACT:
9583   case AMDGPUISD::LDEXP:
9584   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9585   case AMDGPUISD::CVT_F32_UBYTE0:
9586   case AMDGPUISD::CVT_F32_UBYTE1:
9587   case AMDGPUISD::CVT_F32_UBYTE2:
9588   case AMDGPUISD::CVT_F32_UBYTE3:
9589     return true;
9590 
9591   // It can/will be lowered or combined as a bit operation.
9592   // Need to check their input recursively to handle.
9593   case ISD::FNEG:
9594   case ISD::FABS:
9595   case ISD::FCOPYSIGN:
9596     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9597 
9598   case ISD::FSIN:
9599   case ISD::FCOS:
9600   case ISD::FSINCOS:
9601     return Op.getValueType().getScalarType() != MVT::f16;
9602 
9603   case ISD::FMINNUM:
9604   case ISD::FMAXNUM:
9605   case ISD::FMINNUM_IEEE:
9606   case ISD::FMAXNUM_IEEE:
9607   case AMDGPUISD::CLAMP:
9608   case AMDGPUISD::FMED3:
9609   case AMDGPUISD::FMAX3:
9610   case AMDGPUISD::FMIN3: {
9611     // FIXME: Shouldn't treat the generic operations different based these.
9612     // However, we aren't really required to flush the result from
9613     // minnum/maxnum..
9614 
9615     // snans will be quieted, so we only need to worry about denormals.
9616     if (Subtarget->supportsMinMaxDenormModes() ||
9617         denormalsEnabledForType(DAG, Op.getValueType()))
9618       return true;
9619 
9620     // Flushing may be required.
9621     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9622     // targets need to check their input recursively.
9623 
9624     // FIXME: Does this apply with clamp? It's implemented with max.
9625     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9626       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9627         return false;
9628     }
9629 
9630     return true;
9631   }
9632   case ISD::SELECT: {
9633     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9634            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9635   }
9636   case ISD::BUILD_VECTOR: {
9637     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9638       SDValue SrcOp = Op.getOperand(i);
9639       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9640         return false;
9641     }
9642 
9643     return true;
9644   }
9645   case ISD::EXTRACT_VECTOR_ELT:
9646   case ISD::EXTRACT_SUBVECTOR: {
9647     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9648   }
9649   case ISD::INSERT_VECTOR_ELT: {
9650     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9651            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9652   }
9653   case ISD::UNDEF:
9654     // Could be anything.
9655     return false;
9656 
9657   case ISD::BITCAST:
9658     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9659   case ISD::TRUNCATE: {
9660     // Hack round the mess we make when legalizing extract_vector_elt
9661     if (Op.getValueType() == MVT::i16) {
9662       SDValue TruncSrc = Op.getOperand(0);
9663       if (TruncSrc.getValueType() == MVT::i32 &&
9664           TruncSrc.getOpcode() == ISD::BITCAST &&
9665           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9666         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9667       }
9668     }
9669     return false;
9670   }
9671   case ISD::INTRINSIC_WO_CHAIN: {
9672     unsigned IntrinsicID
9673       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9674     // TODO: Handle more intrinsics
9675     switch (IntrinsicID) {
9676     case Intrinsic::amdgcn_cvt_pkrtz:
9677     case Intrinsic::amdgcn_cubeid:
9678     case Intrinsic::amdgcn_frexp_mant:
9679     case Intrinsic::amdgcn_fdot2:
9680     case Intrinsic::amdgcn_rcp:
9681     case Intrinsic::amdgcn_rsq:
9682     case Intrinsic::amdgcn_rsq_clamp:
9683     case Intrinsic::amdgcn_rcp_legacy:
9684     case Intrinsic::amdgcn_rsq_legacy:
9685     case Intrinsic::amdgcn_trig_preop:
9686       return true;
9687     default:
9688       break;
9689     }
9690 
9691     LLVM_FALLTHROUGH;
9692   }
9693   default:
9694     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9695            DAG.isKnownNeverSNaN(Op);
9696   }
9697 
9698   llvm_unreachable("invalid operation");
9699 }
9700 
9701 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9702                                        unsigned MaxDepth) const {
9703   MachineRegisterInfo &MRI = MF.getRegInfo();
9704   MachineInstr *MI = MRI.getVRegDef(Reg);
9705   unsigned Opcode = MI->getOpcode();
9706 
9707   if (Opcode == AMDGPU::G_FCANONICALIZE)
9708     return true;
9709 
9710   if (Opcode == AMDGPU::G_FCONSTANT) {
9711     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9712     if (F.isNaN() && F.isSignaling())
9713       return false;
9714     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9715   }
9716 
9717   if (MaxDepth == 0)
9718     return false;
9719 
9720   switch (Opcode) {
9721   case AMDGPU::G_FMINNUM_IEEE:
9722   case AMDGPU::G_FMAXNUM_IEEE: {
9723     if (Subtarget->supportsMinMaxDenormModes() ||
9724         denormalsEnabledForType(MRI.getType(Reg), MF))
9725       return true;
9726     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9727       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9728         return false;
9729     }
9730     return true;
9731   }
9732   default:
9733     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9734            isKnownNeverSNaN(Reg, MRI);
9735   }
9736 
9737   llvm_unreachable("invalid operation");
9738 }
9739 
9740 // Constant fold canonicalize.
9741 SDValue SITargetLowering::getCanonicalConstantFP(
9742   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9743   // Flush denormals to 0 if not enabled.
9744   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9745     return DAG.getConstantFP(0.0, SL, VT);
9746 
9747   if (C.isNaN()) {
9748     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9749     if (C.isSignaling()) {
9750       // Quiet a signaling NaN.
9751       // FIXME: Is this supposed to preserve payload bits?
9752       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9753     }
9754 
9755     // Make sure it is the canonical NaN bitpattern.
9756     //
9757     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9758     // immediate?
9759     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9760       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9761   }
9762 
9763   // Already canonical.
9764   return DAG.getConstantFP(C, SL, VT);
9765 }
9766 
9767 static bool vectorEltWillFoldAway(SDValue Op) {
9768   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9769 }
9770 
9771 SDValue SITargetLowering::performFCanonicalizeCombine(
9772   SDNode *N,
9773   DAGCombinerInfo &DCI) const {
9774   SelectionDAG &DAG = DCI.DAG;
9775   SDValue N0 = N->getOperand(0);
9776   EVT VT = N->getValueType(0);
9777 
9778   // fcanonicalize undef -> qnan
9779   if (N0.isUndef()) {
9780     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9781     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9782   }
9783 
9784   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9785     EVT VT = N->getValueType(0);
9786     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9787   }
9788 
9789   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9790   //                                                   (fcanonicalize k)
9791   //
9792   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9793 
9794   // TODO: This could be better with wider vectors that will be split to v2f16,
9795   // and to consider uses since there aren't that many packed operations.
9796   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9797       isTypeLegal(MVT::v2f16)) {
9798     SDLoc SL(N);
9799     SDValue NewElts[2];
9800     SDValue Lo = N0.getOperand(0);
9801     SDValue Hi = N0.getOperand(1);
9802     EVT EltVT = Lo.getValueType();
9803 
9804     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9805       for (unsigned I = 0; I != 2; ++I) {
9806         SDValue Op = N0.getOperand(I);
9807         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9808           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9809                                               CFP->getValueAPF());
9810         } else if (Op.isUndef()) {
9811           // Handled below based on what the other operand is.
9812           NewElts[I] = Op;
9813         } else {
9814           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9815         }
9816       }
9817 
9818       // If one half is undef, and one is constant, perfer a splat vector rather
9819       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9820       // cheaper to use and may be free with a packed operation.
9821       if (NewElts[0].isUndef()) {
9822         if (isa<ConstantFPSDNode>(NewElts[1]))
9823           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9824             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9825       }
9826 
9827       if (NewElts[1].isUndef()) {
9828         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9829           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9830       }
9831 
9832       return DAG.getBuildVector(VT, SL, NewElts);
9833     }
9834   }
9835 
9836   unsigned SrcOpc = N0.getOpcode();
9837 
9838   // If it's free to do so, push canonicalizes further up the source, which may
9839   // find a canonical source.
9840   //
9841   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9842   // sNaNs.
9843   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9844     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9845     if (CRHS && N0.hasOneUse()) {
9846       SDLoc SL(N);
9847       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9848                                    N0.getOperand(0));
9849       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9850       DCI.AddToWorklist(Canon0.getNode());
9851 
9852       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9853     }
9854   }
9855 
9856   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9857 }
9858 
9859 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9860   switch (Opc) {
9861   case ISD::FMAXNUM:
9862   case ISD::FMAXNUM_IEEE:
9863     return AMDGPUISD::FMAX3;
9864   case ISD::SMAX:
9865     return AMDGPUISD::SMAX3;
9866   case ISD::UMAX:
9867     return AMDGPUISD::UMAX3;
9868   case ISD::FMINNUM:
9869   case ISD::FMINNUM_IEEE:
9870     return AMDGPUISD::FMIN3;
9871   case ISD::SMIN:
9872     return AMDGPUISD::SMIN3;
9873   case ISD::UMIN:
9874     return AMDGPUISD::UMIN3;
9875   default:
9876     llvm_unreachable("Not a min/max opcode");
9877   }
9878 }
9879 
9880 SDValue SITargetLowering::performIntMed3ImmCombine(
9881   SelectionDAG &DAG, const SDLoc &SL,
9882   SDValue Op0, SDValue Op1, bool Signed) const {
9883   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9884   if (!K1)
9885     return SDValue();
9886 
9887   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9888   if (!K0)
9889     return SDValue();
9890 
9891   if (Signed) {
9892     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9893       return SDValue();
9894   } else {
9895     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9896       return SDValue();
9897   }
9898 
9899   EVT VT = K0->getValueType(0);
9900   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9901   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9902     return DAG.getNode(Med3Opc, SL, VT,
9903                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9904   }
9905 
9906   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9907   if (VT == MVT::i16) {
9908     MVT NVT = MVT::i32;
9909     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9910 
9911     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9912     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9913     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9914 
9915     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9916     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9917   }
9918 
9919   return SDValue();
9920 }
9921 
9922 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9923   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9924     return C;
9925 
9926   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9927     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9928       return C;
9929   }
9930 
9931   return nullptr;
9932 }
9933 
9934 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9935                                                   const SDLoc &SL,
9936                                                   SDValue Op0,
9937                                                   SDValue Op1) const {
9938   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9939   if (!K1)
9940     return SDValue();
9941 
9942   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9943   if (!K0)
9944     return SDValue();
9945 
9946   // Ordered >= (although NaN inputs should have folded away by now).
9947   if (K0->getValueAPF() > K1->getValueAPF())
9948     return SDValue();
9949 
9950   const MachineFunction &MF = DAG.getMachineFunction();
9951   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9952 
9953   // TODO: Check IEEE bit enabled?
9954   EVT VT = Op0.getValueType();
9955   if (Info->getMode().DX10Clamp) {
9956     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9957     // hardware fmed3 behavior converting to a min.
9958     // FIXME: Should this be allowing -0.0?
9959     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9960       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9961   }
9962 
9963   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9964   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9965     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9966     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9967     // then give the other result, which is different from med3 with a NaN
9968     // input.
9969     SDValue Var = Op0.getOperand(0);
9970     if (!DAG.isKnownNeverSNaN(Var))
9971       return SDValue();
9972 
9973     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9974 
9975     if ((!K0->hasOneUse() ||
9976          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9977         (!K1->hasOneUse() ||
9978          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9979       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9980                          Var, SDValue(K0, 0), SDValue(K1, 0));
9981     }
9982   }
9983 
9984   return SDValue();
9985 }
9986 
9987 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9988                                                DAGCombinerInfo &DCI) const {
9989   SelectionDAG &DAG = DCI.DAG;
9990 
9991   EVT VT = N->getValueType(0);
9992   unsigned Opc = N->getOpcode();
9993   SDValue Op0 = N->getOperand(0);
9994   SDValue Op1 = N->getOperand(1);
9995 
9996   // Only do this if the inner op has one use since this will just increases
9997   // register pressure for no benefit.
9998 
9999   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10000       !VT.isVector() &&
10001       (VT == MVT::i32 || VT == MVT::f32 ||
10002        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10003     // max(max(a, b), c) -> max3(a, b, c)
10004     // min(min(a, b), c) -> min3(a, b, c)
10005     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10006       SDLoc DL(N);
10007       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10008                          DL,
10009                          N->getValueType(0),
10010                          Op0.getOperand(0),
10011                          Op0.getOperand(1),
10012                          Op1);
10013     }
10014 
10015     // Try commuted.
10016     // max(a, max(b, c)) -> max3(a, b, c)
10017     // min(a, min(b, c)) -> min3(a, b, c)
10018     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10019       SDLoc DL(N);
10020       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10021                          DL,
10022                          N->getValueType(0),
10023                          Op0,
10024                          Op1.getOperand(0),
10025                          Op1.getOperand(1));
10026     }
10027   }
10028 
10029   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10030   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10031     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10032       return Med3;
10033   }
10034 
10035   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10036     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10037       return Med3;
10038   }
10039 
10040   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10041   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10042        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10043        (Opc == AMDGPUISD::FMIN_LEGACY &&
10044         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10045       (VT == MVT::f32 || VT == MVT::f64 ||
10046        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10047        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10048       Op0.hasOneUse()) {
10049     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10050       return Res;
10051   }
10052 
10053   return SDValue();
10054 }
10055 
10056 static bool isClampZeroToOne(SDValue A, SDValue B) {
10057   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10058     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10059       // FIXME: Should this be allowing -0.0?
10060       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10061              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10062     }
10063   }
10064 
10065   return false;
10066 }
10067 
10068 // FIXME: Should only worry about snans for version with chain.
10069 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10070                                               DAGCombinerInfo &DCI) const {
10071   EVT VT = N->getValueType(0);
10072   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10073   // NaNs. With a NaN input, the order of the operands may change the result.
10074 
10075   SelectionDAG &DAG = DCI.DAG;
10076   SDLoc SL(N);
10077 
10078   SDValue Src0 = N->getOperand(0);
10079   SDValue Src1 = N->getOperand(1);
10080   SDValue Src2 = N->getOperand(2);
10081 
10082   if (isClampZeroToOne(Src0, Src1)) {
10083     // const_a, const_b, x -> clamp is safe in all cases including signaling
10084     // nans.
10085     // FIXME: Should this be allowing -0.0?
10086     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10087   }
10088 
10089   const MachineFunction &MF = DAG.getMachineFunction();
10090   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10091 
10092   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10093   // handling no dx10-clamp?
10094   if (Info->getMode().DX10Clamp) {
10095     // If NaNs is clamped to 0, we are free to reorder the inputs.
10096 
10097     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10098       std::swap(Src0, Src1);
10099 
10100     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10101       std::swap(Src1, Src2);
10102 
10103     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10104       std::swap(Src0, Src1);
10105 
10106     if (isClampZeroToOne(Src1, Src2))
10107       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10108   }
10109 
10110   return SDValue();
10111 }
10112 
10113 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10114                                                  DAGCombinerInfo &DCI) const {
10115   SDValue Src0 = N->getOperand(0);
10116   SDValue Src1 = N->getOperand(1);
10117   if (Src0.isUndef() && Src1.isUndef())
10118     return DCI.DAG.getUNDEF(N->getValueType(0));
10119   return SDValue();
10120 }
10121 
10122 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10123 // expanded into a set of cmp/select instructions.
10124 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10125                                                 unsigned NumElem,
10126                                                 bool IsDivergentIdx) {
10127   if (UseDivergentRegisterIndexing)
10128     return false;
10129 
10130   unsigned VecSize = EltSize * NumElem;
10131 
10132   // Sub-dword vectors of size 2 dword or less have better implementation.
10133   if (VecSize <= 64 && EltSize < 32)
10134     return false;
10135 
10136   // Always expand the rest of sub-dword instructions, otherwise it will be
10137   // lowered via memory.
10138   if (EltSize < 32)
10139     return true;
10140 
10141   // Always do this if var-idx is divergent, otherwise it will become a loop.
10142   if (IsDivergentIdx)
10143     return true;
10144 
10145   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10146   unsigned NumInsts = NumElem /* Number of compares */ +
10147                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10148   return NumInsts <= 16;
10149 }
10150 
10151 static bool shouldExpandVectorDynExt(SDNode *N) {
10152   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10153   if (isa<ConstantSDNode>(Idx))
10154     return false;
10155 
10156   SDValue Vec = N->getOperand(0);
10157   EVT VecVT = Vec.getValueType();
10158   EVT EltVT = VecVT.getVectorElementType();
10159   unsigned EltSize = EltVT.getSizeInBits();
10160   unsigned NumElem = VecVT.getVectorNumElements();
10161 
10162   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10163                                                     Idx->isDivergent());
10164 }
10165 
10166 SDValue SITargetLowering::performExtractVectorEltCombine(
10167   SDNode *N, DAGCombinerInfo &DCI) const {
10168   SDValue Vec = N->getOperand(0);
10169   SelectionDAG &DAG = DCI.DAG;
10170 
10171   EVT VecVT = Vec.getValueType();
10172   EVT EltVT = VecVT.getVectorElementType();
10173 
10174   if ((Vec.getOpcode() == ISD::FNEG ||
10175        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10176     SDLoc SL(N);
10177     EVT EltVT = N->getValueType(0);
10178     SDValue Idx = N->getOperand(1);
10179     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10180                               Vec.getOperand(0), Idx);
10181     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10182   }
10183 
10184   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10185   //    =>
10186   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10187   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10188   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10189   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10190     SDLoc SL(N);
10191     EVT EltVT = N->getValueType(0);
10192     SDValue Idx = N->getOperand(1);
10193     unsigned Opc = Vec.getOpcode();
10194 
10195     switch(Opc) {
10196     default:
10197       break;
10198       // TODO: Support other binary operations.
10199     case ISD::FADD:
10200     case ISD::FSUB:
10201     case ISD::FMUL:
10202     case ISD::ADD:
10203     case ISD::UMIN:
10204     case ISD::UMAX:
10205     case ISD::SMIN:
10206     case ISD::SMAX:
10207     case ISD::FMAXNUM:
10208     case ISD::FMINNUM:
10209     case ISD::FMAXNUM_IEEE:
10210     case ISD::FMINNUM_IEEE: {
10211       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10212                                  Vec.getOperand(0), Idx);
10213       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10214                                  Vec.getOperand(1), Idx);
10215 
10216       DCI.AddToWorklist(Elt0.getNode());
10217       DCI.AddToWorklist(Elt1.getNode());
10218       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10219     }
10220     }
10221   }
10222 
10223   unsigned VecSize = VecVT.getSizeInBits();
10224   unsigned EltSize = EltVT.getSizeInBits();
10225 
10226   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10227   if (::shouldExpandVectorDynExt(N)) {
10228     SDLoc SL(N);
10229     SDValue Idx = N->getOperand(1);
10230     SDValue V;
10231     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10232       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10233       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10234       if (I == 0)
10235         V = Elt;
10236       else
10237         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10238     }
10239     return V;
10240   }
10241 
10242   if (!DCI.isBeforeLegalize())
10243     return SDValue();
10244 
10245   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10246   // elements. This exposes more load reduction opportunities by replacing
10247   // multiple small extract_vector_elements with a single 32-bit extract.
10248   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10249   if (isa<MemSDNode>(Vec) &&
10250       EltSize <= 16 &&
10251       EltVT.isByteSized() &&
10252       VecSize > 32 &&
10253       VecSize % 32 == 0 &&
10254       Idx) {
10255     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10256 
10257     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10258     unsigned EltIdx = BitIndex / 32;
10259     unsigned LeftoverBitIdx = BitIndex % 32;
10260     SDLoc SL(N);
10261 
10262     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10263     DCI.AddToWorklist(Cast.getNode());
10264 
10265     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10266                               DAG.getConstant(EltIdx, SL, MVT::i32));
10267     DCI.AddToWorklist(Elt.getNode());
10268     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10269                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10270     DCI.AddToWorklist(Srl.getNode());
10271 
10272     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10273     DCI.AddToWorklist(Trunc.getNode());
10274     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10275   }
10276 
10277   return SDValue();
10278 }
10279 
10280 SDValue
10281 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10282                                                 DAGCombinerInfo &DCI) const {
10283   SDValue Vec = N->getOperand(0);
10284   SDValue Idx = N->getOperand(2);
10285   EVT VecVT = Vec.getValueType();
10286   EVT EltVT = VecVT.getVectorElementType();
10287 
10288   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10289   // => BUILD_VECTOR n x select (e, const-idx)
10290   if (!::shouldExpandVectorDynExt(N))
10291     return SDValue();
10292 
10293   SelectionDAG &DAG = DCI.DAG;
10294   SDLoc SL(N);
10295   SDValue Ins = N->getOperand(1);
10296   EVT IdxVT = Idx.getValueType();
10297 
10298   SmallVector<SDValue, 16> Ops;
10299   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10300     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10301     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10302     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10303     Ops.push_back(V);
10304   }
10305 
10306   return DAG.getBuildVector(VecVT, SL, Ops);
10307 }
10308 
10309 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10310                                           const SDNode *N0,
10311                                           const SDNode *N1) const {
10312   EVT VT = N0->getValueType(0);
10313 
10314   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10315   // support denormals ever.
10316   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10317        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10318         getSubtarget()->hasMadF16())) &&
10319        isOperationLegal(ISD::FMAD, VT))
10320     return ISD::FMAD;
10321 
10322   const TargetOptions &Options = DAG.getTarget().Options;
10323   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10324        (N0->getFlags().hasAllowContract() &&
10325         N1->getFlags().hasAllowContract())) &&
10326       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10327     return ISD::FMA;
10328   }
10329 
10330   return 0;
10331 }
10332 
10333 // For a reassociatable opcode perform:
10334 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10335 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10336                                                SelectionDAG &DAG) const {
10337   EVT VT = N->getValueType(0);
10338   if (VT != MVT::i32 && VT != MVT::i64)
10339     return SDValue();
10340 
10341   unsigned Opc = N->getOpcode();
10342   SDValue Op0 = N->getOperand(0);
10343   SDValue Op1 = N->getOperand(1);
10344 
10345   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10346     return SDValue();
10347 
10348   if (Op0->isDivergent())
10349     std::swap(Op0, Op1);
10350 
10351   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10352     return SDValue();
10353 
10354   SDValue Op2 = Op1.getOperand(1);
10355   Op1 = Op1.getOperand(0);
10356   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10357     return SDValue();
10358 
10359   if (Op1->isDivergent())
10360     std::swap(Op1, Op2);
10361 
10362   // If either operand is constant this will conflict with
10363   // DAGCombiner::ReassociateOps().
10364   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10365       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10366     return SDValue();
10367 
10368   SDLoc SL(N);
10369   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10370   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10371 }
10372 
10373 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10374                            EVT VT,
10375                            SDValue N0, SDValue N1, SDValue N2,
10376                            bool Signed) {
10377   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10378   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10379   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10380   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10381 }
10382 
10383 SDValue SITargetLowering::performAddCombine(SDNode *N,
10384                                             DAGCombinerInfo &DCI) const {
10385   SelectionDAG &DAG = DCI.DAG;
10386   EVT VT = N->getValueType(0);
10387   SDLoc SL(N);
10388   SDValue LHS = N->getOperand(0);
10389   SDValue RHS = N->getOperand(1);
10390 
10391   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10392       && Subtarget->hasMad64_32() &&
10393       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10394       VT.getScalarSizeInBits() <= 64) {
10395     if (LHS.getOpcode() != ISD::MUL)
10396       std::swap(LHS, RHS);
10397 
10398     SDValue MulLHS = LHS.getOperand(0);
10399     SDValue MulRHS = LHS.getOperand(1);
10400     SDValue AddRHS = RHS;
10401 
10402     // TODO: Maybe restrict if SGPR inputs.
10403     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10404         numBitsUnsigned(MulRHS, DAG) <= 32) {
10405       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10406       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10407       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10408       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10409     }
10410 
10411     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10412       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10413       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10414       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10415       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10416     }
10417 
10418     return SDValue();
10419   }
10420 
10421   if (SDValue V = reassociateScalarOps(N, DAG)) {
10422     return V;
10423   }
10424 
10425   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10426     return SDValue();
10427 
10428   // add x, zext (setcc) => addcarry x, 0, setcc
10429   // add x, sext (setcc) => subcarry x, 0, setcc
10430   unsigned Opc = LHS.getOpcode();
10431   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10432       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10433     std::swap(RHS, LHS);
10434 
10435   Opc = RHS.getOpcode();
10436   switch (Opc) {
10437   default: break;
10438   case ISD::ZERO_EXTEND:
10439   case ISD::SIGN_EXTEND:
10440   case ISD::ANY_EXTEND: {
10441     auto Cond = RHS.getOperand(0);
10442     // If this won't be a real VOPC output, we would still need to insert an
10443     // extra instruction anyway.
10444     if (!isBoolSGPR(Cond))
10445       break;
10446     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10447     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10448     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10449     return DAG.getNode(Opc, SL, VTList, Args);
10450   }
10451   case ISD::ADDCARRY: {
10452     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10453     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10454     if (!C || C->getZExtValue() != 0) break;
10455     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10456     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10457   }
10458   }
10459   return SDValue();
10460 }
10461 
10462 SDValue SITargetLowering::performSubCombine(SDNode *N,
10463                                             DAGCombinerInfo &DCI) const {
10464   SelectionDAG &DAG = DCI.DAG;
10465   EVT VT = N->getValueType(0);
10466 
10467   if (VT != MVT::i32)
10468     return SDValue();
10469 
10470   SDLoc SL(N);
10471   SDValue LHS = N->getOperand(0);
10472   SDValue RHS = N->getOperand(1);
10473 
10474   // sub x, zext (setcc) => subcarry x, 0, setcc
10475   // sub x, sext (setcc) => addcarry x, 0, setcc
10476   unsigned Opc = RHS.getOpcode();
10477   switch (Opc) {
10478   default: break;
10479   case ISD::ZERO_EXTEND:
10480   case ISD::SIGN_EXTEND:
10481   case ISD::ANY_EXTEND: {
10482     auto Cond = RHS.getOperand(0);
10483     // If this won't be a real VOPC output, we would still need to insert an
10484     // extra instruction anyway.
10485     if (!isBoolSGPR(Cond))
10486       break;
10487     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10488     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10489     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10490     return DAG.getNode(Opc, SL, VTList, Args);
10491   }
10492   }
10493 
10494   if (LHS.getOpcode() == ISD::SUBCARRY) {
10495     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10496     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10497     if (!C || !C->isNullValue())
10498       return SDValue();
10499     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10500     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10501   }
10502   return SDValue();
10503 }
10504 
10505 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10506   DAGCombinerInfo &DCI) const {
10507 
10508   if (N->getValueType(0) != MVT::i32)
10509     return SDValue();
10510 
10511   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10512   if (!C || C->getZExtValue() != 0)
10513     return SDValue();
10514 
10515   SelectionDAG &DAG = DCI.DAG;
10516   SDValue LHS = N->getOperand(0);
10517 
10518   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10519   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10520   unsigned LHSOpc = LHS.getOpcode();
10521   unsigned Opc = N->getOpcode();
10522   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10523       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10524     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10525     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10526   }
10527   return SDValue();
10528 }
10529 
10530 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10531                                              DAGCombinerInfo &DCI) const {
10532   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10533     return SDValue();
10534 
10535   SelectionDAG &DAG = DCI.DAG;
10536   EVT VT = N->getValueType(0);
10537 
10538   SDLoc SL(N);
10539   SDValue LHS = N->getOperand(0);
10540   SDValue RHS = N->getOperand(1);
10541 
10542   // These should really be instruction patterns, but writing patterns with
10543   // source modiifiers is a pain.
10544 
10545   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10546   if (LHS.getOpcode() == ISD::FADD) {
10547     SDValue A = LHS.getOperand(0);
10548     if (A == LHS.getOperand(1)) {
10549       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10550       if (FusedOp != 0) {
10551         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10552         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10553       }
10554     }
10555   }
10556 
10557   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10558   if (RHS.getOpcode() == ISD::FADD) {
10559     SDValue A = RHS.getOperand(0);
10560     if (A == RHS.getOperand(1)) {
10561       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10562       if (FusedOp != 0) {
10563         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10564         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10565       }
10566     }
10567   }
10568 
10569   return SDValue();
10570 }
10571 
10572 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10573                                              DAGCombinerInfo &DCI) const {
10574   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10575     return SDValue();
10576 
10577   SelectionDAG &DAG = DCI.DAG;
10578   SDLoc SL(N);
10579   EVT VT = N->getValueType(0);
10580   assert(!VT.isVector());
10581 
10582   // Try to get the fneg to fold into the source modifier. This undoes generic
10583   // DAG combines and folds them into the mad.
10584   //
10585   // Only do this if we are not trying to support denormals. v_mad_f32 does
10586   // not support denormals ever.
10587   SDValue LHS = N->getOperand(0);
10588   SDValue RHS = N->getOperand(1);
10589   if (LHS.getOpcode() == ISD::FADD) {
10590     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10591     SDValue A = LHS.getOperand(0);
10592     if (A == LHS.getOperand(1)) {
10593       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10594       if (FusedOp != 0){
10595         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10596         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10597 
10598         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10599       }
10600     }
10601   }
10602 
10603   if (RHS.getOpcode() == ISD::FADD) {
10604     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10605 
10606     SDValue A = RHS.getOperand(0);
10607     if (A == RHS.getOperand(1)) {
10608       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10609       if (FusedOp != 0){
10610         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10611         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10612       }
10613     }
10614   }
10615 
10616   return SDValue();
10617 }
10618 
10619 SDValue SITargetLowering::performFMACombine(SDNode *N,
10620                                             DAGCombinerInfo &DCI) const {
10621   SelectionDAG &DAG = DCI.DAG;
10622   EVT VT = N->getValueType(0);
10623   SDLoc SL(N);
10624 
10625   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10626     return SDValue();
10627 
10628   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10629   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10630   SDValue Op1 = N->getOperand(0);
10631   SDValue Op2 = N->getOperand(1);
10632   SDValue FMA = N->getOperand(2);
10633 
10634   if (FMA.getOpcode() != ISD::FMA ||
10635       Op1.getOpcode() != ISD::FP_EXTEND ||
10636       Op2.getOpcode() != ISD::FP_EXTEND)
10637     return SDValue();
10638 
10639   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10640   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10641   // is sufficient to allow generaing fdot2.
10642   const TargetOptions &Options = DAG.getTarget().Options;
10643   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10644       (N->getFlags().hasAllowContract() &&
10645        FMA->getFlags().hasAllowContract())) {
10646     Op1 = Op1.getOperand(0);
10647     Op2 = Op2.getOperand(0);
10648     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10649         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10650       return SDValue();
10651 
10652     SDValue Vec1 = Op1.getOperand(0);
10653     SDValue Idx1 = Op1.getOperand(1);
10654     SDValue Vec2 = Op2.getOperand(0);
10655 
10656     SDValue FMAOp1 = FMA.getOperand(0);
10657     SDValue FMAOp2 = FMA.getOperand(1);
10658     SDValue FMAAcc = FMA.getOperand(2);
10659 
10660     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10661         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10662       return SDValue();
10663 
10664     FMAOp1 = FMAOp1.getOperand(0);
10665     FMAOp2 = FMAOp2.getOperand(0);
10666     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10667         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10668       return SDValue();
10669 
10670     SDValue Vec3 = FMAOp1.getOperand(0);
10671     SDValue Vec4 = FMAOp2.getOperand(0);
10672     SDValue Idx2 = FMAOp1.getOperand(1);
10673 
10674     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10675         // Idx1 and Idx2 cannot be the same.
10676         Idx1 == Idx2)
10677       return SDValue();
10678 
10679     if (Vec1 == Vec2 || Vec3 == Vec4)
10680       return SDValue();
10681 
10682     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10683       return SDValue();
10684 
10685     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10686         (Vec1 == Vec4 && Vec2 == Vec3)) {
10687       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10688                          DAG.getTargetConstant(0, SL, MVT::i1));
10689     }
10690   }
10691   return SDValue();
10692 }
10693 
10694 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10695                                               DAGCombinerInfo &DCI) const {
10696   SelectionDAG &DAG = DCI.DAG;
10697   SDLoc SL(N);
10698 
10699   SDValue LHS = N->getOperand(0);
10700   SDValue RHS = N->getOperand(1);
10701   EVT VT = LHS.getValueType();
10702   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10703 
10704   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10705   if (!CRHS) {
10706     CRHS = dyn_cast<ConstantSDNode>(LHS);
10707     if (CRHS) {
10708       std::swap(LHS, RHS);
10709       CC = getSetCCSwappedOperands(CC);
10710     }
10711   }
10712 
10713   if (CRHS) {
10714     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10715         isBoolSGPR(LHS.getOperand(0))) {
10716       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10717       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10718       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10719       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10720       if ((CRHS->isAllOnesValue() &&
10721            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10722           (CRHS->isNullValue() &&
10723            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10724         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10725                            DAG.getConstant(-1, SL, MVT::i1));
10726       if ((CRHS->isAllOnesValue() &&
10727            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10728           (CRHS->isNullValue() &&
10729            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10730         return LHS.getOperand(0);
10731     }
10732 
10733     uint64_t CRHSVal = CRHS->getZExtValue();
10734     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10735         LHS.getOpcode() == ISD::SELECT &&
10736         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10737         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10738         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10739         isBoolSGPR(LHS.getOperand(0))) {
10740       // Given CT != FT:
10741       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10742       // setcc (select cc, CT, CF), CF, ne => cc
10743       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10744       // setcc (select cc, CT, CF), CT, eq => cc
10745       uint64_t CT = LHS.getConstantOperandVal(1);
10746       uint64_t CF = LHS.getConstantOperandVal(2);
10747 
10748       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10749           (CT == CRHSVal && CC == ISD::SETNE))
10750         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10751                            DAG.getConstant(-1, SL, MVT::i1));
10752       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10753           (CT == CRHSVal && CC == ISD::SETEQ))
10754         return LHS.getOperand(0);
10755     }
10756   }
10757 
10758   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10759                                            VT != MVT::f16))
10760     return SDValue();
10761 
10762   // Match isinf/isfinite pattern
10763   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10764   // (fcmp one (fabs x), inf) -> (fp_class x,
10765   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10766   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10767     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10768     if (!CRHS)
10769       return SDValue();
10770 
10771     const APFloat &APF = CRHS->getValueAPF();
10772     if (APF.isInfinity() && !APF.isNegative()) {
10773       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10774                                  SIInstrFlags::N_INFINITY;
10775       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10776                                     SIInstrFlags::P_ZERO |
10777                                     SIInstrFlags::N_NORMAL |
10778                                     SIInstrFlags::P_NORMAL |
10779                                     SIInstrFlags::N_SUBNORMAL |
10780                                     SIInstrFlags::P_SUBNORMAL;
10781       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10782       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10783                          DAG.getConstant(Mask, SL, MVT::i32));
10784     }
10785   }
10786 
10787   return SDValue();
10788 }
10789 
10790 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10791                                                      DAGCombinerInfo &DCI) const {
10792   SelectionDAG &DAG = DCI.DAG;
10793   SDLoc SL(N);
10794   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10795 
10796   SDValue Src = N->getOperand(0);
10797   SDValue Shift = N->getOperand(0);
10798 
10799   // TODO: Extend type shouldn't matter (assuming legal types).
10800   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10801     Shift = Shift.getOperand(0);
10802 
10803   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10804     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10805     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10806     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10807     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10808     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10809     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10810       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10811                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10812 
10813       unsigned ShiftOffset = 8 * Offset;
10814       if (Shift.getOpcode() == ISD::SHL)
10815         ShiftOffset -= C->getZExtValue();
10816       else
10817         ShiftOffset += C->getZExtValue();
10818 
10819       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10820         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10821                            MVT::f32, Shift);
10822       }
10823     }
10824   }
10825 
10826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10827   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10828   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10829     // We simplified Src. If this node is not dead, visit it again so it is
10830     // folded properly.
10831     if (N->getOpcode() != ISD::DELETED_NODE)
10832       DCI.AddToWorklist(N);
10833     return SDValue(N, 0);
10834   }
10835 
10836   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10837   if (SDValue DemandedSrc =
10838           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10839     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10840 
10841   return SDValue();
10842 }
10843 
10844 SDValue SITargetLowering::performClampCombine(SDNode *N,
10845                                               DAGCombinerInfo &DCI) const {
10846   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10847   if (!CSrc)
10848     return SDValue();
10849 
10850   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10851   const APFloat &F = CSrc->getValueAPF();
10852   APFloat Zero = APFloat::getZero(F.getSemantics());
10853   if (F < Zero ||
10854       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10855     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10856   }
10857 
10858   APFloat One(F.getSemantics(), "1.0");
10859   if (F > One)
10860     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10861 
10862   return SDValue(CSrc, 0);
10863 }
10864 
10865 
10866 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10867                                             DAGCombinerInfo &DCI) const {
10868   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10869     return SDValue();
10870   switch (N->getOpcode()) {
10871   case ISD::ADD:
10872     return performAddCombine(N, DCI);
10873   case ISD::SUB:
10874     return performSubCombine(N, DCI);
10875   case ISD::ADDCARRY:
10876   case ISD::SUBCARRY:
10877     return performAddCarrySubCarryCombine(N, DCI);
10878   case ISD::FADD:
10879     return performFAddCombine(N, DCI);
10880   case ISD::FSUB:
10881     return performFSubCombine(N, DCI);
10882   case ISD::SETCC:
10883     return performSetCCCombine(N, DCI);
10884   case ISD::FMAXNUM:
10885   case ISD::FMINNUM:
10886   case ISD::FMAXNUM_IEEE:
10887   case ISD::FMINNUM_IEEE:
10888   case ISD::SMAX:
10889   case ISD::SMIN:
10890   case ISD::UMAX:
10891   case ISD::UMIN:
10892   case AMDGPUISD::FMIN_LEGACY:
10893   case AMDGPUISD::FMAX_LEGACY:
10894     return performMinMaxCombine(N, DCI);
10895   case ISD::FMA:
10896     return performFMACombine(N, DCI);
10897   case ISD::AND:
10898     return performAndCombine(N, DCI);
10899   case ISD::OR:
10900     return performOrCombine(N, DCI);
10901   case ISD::XOR:
10902     return performXorCombine(N, DCI);
10903   case ISD::ZERO_EXTEND:
10904     return performZeroExtendCombine(N, DCI);
10905   case ISD::SIGN_EXTEND_INREG:
10906     return performSignExtendInRegCombine(N , DCI);
10907   case AMDGPUISD::FP_CLASS:
10908     return performClassCombine(N, DCI);
10909   case ISD::FCANONICALIZE:
10910     return performFCanonicalizeCombine(N, DCI);
10911   case AMDGPUISD::RCP:
10912     return performRcpCombine(N, DCI);
10913   case AMDGPUISD::FRACT:
10914   case AMDGPUISD::RSQ:
10915   case AMDGPUISD::RCP_LEGACY:
10916   case AMDGPUISD::RCP_IFLAG:
10917   case AMDGPUISD::RSQ_CLAMP:
10918   case AMDGPUISD::LDEXP: {
10919     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10920     SDValue Src = N->getOperand(0);
10921     if (Src.isUndef())
10922       return Src;
10923     break;
10924   }
10925   case ISD::SINT_TO_FP:
10926   case ISD::UINT_TO_FP:
10927     return performUCharToFloatCombine(N, DCI);
10928   case AMDGPUISD::CVT_F32_UBYTE0:
10929   case AMDGPUISD::CVT_F32_UBYTE1:
10930   case AMDGPUISD::CVT_F32_UBYTE2:
10931   case AMDGPUISD::CVT_F32_UBYTE3:
10932     return performCvtF32UByteNCombine(N, DCI);
10933   case AMDGPUISD::FMED3:
10934     return performFMed3Combine(N, DCI);
10935   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10936     return performCvtPkRTZCombine(N, DCI);
10937   case AMDGPUISD::CLAMP:
10938     return performClampCombine(N, DCI);
10939   case ISD::SCALAR_TO_VECTOR: {
10940     SelectionDAG &DAG = DCI.DAG;
10941     EVT VT = N->getValueType(0);
10942 
10943     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10944     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10945       SDLoc SL(N);
10946       SDValue Src = N->getOperand(0);
10947       EVT EltVT = Src.getValueType();
10948       if (EltVT == MVT::f16)
10949         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10950 
10951       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10952       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10953     }
10954 
10955     break;
10956   }
10957   case ISD::EXTRACT_VECTOR_ELT:
10958     return performExtractVectorEltCombine(N, DCI);
10959   case ISD::INSERT_VECTOR_ELT:
10960     return performInsertVectorEltCombine(N, DCI);
10961   case ISD::LOAD: {
10962     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10963       return Widended;
10964     LLVM_FALLTHROUGH;
10965   }
10966   default: {
10967     if (!DCI.isBeforeLegalize()) {
10968       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10969         return performMemSDNodeCombine(MemNode, DCI);
10970     }
10971 
10972     break;
10973   }
10974   }
10975 
10976   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10977 }
10978 
10979 /// Helper function for adjustWritemask
10980 static unsigned SubIdx2Lane(unsigned Idx) {
10981   switch (Idx) {
10982   default: return ~0u;
10983   case AMDGPU::sub0: return 0;
10984   case AMDGPU::sub1: return 1;
10985   case AMDGPU::sub2: return 2;
10986   case AMDGPU::sub3: return 3;
10987   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10988   }
10989 }
10990 
10991 /// Adjust the writemask of MIMG instructions
10992 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10993                                           SelectionDAG &DAG) const {
10994   unsigned Opcode = Node->getMachineOpcode();
10995 
10996   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10997   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10998   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10999     return Node; // not implemented for D16
11000 
11001   SDNode *Users[5] = { nullptr };
11002   unsigned Lane = 0;
11003   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11004   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11005   unsigned NewDmask = 0;
11006   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11007   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11008   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11009                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11010   unsigned TFCLane = 0;
11011   bool HasChain = Node->getNumValues() > 1;
11012 
11013   if (OldDmask == 0) {
11014     // These are folded out, but on the chance it happens don't assert.
11015     return Node;
11016   }
11017 
11018   unsigned OldBitsSet = countPopulation(OldDmask);
11019   // Work out which is the TFE/LWE lane if that is enabled.
11020   if (UsesTFC) {
11021     TFCLane = OldBitsSet;
11022   }
11023 
11024   // Try to figure out the used register components
11025   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11026        I != E; ++I) {
11027 
11028     // Don't look at users of the chain.
11029     if (I.getUse().getResNo() != 0)
11030       continue;
11031 
11032     // Abort if we can't understand the usage
11033     if (!I->isMachineOpcode() ||
11034         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11035       return Node;
11036 
11037     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11038     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11039     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11040     // set, etc.
11041     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11042     if (Lane == ~0u)
11043       return Node;
11044 
11045     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11046     if (UsesTFC && Lane == TFCLane) {
11047       Users[Lane] = *I;
11048     } else {
11049       // Set which texture component corresponds to the lane.
11050       unsigned Comp;
11051       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11052         Comp = countTrailingZeros(Dmask);
11053         Dmask &= ~(1 << Comp);
11054       }
11055 
11056       // Abort if we have more than one user per component.
11057       if (Users[Lane])
11058         return Node;
11059 
11060       Users[Lane] = *I;
11061       NewDmask |= 1 << Comp;
11062     }
11063   }
11064 
11065   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11066   bool NoChannels = !NewDmask;
11067   if (NoChannels) {
11068     if (!UsesTFC) {
11069       // No uses of the result and not using TFC. Then do nothing.
11070       return Node;
11071     }
11072     // If the original dmask has one channel - then nothing to do
11073     if (OldBitsSet == 1)
11074       return Node;
11075     // Use an arbitrary dmask - required for the instruction to work
11076     NewDmask = 1;
11077   }
11078   // Abort if there's no change
11079   if (NewDmask == OldDmask)
11080     return Node;
11081 
11082   unsigned BitsSet = countPopulation(NewDmask);
11083 
11084   // Check for TFE or LWE - increase the number of channels by one to account
11085   // for the extra return value
11086   // This will need adjustment for D16 if this is also included in
11087   // adjustWriteMask (this function) but at present D16 are excluded.
11088   unsigned NewChannels = BitsSet + UsesTFC;
11089 
11090   int NewOpcode =
11091       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11092   assert(NewOpcode != -1 &&
11093          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11094          "failed to find equivalent MIMG op");
11095 
11096   // Adjust the writemask in the node
11097   SmallVector<SDValue, 12> Ops;
11098   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11099   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11100   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11101 
11102   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11103 
11104   MVT ResultVT = NewChannels == 1 ?
11105     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11106                            NewChannels == 5 ? 8 : NewChannels);
11107   SDVTList NewVTList = HasChain ?
11108     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11109 
11110 
11111   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11112                                               NewVTList, Ops);
11113 
11114   if (HasChain) {
11115     // Update chain.
11116     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11117     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11118   }
11119 
11120   if (NewChannels == 1) {
11121     assert(Node->hasNUsesOfValue(1, 0));
11122     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11123                                       SDLoc(Node), Users[Lane]->getValueType(0),
11124                                       SDValue(NewNode, 0));
11125     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11126     return nullptr;
11127   }
11128 
11129   // Update the users of the node with the new indices
11130   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11131     SDNode *User = Users[i];
11132     if (!User) {
11133       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11134       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11135       if (i || !NoChannels)
11136         continue;
11137     } else {
11138       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11139       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11140     }
11141 
11142     switch (Idx) {
11143     default: break;
11144     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11145     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11146     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11147     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11148     }
11149   }
11150 
11151   DAG.RemoveDeadNode(Node);
11152   return nullptr;
11153 }
11154 
11155 static bool isFrameIndexOp(SDValue Op) {
11156   if (Op.getOpcode() == ISD::AssertZext)
11157     Op = Op.getOperand(0);
11158 
11159   return isa<FrameIndexSDNode>(Op);
11160 }
11161 
11162 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11163 /// with frame index operands.
11164 /// LLVM assumes that inputs are to these instructions are registers.
11165 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11166                                                         SelectionDAG &DAG) const {
11167   if (Node->getOpcode() == ISD::CopyToReg) {
11168     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11169     SDValue SrcVal = Node->getOperand(2);
11170 
11171     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11172     // to try understanding copies to physical registers.
11173     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11174       SDLoc SL(Node);
11175       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11176       SDValue VReg = DAG.getRegister(
11177         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11178 
11179       SDNode *Glued = Node->getGluedNode();
11180       SDValue ToVReg
11181         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11182                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11183       SDValue ToResultReg
11184         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11185                            VReg, ToVReg.getValue(1));
11186       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11187       DAG.RemoveDeadNode(Node);
11188       return ToResultReg.getNode();
11189     }
11190   }
11191 
11192   SmallVector<SDValue, 8> Ops;
11193   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11194     if (!isFrameIndexOp(Node->getOperand(i))) {
11195       Ops.push_back(Node->getOperand(i));
11196       continue;
11197     }
11198 
11199     SDLoc DL(Node);
11200     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11201                                      Node->getOperand(i).getValueType(),
11202                                      Node->getOperand(i)), 0));
11203   }
11204 
11205   return DAG.UpdateNodeOperands(Node, Ops);
11206 }
11207 
11208 /// Fold the instructions after selecting them.
11209 /// Returns null if users were already updated.
11210 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11211                                           SelectionDAG &DAG) const {
11212   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11213   unsigned Opcode = Node->getMachineOpcode();
11214 
11215   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11216       !TII->isGather4(Opcode) &&
11217       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11218     return adjustWritemask(Node, DAG);
11219   }
11220 
11221   if (Opcode == AMDGPU::INSERT_SUBREG ||
11222       Opcode == AMDGPU::REG_SEQUENCE) {
11223     legalizeTargetIndependentNode(Node, DAG);
11224     return Node;
11225   }
11226 
11227   switch (Opcode) {
11228   case AMDGPU::V_DIV_SCALE_F32_e64:
11229   case AMDGPU::V_DIV_SCALE_F64_e64: {
11230     // Satisfy the operand register constraint when one of the inputs is
11231     // undefined. Ordinarily each undef value will have its own implicit_def of
11232     // a vreg, so force these to use a single register.
11233     SDValue Src0 = Node->getOperand(1);
11234     SDValue Src1 = Node->getOperand(3);
11235     SDValue Src2 = Node->getOperand(5);
11236 
11237     if ((Src0.isMachineOpcode() &&
11238          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11239         (Src0 == Src1 || Src0 == Src2))
11240       break;
11241 
11242     MVT VT = Src0.getValueType().getSimpleVT();
11243     const TargetRegisterClass *RC =
11244         getRegClassFor(VT, Src0.getNode()->isDivergent());
11245 
11246     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11247     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11248 
11249     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11250                                       UndefReg, Src0, SDValue());
11251 
11252     // src0 must be the same register as src1 or src2, even if the value is
11253     // undefined, so make sure we don't violate this constraint.
11254     if (Src0.isMachineOpcode() &&
11255         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11256       if (Src1.isMachineOpcode() &&
11257           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11258         Src0 = Src1;
11259       else if (Src2.isMachineOpcode() &&
11260                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11261         Src0 = Src2;
11262       else {
11263         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11264         Src0 = UndefReg;
11265         Src1 = UndefReg;
11266       }
11267     } else
11268       break;
11269 
11270     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11271     Ops[1] = Src0;
11272     Ops[3] = Src1;
11273     Ops[5] = Src2;
11274     Ops.push_back(ImpDef.getValue(1));
11275     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11276   }
11277   default:
11278     break;
11279   }
11280 
11281   return Node;
11282 }
11283 
11284 // Any MIMG instructions that use tfe or lwe require an initialization of the
11285 // result register that will be written in the case of a memory access failure.
11286 // The required code is also added to tie this init code to the result of the
11287 // img instruction.
11288 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11289   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11290   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11291   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11292   MachineBasicBlock &MBB = *MI.getParent();
11293 
11294   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11295   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11296   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11297 
11298   if (!TFE && !LWE) // intersect_ray
11299     return;
11300 
11301   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11302   unsigned LWEVal = LWE->getImm();
11303   unsigned D16Val = D16 ? D16->getImm() : 0;
11304 
11305   if (!TFEVal && !LWEVal)
11306     return;
11307 
11308   // At least one of TFE or LWE are non-zero
11309   // We have to insert a suitable initialization of the result value and
11310   // tie this to the dest of the image instruction.
11311 
11312   const DebugLoc &DL = MI.getDebugLoc();
11313 
11314   int DstIdx =
11315       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11316 
11317   // Calculate which dword we have to initialize to 0.
11318   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11319 
11320   // check that dmask operand is found.
11321   assert(MO_Dmask && "Expected dmask operand in instruction");
11322 
11323   unsigned dmask = MO_Dmask->getImm();
11324   // Determine the number of active lanes taking into account the
11325   // Gather4 special case
11326   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11327 
11328   bool Packed = !Subtarget->hasUnpackedD16VMem();
11329 
11330   unsigned InitIdx =
11331       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11332 
11333   // Abandon attempt if the dst size isn't large enough
11334   // - this is in fact an error but this is picked up elsewhere and
11335   // reported correctly.
11336   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11337   if (DstSize < InitIdx)
11338     return;
11339 
11340   // Create a register for the intialization value.
11341   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11342   unsigned NewDst = 0; // Final initialized value will be in here
11343 
11344   // If PRTStrictNull feature is enabled (the default) then initialize
11345   // all the result registers to 0, otherwise just the error indication
11346   // register (VGPRn+1)
11347   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11348   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11349 
11350   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11351   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11352     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11353     // Initialize dword
11354     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11355     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11356       .addImm(0);
11357     // Insert into the super-reg
11358     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11359       .addReg(PrevDst)
11360       .addReg(SubReg)
11361       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11362 
11363     PrevDst = NewDst;
11364   }
11365 
11366   // Add as an implicit operand
11367   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11368 
11369   // Tie the just added implicit operand to the dst
11370   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11371 }
11372 
11373 /// Assign the register class depending on the number of
11374 /// bits set in the writemask
11375 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11376                                                      SDNode *Node) const {
11377   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11378 
11379   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11380 
11381   if (TII->isVOP3(MI.getOpcode())) {
11382     // Make sure constant bus requirements are respected.
11383     TII->legalizeOperandsVOP3(MRI, MI);
11384 
11385     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11386     // This saves a chain-copy of registers and better ballance register
11387     // use between vgpr and agpr as agpr tuples tend to be big.
11388     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11389       unsigned Opc = MI.getOpcode();
11390       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11391       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11392                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11393         if (I == -1)
11394           break;
11395         MachineOperand &Op = MI.getOperand(I);
11396         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11397              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11398             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11399           continue;
11400         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11401         if (!Src || !Src->isCopy() ||
11402             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11403           continue;
11404         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11405         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11406         // All uses of agpr64 and agpr32 can also accept vgpr except for
11407         // v_accvgpr_read, but we do not produce agpr reads during selection,
11408         // so no use checks are needed.
11409         MRI.setRegClass(Op.getReg(), NewRC);
11410       }
11411     }
11412 
11413     return;
11414   }
11415 
11416   // Replace unused atomics with the no return version.
11417   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11418   if (NoRetAtomicOp != -1) {
11419     if (!Node->hasAnyUseOfValue(0)) {
11420       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11421                                                AMDGPU::OpName::cpol);
11422       if (CPolIdx != -1) {
11423         MachineOperand &CPol = MI.getOperand(CPolIdx);
11424         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11425       }
11426       MI.RemoveOperand(0);
11427       MI.setDesc(TII->get(NoRetAtomicOp));
11428       return;
11429     }
11430 
11431     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11432     // instruction, because the return type of these instructions is a vec2 of
11433     // the memory type, so it can be tied to the input operand.
11434     // This means these instructions always have a use, so we need to add a
11435     // special case to check if the atomic has only one extract_subreg use,
11436     // which itself has no uses.
11437     if ((Node->hasNUsesOfValue(1, 0) &&
11438          Node->use_begin()->isMachineOpcode() &&
11439          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11440          !Node->use_begin()->hasAnyUseOfValue(0))) {
11441       Register Def = MI.getOperand(0).getReg();
11442 
11443       // Change this into a noret atomic.
11444       MI.setDesc(TII->get(NoRetAtomicOp));
11445       MI.RemoveOperand(0);
11446 
11447       // If we only remove the def operand from the atomic instruction, the
11448       // extract_subreg will be left with a use of a vreg without a def.
11449       // So we need to insert an implicit_def to avoid machine verifier
11450       // errors.
11451       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11452               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11453     }
11454     return;
11455   }
11456 
11457   if (TII->isMIMG(MI) && !MI.mayStore())
11458     AddIMGInit(MI);
11459 }
11460 
11461 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11462                               uint64_t Val) {
11463   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11464   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11465 }
11466 
11467 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11468                                                 const SDLoc &DL,
11469                                                 SDValue Ptr) const {
11470   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11471 
11472   // Build the half of the subregister with the constants before building the
11473   // full 128-bit register. If we are building multiple resource descriptors,
11474   // this will allow CSEing of the 2-component register.
11475   const SDValue Ops0[] = {
11476     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11477     buildSMovImm32(DAG, DL, 0),
11478     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11479     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11480     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11481   };
11482 
11483   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11484                                                 MVT::v2i32, Ops0), 0);
11485 
11486   // Combine the constants and the pointer.
11487   const SDValue Ops1[] = {
11488     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11489     Ptr,
11490     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11491     SubRegHi,
11492     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11493   };
11494 
11495   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11496 }
11497 
11498 /// Return a resource descriptor with the 'Add TID' bit enabled
11499 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11500 ///        of the resource descriptor) to create an offset, which is added to
11501 ///        the resource pointer.
11502 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11503                                            SDValue Ptr, uint32_t RsrcDword1,
11504                                            uint64_t RsrcDword2And3) const {
11505   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11506   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11507   if (RsrcDword1) {
11508     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11509                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11510                     0);
11511   }
11512 
11513   SDValue DataLo = buildSMovImm32(DAG, DL,
11514                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11515   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11516 
11517   const SDValue Ops[] = {
11518     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11519     PtrLo,
11520     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11521     PtrHi,
11522     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11523     DataLo,
11524     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11525     DataHi,
11526     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11527   };
11528 
11529   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11530 }
11531 
11532 //===----------------------------------------------------------------------===//
11533 //                         SI Inline Assembly Support
11534 //===----------------------------------------------------------------------===//
11535 
11536 std::pair<unsigned, const TargetRegisterClass *>
11537 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11538                                                StringRef Constraint,
11539                                                MVT VT) const {
11540   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11541 
11542   const TargetRegisterClass *RC = nullptr;
11543   if (Constraint.size() == 1) {
11544     const unsigned BitWidth = VT.getSizeInBits();
11545     switch (Constraint[0]) {
11546     default:
11547       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11548     case 's':
11549     case 'r':
11550       switch (BitWidth) {
11551       case 16:
11552         RC = &AMDGPU::SReg_32RegClass;
11553         break;
11554       case 64:
11555         RC = &AMDGPU::SGPR_64RegClass;
11556         break;
11557       default:
11558         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11559         if (!RC)
11560           return std::make_pair(0U, nullptr);
11561         break;
11562       }
11563       break;
11564     case 'v':
11565       switch (BitWidth) {
11566       case 16:
11567         RC = &AMDGPU::VGPR_32RegClass;
11568         break;
11569       default:
11570         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11571         if (!RC)
11572           return std::make_pair(0U, nullptr);
11573         break;
11574       }
11575       break;
11576     case 'a':
11577       if (!Subtarget->hasMAIInsts())
11578         break;
11579       switch (BitWidth) {
11580       case 16:
11581         RC = &AMDGPU::AGPR_32RegClass;
11582         break;
11583       default:
11584         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11585         if (!RC)
11586           return std::make_pair(0U, nullptr);
11587         break;
11588       }
11589       break;
11590     }
11591     // We actually support i128, i16 and f16 as inline parameters
11592     // even if they are not reported as legal
11593     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11594                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11595       return std::make_pair(0U, RC);
11596   }
11597 
11598   if (Constraint.size() > 1) {
11599     if (Constraint[1] == 'v') {
11600       RC = &AMDGPU::VGPR_32RegClass;
11601     } else if (Constraint[1] == 's') {
11602       RC = &AMDGPU::SGPR_32RegClass;
11603     } else if (Constraint[1] == 'a') {
11604       RC = &AMDGPU::AGPR_32RegClass;
11605     }
11606 
11607     if (RC) {
11608       uint32_t Idx;
11609       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11610       if (!Failed && Idx < RC->getNumRegs())
11611         return std::make_pair(RC->getRegister(Idx), RC);
11612     }
11613   }
11614 
11615   // FIXME: Returns VS_32 for physical SGPR constraints
11616   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11617 }
11618 
11619 static bool isImmConstraint(StringRef Constraint) {
11620   if (Constraint.size() == 1) {
11621     switch (Constraint[0]) {
11622     default: break;
11623     case 'I':
11624     case 'J':
11625     case 'A':
11626     case 'B':
11627     case 'C':
11628       return true;
11629     }
11630   } else if (Constraint == "DA" ||
11631              Constraint == "DB") {
11632     return true;
11633   }
11634   return false;
11635 }
11636 
11637 SITargetLowering::ConstraintType
11638 SITargetLowering::getConstraintType(StringRef Constraint) const {
11639   if (Constraint.size() == 1) {
11640     switch (Constraint[0]) {
11641     default: break;
11642     case 's':
11643     case 'v':
11644     case 'a':
11645       return C_RegisterClass;
11646     }
11647   }
11648   if (isImmConstraint(Constraint)) {
11649     return C_Other;
11650   }
11651   return TargetLowering::getConstraintType(Constraint);
11652 }
11653 
11654 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11655   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11656     Val = Val & maskTrailingOnes<uint64_t>(Size);
11657   }
11658   return Val;
11659 }
11660 
11661 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11662                                                     std::string &Constraint,
11663                                                     std::vector<SDValue> &Ops,
11664                                                     SelectionDAG &DAG) const {
11665   if (isImmConstraint(Constraint)) {
11666     uint64_t Val;
11667     if (getAsmOperandConstVal(Op, Val) &&
11668         checkAsmConstraintVal(Op, Constraint, Val)) {
11669       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11670       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11671     }
11672   } else {
11673     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11674   }
11675 }
11676 
11677 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11678   unsigned Size = Op.getScalarValueSizeInBits();
11679   if (Size > 64)
11680     return false;
11681 
11682   if (Size == 16 && !Subtarget->has16BitInsts())
11683     return false;
11684 
11685   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11686     Val = C->getSExtValue();
11687     return true;
11688   }
11689   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11690     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11691     return true;
11692   }
11693   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11694     if (Size != 16 || Op.getNumOperands() != 2)
11695       return false;
11696     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11697       return false;
11698     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11699       Val = C->getSExtValue();
11700       return true;
11701     }
11702     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11703       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11704       return true;
11705     }
11706   }
11707 
11708   return false;
11709 }
11710 
11711 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11712                                              const std::string &Constraint,
11713                                              uint64_t Val) const {
11714   if (Constraint.size() == 1) {
11715     switch (Constraint[0]) {
11716     case 'I':
11717       return AMDGPU::isInlinableIntLiteral(Val);
11718     case 'J':
11719       return isInt<16>(Val);
11720     case 'A':
11721       return checkAsmConstraintValA(Op, Val);
11722     case 'B':
11723       return isInt<32>(Val);
11724     case 'C':
11725       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11726              AMDGPU::isInlinableIntLiteral(Val);
11727     default:
11728       break;
11729     }
11730   } else if (Constraint.size() == 2) {
11731     if (Constraint == "DA") {
11732       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11733       int64_t LoBits = static_cast<int32_t>(Val);
11734       return checkAsmConstraintValA(Op, HiBits, 32) &&
11735              checkAsmConstraintValA(Op, LoBits, 32);
11736     }
11737     if (Constraint == "DB") {
11738       return true;
11739     }
11740   }
11741   llvm_unreachable("Invalid asm constraint");
11742 }
11743 
11744 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11745                                               uint64_t Val,
11746                                               unsigned MaxSize) const {
11747   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11748   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11749   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11750       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11751       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11752     return true;
11753   }
11754   return false;
11755 }
11756 
11757 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11758   switch (UnalignedClassID) {
11759   case AMDGPU::VReg_64RegClassID:
11760     return AMDGPU::VReg_64_Align2RegClassID;
11761   case AMDGPU::VReg_96RegClassID:
11762     return AMDGPU::VReg_96_Align2RegClassID;
11763   case AMDGPU::VReg_128RegClassID:
11764     return AMDGPU::VReg_128_Align2RegClassID;
11765   case AMDGPU::VReg_160RegClassID:
11766     return AMDGPU::VReg_160_Align2RegClassID;
11767   case AMDGPU::VReg_192RegClassID:
11768     return AMDGPU::VReg_192_Align2RegClassID;
11769   case AMDGPU::VReg_256RegClassID:
11770     return AMDGPU::VReg_256_Align2RegClassID;
11771   case AMDGPU::VReg_512RegClassID:
11772     return AMDGPU::VReg_512_Align2RegClassID;
11773   case AMDGPU::VReg_1024RegClassID:
11774     return AMDGPU::VReg_1024_Align2RegClassID;
11775   case AMDGPU::AReg_64RegClassID:
11776     return AMDGPU::AReg_64_Align2RegClassID;
11777   case AMDGPU::AReg_96RegClassID:
11778     return AMDGPU::AReg_96_Align2RegClassID;
11779   case AMDGPU::AReg_128RegClassID:
11780     return AMDGPU::AReg_128_Align2RegClassID;
11781   case AMDGPU::AReg_160RegClassID:
11782     return AMDGPU::AReg_160_Align2RegClassID;
11783   case AMDGPU::AReg_192RegClassID:
11784     return AMDGPU::AReg_192_Align2RegClassID;
11785   case AMDGPU::AReg_256RegClassID:
11786     return AMDGPU::AReg_256_Align2RegClassID;
11787   case AMDGPU::AReg_512RegClassID:
11788     return AMDGPU::AReg_512_Align2RegClassID;
11789   case AMDGPU::AReg_1024RegClassID:
11790     return AMDGPU::AReg_1024_Align2RegClassID;
11791   default:
11792     return -1;
11793   }
11794 }
11795 
11796 // Figure out which registers should be reserved for stack access. Only after
11797 // the function is legalized do we know all of the non-spill stack objects or if
11798 // calls are present.
11799 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11800   MachineRegisterInfo &MRI = MF.getRegInfo();
11801   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11802   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11803   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11804   const SIInstrInfo *TII = ST.getInstrInfo();
11805 
11806   if (Info->isEntryFunction()) {
11807     // Callable functions have fixed registers used for stack access.
11808     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11809   }
11810 
11811   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11812                              Info->getStackPtrOffsetReg()));
11813   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11814     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11815 
11816   // We need to worry about replacing the default register with itself in case
11817   // of MIR testcases missing the MFI.
11818   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11819     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11820 
11821   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11822     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11823 
11824   Info->limitOccupancy(MF);
11825 
11826   if (ST.isWave32() && !MF.empty()) {
11827     for (auto &MBB : MF) {
11828       for (auto &MI : MBB) {
11829         TII->fixImplicitOperands(MI);
11830       }
11831     }
11832   }
11833 
11834   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11835   // classes if required. Ideally the register class constraints would differ
11836   // per-subtarget, but there's no easy way to achieve that right now. This is
11837   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11838   // from using them as the register class for legal types.
11839   if (ST.needsAlignedVGPRs()) {
11840     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11841       const Register Reg = Register::index2VirtReg(I);
11842       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11843       if (!RC)
11844         continue;
11845       int NewClassID = getAlignedAGPRClassID(RC->getID());
11846       if (NewClassID != -1)
11847         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11848     }
11849   }
11850 
11851   TargetLoweringBase::finalizeLowering(MF);
11852 
11853   // Allocate a VGPR for future SGPR Spill if
11854   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11855   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11856   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11857       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11858     Info->reserveVGPRforSGPRSpills(MF);
11859 }
11860 
11861 void SITargetLowering::computeKnownBitsForFrameIndex(
11862   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11863   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11864 
11865   // Set the high bits to zero based on the maximum allowed scratch size per
11866   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11867   // calculation won't overflow, so assume the sign bit is never set.
11868   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11869 }
11870 
11871 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11872                                    KnownBits &Known, unsigned Dim) {
11873   unsigned MaxValue =
11874       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11875   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11876 }
11877 
11878 void SITargetLowering::computeKnownBitsForTargetInstr(
11879     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11880     const MachineRegisterInfo &MRI, unsigned Depth) const {
11881   const MachineInstr *MI = MRI.getVRegDef(R);
11882   switch (MI->getOpcode()) {
11883   case AMDGPU::G_INTRINSIC: {
11884     switch (MI->getIntrinsicID()) {
11885     case Intrinsic::amdgcn_workitem_id_x:
11886       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11887       break;
11888     case Intrinsic::amdgcn_workitem_id_y:
11889       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11890       break;
11891     case Intrinsic::amdgcn_workitem_id_z:
11892       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11893       break;
11894     case Intrinsic::amdgcn_mbcnt_lo:
11895     case Intrinsic::amdgcn_mbcnt_hi: {
11896       // These return at most the wavefront size - 1.
11897       unsigned Size = MRI.getType(R).getSizeInBits();
11898       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11899       break;
11900     }
11901     case Intrinsic::amdgcn_groupstaticsize: {
11902       // We can report everything over the maximum size as 0. We can't report
11903       // based on the actual size because we don't know if it's accurate or not
11904       // at any given point.
11905       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11906       break;
11907     }
11908     }
11909     break;
11910   }
11911   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11912     Known.Zero.setHighBits(24);
11913     break;
11914   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11915     Known.Zero.setHighBits(16);
11916     break;
11917   }
11918 }
11919 
11920 Align SITargetLowering::computeKnownAlignForTargetInstr(
11921   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11922   unsigned Depth) const {
11923   const MachineInstr *MI = MRI.getVRegDef(R);
11924   switch (MI->getOpcode()) {
11925   case AMDGPU::G_INTRINSIC:
11926   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11927     // FIXME: Can this move to generic code? What about the case where the call
11928     // site specifies a lower alignment?
11929     Intrinsic::ID IID = MI->getIntrinsicID();
11930     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11931     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11932     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11933       return *RetAlign;
11934     return Align(1);
11935   }
11936   default:
11937     return Align(1);
11938   }
11939 }
11940 
11941 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11942   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11943   const Align CacheLineAlign = Align(64);
11944 
11945   // Pre-GFX10 target did not benefit from loop alignment
11946   if (!ML || DisableLoopAlignment ||
11947       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11948       getSubtarget()->hasInstFwdPrefetchBug())
11949     return PrefAlign;
11950 
11951   // On GFX10 I$ is 4 x 64 bytes cache lines.
11952   // By default prefetcher keeps one cache line behind and reads two ahead.
11953   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11954   // behind and one ahead.
11955   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11956   // If loop fits 64 bytes it always spans no more than two cache lines and
11957   // does not need an alignment.
11958   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11959   // Else if loop is less or equal 192 bytes we need two lines behind.
11960 
11961   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11962   const MachineBasicBlock *Header = ML->getHeader();
11963   if (Header->getAlignment() != PrefAlign)
11964     return Header->getAlignment(); // Already processed.
11965 
11966   unsigned LoopSize = 0;
11967   for (const MachineBasicBlock *MBB : ML->blocks()) {
11968     // If inner loop block is aligned assume in average half of the alignment
11969     // size to be added as nops.
11970     if (MBB != Header)
11971       LoopSize += MBB->getAlignment().value() / 2;
11972 
11973     for (const MachineInstr &MI : *MBB) {
11974       LoopSize += TII->getInstSizeInBytes(MI);
11975       if (LoopSize > 192)
11976         return PrefAlign;
11977     }
11978   }
11979 
11980   if (LoopSize <= 64)
11981     return PrefAlign;
11982 
11983   if (LoopSize <= 128)
11984     return CacheLineAlign;
11985 
11986   // If any of parent loops is surrounded by prefetch instructions do not
11987   // insert new for inner loop, which would reset parent's settings.
11988   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11989     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11990       auto I = Exit->getFirstNonDebugInstr();
11991       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11992         return CacheLineAlign;
11993     }
11994   }
11995 
11996   MachineBasicBlock *Pre = ML->getLoopPreheader();
11997   MachineBasicBlock *Exit = ML->getExitBlock();
11998 
11999   if (Pre && Exit) {
12000     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12001             TII->get(AMDGPU::S_INST_PREFETCH))
12002       .addImm(1); // prefetch 2 lines behind PC
12003 
12004     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12005             TII->get(AMDGPU::S_INST_PREFETCH))
12006       .addImm(2); // prefetch 1 line behind PC
12007   }
12008 
12009   return CacheLineAlign;
12010 }
12011 
12012 LLVM_ATTRIBUTE_UNUSED
12013 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12014   assert(N->getOpcode() == ISD::CopyFromReg);
12015   do {
12016     // Follow the chain until we find an INLINEASM node.
12017     N = N->getOperand(0).getNode();
12018     if (N->getOpcode() == ISD::INLINEASM ||
12019         N->getOpcode() == ISD::INLINEASM_BR)
12020       return true;
12021   } while (N->getOpcode() == ISD::CopyFromReg);
12022   return false;
12023 }
12024 
12025 bool SITargetLowering::isSDNodeSourceOfDivergence(
12026     const SDNode *N, FunctionLoweringInfo *FLI,
12027     LegacyDivergenceAnalysis *KDA) const {
12028   switch (N->getOpcode()) {
12029   case ISD::CopyFromReg: {
12030     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12031     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12032     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12033     Register Reg = R->getReg();
12034 
12035     // FIXME: Why does this need to consider isLiveIn?
12036     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12037       return !TRI->isSGPRReg(MRI, Reg);
12038 
12039     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12040       return KDA->isDivergent(V);
12041 
12042     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12043     return !TRI->isSGPRReg(MRI, Reg);
12044   }
12045   case ISD::LOAD: {
12046     const LoadSDNode *L = cast<LoadSDNode>(N);
12047     unsigned AS = L->getAddressSpace();
12048     // A flat load may access private memory.
12049     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12050   }
12051   case ISD::CALLSEQ_END:
12052     return true;
12053   case ISD::INTRINSIC_WO_CHAIN:
12054     return AMDGPU::isIntrinsicSourceOfDivergence(
12055         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12056   case ISD::INTRINSIC_W_CHAIN:
12057     return AMDGPU::isIntrinsicSourceOfDivergence(
12058         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12059   case AMDGPUISD::ATOMIC_CMP_SWAP:
12060   case AMDGPUISD::ATOMIC_INC:
12061   case AMDGPUISD::ATOMIC_DEC:
12062   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12063   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12064   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12065   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12066   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12067   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12068   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12069   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12070   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12071   case AMDGPUISD::BUFFER_ATOMIC_AND:
12072   case AMDGPUISD::BUFFER_ATOMIC_OR:
12073   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12074   case AMDGPUISD::BUFFER_ATOMIC_INC:
12075   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12076   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12077   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12078   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12079   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12080   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12081     // Target-specific read-modify-write atomics are sources of divergence.
12082     return true;
12083   default:
12084     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12085       // Generic read-modify-write atomics are sources of divergence.
12086       return A->readMem() && A->writeMem();
12087     }
12088     return false;
12089   }
12090 }
12091 
12092 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12093                                                EVT VT) const {
12094   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12095   case MVT::f32:
12096     return hasFP32Denormals(DAG.getMachineFunction());
12097   case MVT::f64:
12098   case MVT::f16:
12099     return hasFP64FP16Denormals(DAG.getMachineFunction());
12100   default:
12101     return false;
12102   }
12103 }
12104 
12105 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12106                                                MachineFunction &MF) const {
12107   switch (Ty.getScalarSizeInBits()) {
12108   case 32:
12109     return hasFP32Denormals(MF);
12110   case 64:
12111   case 16:
12112     return hasFP64FP16Denormals(MF);
12113   default:
12114     return false;
12115   }
12116 }
12117 
12118 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12119                                                     const SelectionDAG &DAG,
12120                                                     bool SNaN,
12121                                                     unsigned Depth) const {
12122   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12123     const MachineFunction &MF = DAG.getMachineFunction();
12124     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12125 
12126     if (Info->getMode().DX10Clamp)
12127       return true; // Clamped to 0.
12128     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12129   }
12130 
12131   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12132                                                             SNaN, Depth);
12133 }
12134 
12135 // Global FP atomic instructions have a hardcoded FP mode and do not support
12136 // FP32 denormals, and only support v2f16 denormals.
12137 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12138   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12139   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12140   if (&Flt == &APFloat::IEEEsingle())
12141     return DenormMode == DenormalMode::getPreserveSign();
12142   return DenormMode == DenormalMode::getIEEE();
12143 }
12144 
12145 TargetLowering::AtomicExpansionKind
12146 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12147   switch (RMW->getOperation()) {
12148   case AtomicRMWInst::FAdd: {
12149     Type *Ty = RMW->getType();
12150 
12151     // We don't have a way to support 16-bit atomics now, so just leave them
12152     // as-is.
12153     if (Ty->isHalfTy())
12154       return AtomicExpansionKind::None;
12155 
12156     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12157       return AtomicExpansionKind::CmpXChg;
12158 
12159     unsigned AS = RMW->getPointerAddressSpace();
12160 
12161     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12162          Subtarget->hasAtomicFaddInsts()) {
12163       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12164       // floating point atomic instructions. May generate more efficient code,
12165       // but may not respect rounding and denormal modes, and may give incorrect
12166       // results for certain memory destinations.
12167       if (RMW->getFunction()
12168               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12169               .getValueAsString() != "true")
12170         return AtomicExpansionKind::CmpXChg;
12171 
12172       if (Subtarget->hasGFX90AInsts()) {
12173         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12174           return AtomicExpansionKind::CmpXChg;
12175 
12176         auto SSID = RMW->getSyncScopeID();
12177         if (SSID == SyncScope::System ||
12178             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12179           return AtomicExpansionKind::CmpXChg;
12180 
12181         return AtomicExpansionKind::None;
12182       }
12183 
12184       if (AS == AMDGPUAS::FLAT_ADDRESS)
12185         return AtomicExpansionKind::CmpXChg;
12186 
12187       return RMW->use_empty() ? AtomicExpansionKind::None
12188                               : AtomicExpansionKind::CmpXChg;
12189     }
12190 
12191     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12192     // to round-to-nearest-even.
12193     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12194     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
12195       if (!Ty->isDoubleTy())
12196         return AtomicExpansionKind::None;
12197 
12198       return (fpModeMatchesGlobalFPAtomicMode(RMW) ||
12199               RMW->getFunction()
12200                       ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12201                       .getValueAsString() == "true")
12202                  ? AtomicExpansionKind::None
12203                  : AtomicExpansionKind::CmpXChg;
12204     }
12205 
12206     return AtomicExpansionKind::CmpXChg;
12207   }
12208   default:
12209     break;
12210   }
12211 
12212   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12213 }
12214 
12215 const TargetRegisterClass *
12216 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12217   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12218   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12219   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12220     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12221                                                : &AMDGPU::SReg_32RegClass;
12222   if (!TRI->isSGPRClass(RC) && !isDivergent)
12223     return TRI->getEquivalentSGPRClass(RC);
12224   else if (TRI->isSGPRClass(RC) && isDivergent)
12225     return TRI->getEquivalentVGPRClass(RC);
12226 
12227   return RC;
12228 }
12229 
12230 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12231 // uniform values (as produced by the mask results of control flow intrinsics)
12232 // used outside of divergent blocks. The phi users need to also be treated as
12233 // always uniform.
12234 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12235                       unsigned WaveSize) {
12236   // FIXME: We asssume we never cast the mask results of a control flow
12237   // intrinsic.
12238   // Early exit if the type won't be consistent as a compile time hack.
12239   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12240   if (!IT || IT->getBitWidth() != WaveSize)
12241     return false;
12242 
12243   if (!isa<Instruction>(V))
12244     return false;
12245   if (!Visited.insert(V).second)
12246     return false;
12247   bool Result = false;
12248   for (auto U : V->users()) {
12249     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12250       if (V == U->getOperand(1)) {
12251         switch (Intrinsic->getIntrinsicID()) {
12252         default:
12253           Result = false;
12254           break;
12255         case Intrinsic::amdgcn_if_break:
12256         case Intrinsic::amdgcn_if:
12257         case Intrinsic::amdgcn_else:
12258           Result = true;
12259           break;
12260         }
12261       }
12262       if (V == U->getOperand(0)) {
12263         switch (Intrinsic->getIntrinsicID()) {
12264         default:
12265           Result = false;
12266           break;
12267         case Intrinsic::amdgcn_end_cf:
12268         case Intrinsic::amdgcn_loop:
12269           Result = true;
12270           break;
12271         }
12272       }
12273     } else {
12274       Result = hasCFUser(U, Visited, WaveSize);
12275     }
12276     if (Result)
12277       break;
12278   }
12279   return Result;
12280 }
12281 
12282 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12283                                                const Value *V) const {
12284   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12285     if (CI->isInlineAsm()) {
12286       // FIXME: This cannot give a correct answer. This should only trigger in
12287       // the case where inline asm returns mixed SGPR and VGPR results, used
12288       // outside the defining block. We don't have a specific result to
12289       // consider, so this assumes if any value is SGPR, the overall register
12290       // also needs to be SGPR.
12291       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12292       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12293           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12294       for (auto &TC : TargetConstraints) {
12295         if (TC.Type == InlineAsm::isOutput) {
12296           ComputeConstraintToUse(TC, SDValue());
12297           unsigned AssignedReg;
12298           const TargetRegisterClass *RC;
12299           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12300               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12301           if (RC) {
12302             MachineRegisterInfo &MRI = MF.getRegInfo();
12303             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12304               return true;
12305             else if (SIRI->isSGPRClass(RC))
12306               return true;
12307           }
12308         }
12309       }
12310     }
12311   }
12312   SmallPtrSet<const Value *, 16> Visited;
12313   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12314 }
12315 
12316 std::pair<InstructionCost, MVT>
12317 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12318                                           Type *Ty) const {
12319   std::pair<InstructionCost, MVT> Cost =
12320       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12321   auto Size = DL.getTypeSizeInBits(Ty);
12322   // Maximum load or store can handle 8 dwords for scalar and 4 for
12323   // vector ALU. Let's assume anything above 8 dwords is expensive
12324   // even if legal.
12325   if (Size <= 256)
12326     return Cost;
12327 
12328   Cost.first = (Size + 255) / 256;
12329   return Cost;
12330 }
12331